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
qdrant__qdrant-client
qdrant_client/http/api/snapshots_api.py
{ "start": 1315, "end": 14184 }
class ____: def __init__(self, api_client: "Union[ApiClient, AsyncApiClient]"): self.api_client = api_client def _build_for_create_full_snapshot( self, wait: bool = None, ): """ Create new snapshot of the whole storage """ query_params = {} if...
_SnapshotsApi
python
facebookresearch__faiss
tests/test_build_blocks.py
{ "start": 15554, "end": 16922 }
class ____(unittest.TestCase): def do_test(self, ismax, dtype): rs = np.random.RandomState() n, k, nshard = 10, 5, 3 all_ids = rs.randint(100000, size=(nshard, n, k)).astype('int64') all_dis = rs.rand(nshard, n, k) if dtype == 'int32': all_dis = (all_dis * 100000...
TestMergeKNNResults
python
PyCQA__pylint
tests/functional/u/unsupported/unsupported_assignment_operation.py
{ "start": 1894, "end": 1991 }
class ____(type): def __setitem__(cls, key, value): return key + value
MetaSubscriptable
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/compute.py
{ "start": 1611, "end": 1884 }
class ____(BaseGoogleLink): """Helper class for constructing Compute Instance Template details Link.""" name = "Compute Instance Template details" key = "compute_instance_template_details" format_str = COMPUTE_TEMPLATE_LINK
ComputeInstanceTemplateDetailsLink
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 817096, "end": 817543 }
class ____(VegaLiteSchema): """ OrderOnlyDef schema wrapper. Parameters ---------- sort : :class:`SortOrder`, Literal['ascending', 'descending'] The sort order. One of ``"ascending"`` (default) or ``"descending"``. """ _schema = {"$ref": "#/definitions/OrderOnlyDef"} def __ini...
OrderOnlyDef
python
huggingface__transformers
src/transformers/models/lilt/modeling_lilt.py
{ "start": 36481, "end": 37270 }
class ____(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None ...
LiltClassificationHead
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/required1.py
{ "start": 1038, "end": 1275 }
class ____: # This should generate an error because Required can't be # used in this context. x: Required[int] # This should generate an error because NotRequired can't be # used in this context. y: Required[int]
Foo
python
doocs__leetcode
solution/2200-2299/2259.Remove Digit From Number to Maximize Result/Solution.py
{ "start": 0, "end": 190 }
class ____: def removeDigit(self, number: str, digit: str) -> str: return max( number[:i] + number[i + 1 :] for i, d in enumerate(number) if d == digit )
Solution
python
pypa__pipenv
pipenv/patched/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 11523, "end": 12205 }
class ____(_InstallRequirementBackedCandidate): is_editable = True def __init__( self, link: Link, template: InstallRequirement, factory: "Factory", name: Optional[NormalizedName] = None, version: Optional[Version] = None, ) -> None: super().__init__(...
EditableCandidate
python
Lightning-AI__lightning
tests/tests_pytorch/loops/test_fetchers.py
{ "start": 9246, "end": 10932 }
class ____(BoringModel): def __init__(self) -> None: super().__init__() self.automatic_optimization = False self.batch_i_handle = None self.num_batches_processed = 0 def _async_op(self, batch: Any) -> DummyWaitable: return DummyWaitable(val=batch) def training_step(...
AsyncBoringModel
python
huggingface__transformers
src/transformers/models/align/modeling_align.py
{ "start": 11014, "end": 12390 }
class ____(nn.Module): r""" This corresponds to the Squeeze and Excitement phase of each block in the original implementation. """ def __init__(self, config: AlignVisionConfig, in_dim: int, expand_dim: int, expand: bool = False): super().__init__() self.dim = expand_dim if expand else i...
AlignVisionSqueezeExciteLayer
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP044.py
{ "start": 82, "end": 126 }
class ____(Generic[Unpack[Shape]]): pass
C
python
apache__airflow
airflow-ctl/src/airflowctl/api/operations.py
{ "start": 24519, "end": 26572 }
class ____(BaseOperations): """Variable operations.""" def get(self, variable_key: str) -> VariableResponse | ServerResponseError: """Get a variable.""" try: self.response = self.client.get(f"variables/{variable_key}") return VariableResponse.model_validate_json(self.res...
VariablesOperations
python
numba__llvmlite
llvmlite/ir/values.py
{ "start": 22912, "end": 23594 }
class ____(set): """A set of string attribute. Only accept items listed in *_known*. Properties: * Iterate in sorted order """ _known = () def __init__(self, args=()): super().__init__() if isinstance(args, str): args = [args] for name in args: ...
AttributeSet
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_pubmed_id.py
{ "start": 483, "end": 1599 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_pubmed_id" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(...
ColumnValuesToBeValidPubmedId
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_v3.py
{ "start": 5819, "end": 7342 }
class ____(saveable_object.SaveableObject): """Defines how to save and restore a shard of TPUEmbedding sharded variable.""" def __init__( self, variable: tf_variables.Variable, shard_id: int, num_shards: int, shard_dim: int, name: str, ): """Init TPUEmbeddingShardedSaveabl...
TPUEmbeddingShardedSaveable
python
gevent__gevent
src/greentest/3.12/test_ssl.py
{ "start": 203872, "end": 214902 }
class ____(unittest.TestCase): """Verify behavior of close sockets with received data before to the handshake. """ class SingleConnectionTestServerThread(threading.Thread): def __init__(self, *, name, call_after_accept, timeout=None): self.call_after_accept = call_after_accept ...
TestPreHandshakeClose
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 10677, "end": 10811 }
class ____(tuple[*Ts]): def __new__(cls: type[Generic3]) -> Generic3: ... def __enter__(self: Generic3) -> Generic3: ...
Generic3
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 29646, "end": 34520 }
class ____(TestCase): def setUp(self): self.renderer = AdminRenderer() def test_render_when_resource_created(self): class DummyView(APIView): renderer_classes = (AdminRenderer, ) request = Request(HttpRequest()) request.build_absolute_uri = lambda: 'http://example.c...
AdminRendererTests
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/pagination.py
{ "start": 1752, "end": 2312 }
class ____: """ Cursor class useful for paginating results based on a last seen value. """ value: Any def __str__(self) -> str: return self.to_string() def to_string(self) -> str: string_serialized = serialize_value(self) return base64.b64encode(bytes(string_serialized...
ValueIndexCursor
python
getsentry__sentry
src/sentry/integrations/base.py
{ "start": 2192, "end": 3429 }
class ____(NamedTuple): description: str | _StrPromise # A markdown description of the integration features: Sequence[FeatureDescription] # A list of FeatureDescriptions author: str # The integration author's name noun: str | _StrPromise # The noun used to identify the integration issue_url: str...
IntegrationMetadata
python
has2k1__plotnine
plotnine/scales/scale_color.py
{ "start": 8136, "end": 8290 }
class ____(scale_color_gradient2): """ Create a 3 point diverging color gradient """ _aesthetics = ["fill"] @dataclass
scale_fill_gradient2
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_custom_job.py
{ "start": 7527, "end": 12075 }
class ____: def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_no_default_project_id ): self.hook = CustomJobHook(gcp_conn_id=TEST_GCP_CONN_ID) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobHook.get_pipeline_se...
TestCustomJobWithoutDefaultProjectIdHook
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/pyodbc.py
{ "start": 18929, "end": 19002 }
class ____(_ODBCDateTimeBindProcessor, _MSDateTime): pass
_ODBCDateTime
python
numpy__numpy
numpy/lib/tests/test_shape_base.py
{ "start": 20397, "end": 21054 }
class ____: """Only testing for integer splits. """ def test_non_iterable(self): assert_raises(ValueError, vsplit, 1, 1) def test_0D_array(self): a = np.array(1) assert_raises(ValueError, vsplit, a, 2) def test_1D_array(self): a = np.array([1, 2, 3, 4]) try...
TestVsplit
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/templates/render.py
{ "start": 1372, "end": 2873 }
class ____: column: str title: str formatter: Optional[Callable[[Any], str]] = None def dataframe_to_table_html(df: pd.DataFrame, column_mapping: List[ColumnInfo]) -> str: """ Convert a dataframe to an HTML table. """ # convert true and false to checkmarks and x's df.replace({True: "✅...
ColumnInfo
python
HypothesisWorks__hypothesis
hypothesis-python/tests/attrs/test_pretty.py
{ "start": 1177, "end": 1710 }
class ____: a: int b: int c: int d: int e: int f: int g: int h: int i: int j: int k: int l: int m: int n: int o: int p: int q: int r: int s: int def test_will_line_break_between_fields(): obj = SomeAttrsClassWithLotsOfFields( **{ ...
SomeAttrsClassWithLotsOfFields
python
scipy__scipy
scipy/integrate/_rules/_base.py
{ "start": 9001, "end": 12275 }
class ____(FixedRule): r""" A cubature rule with error estimate given by the difference between two underlying fixed rules. If constructed as ``NestedFixedRule(higher, lower)``, this will use:: estimate(f, a, b) := higher.estimate(f, a, b) estimate_error(f, a, b) := \|higher.estimate(f...
NestedFixedRule
python
getsentry__sentry
src/sentry/db/models/fields/bounded.py
{ "start": 1764, "end": 2019 }
class ____(models.AutoField): MAX_VALUE = I32_MAX def get_prep_value(self, value: int) -> int: if value: value = int(value) assert value <= self.MAX_VALUE return super().get_prep_value(value)
BoundedAutoField
python
pytest-dev__pytest-xdist
testing/acceptance_test.py
{ "start": 12284, "end": 13608 }
class ____: def test_simple(self, pytester: pytest.Pytester) -> None: pytester.makepyfile( """ def test_hello(): pass """ ) result = pytester.runpytest_subprocess("--debug", "--dist=each", "--tx=2*popen") assert not result.ret r...
TestDistEach
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 21435, "end": 22593 }
class ____(RenderedComponentContent): def __init__( self, text, header=None, subheader=None, styling=None, content_block_type="text" ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.text = text self.header = header self.subheader = ...
TextContent
python
huggingface__transformers
src/transformers/models/dinat/modeling_dinat.py
{ "start": 22409, "end": 25305 }
class ____(DinatPreTrainedModel): def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) requires_backends(self, ["natten"]) self.conf...
DinatModel
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/black/cases/torture.py
{ "start": 330, "end": 1044 }
class ____: def foo(self): for _ in range(10): aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc( # pylint: disable=no-member xxxxxxxxxxxx ) def test(self, othr): return (1 == 2 and (name, description, self.default, self.selected, self.auto_generated,...
A
python
PyCQA__pylint
tests/functional/n/non/non_iterator_returned.py
{ "start": 1103, "end": 1253 }
class ____: """__iter__ returns a class which uses an iterator-metaclass.""" def __iter__(self): return IteratorClass
FifthGoodIterator
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 20022, "end": 20162 }
class ____(DagsterUserCodeExecutionError): """Errors raised in a user process during the loading of user code."""
DagsterUserCodeLoadError
python
allegroai__clearml
clearml/utilities/pyhocon/config_parser.py
{ "start": 29631, "end": 29986 }
class ____(TokenConverter): def __init__(self, expr=None): super(ConcatenatedValueParser, self).__init__(expr) self.parent = None self.key = None def postParse(self, instring, loc, token_list): config_values = ConfigValues(token_list, instring, loc) return [config_values...
ConcatenatedValueParser
python
spyder-ide__spyder
spyder/plugins/shortcuts/widgets/table.py
{ "start": 4839, "end": 17727 }
class ____(QDialog): """A dialog for entering key sequences.""" def __init__(self, parent, context, name, sequence, shortcuts): super().__init__(parent) self._parent = parent self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint) s...
ShortcutEditor
python
Farama-Foundation__Gymnasium
gymnasium/spaces/text.py
{ "start": 337, "end": 9681 }
class ____(Space[str]): r"""A space representing a string comprised of characters from a given charset. Example: >>> from gymnasium.spaces import Text >>> # {"", "B5", "hello", ...} >>> Text(5) Text(1, 5, charset=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz) ...
Text
python
graphql-python__graphene
graphene/relay/tests/test_custom_global_id.py
{ "start": 224, "end": 2491 }
class ____: def setup_method(self): self.user_list = [ {"id": uuid4(), "name": "First"}, {"id": uuid4(), "name": "Second"}, {"id": uuid4(), "name": "Third"}, {"id": uuid4(), "name": "Fourth"}, ] self.users = {user["id"]: user for user in self.u...
TestUUIDGlobalID
python
scrapy__scrapy
tests/spiders.py
{ "start": 1754, "end": 2306 }
class ____(MetaSpider): name = "delay" def __init__(self, n=1, b=0, *args, **kwargs): super().__init__(*args, **kwargs) self.n = n self.b = b self.t1 = self.t2 = self.t2_err = 0 async def start(self): self.t1 = time.time() url = self.mockserver.url(f"/delay?...
DelaySpider
python
ansible__ansible
lib/ansible/errors/__init__.py
{ "start": 7018, "end": 7133 }
class ____(AnsibleParserError): """Errors caused during field attribute processing."""
AnsibleFieldAttributeError
python
python-poetry__poetry
tests/integration/test_utils_vcs_git.py
{ "start": 1088, "end": 13908 }
class ____(TypedDict): name: str | None branch: str | None tag: str | None revision: str | None source_root: Path | None clean: bool @pytest.fixture(autouse=True) def git_mock() -> None: pass @pytest.fixture(autouse=True) def setup(config: Config) -> None: pass REVISION_TO_VERSION_...
GitCloneKwargs
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/step_function.py
{ "start": 1105, "end": 2685 }
class ____(AwsBaseWaiterTrigger): """ Trigger to poll for the completion of a Step Functions execution. :param execution_arn: ARN of the state machine to poll :param waiter_delay: The amount of time in seconds to wait between attempts. :param waiter_max_attempts: The maximum number of attempts to b...
StepFunctionsExecutionCompleteTrigger
python
PyCQA__pylint
tests/functional/c/consider/consider_using_with_open.py
{ "start": 2453, "end": 5862 }
class ____: """ The message is triggered if a context manager is assigned to a variable, which name is later reassigned without the variable being used inside a ``with`` first. E.g. the following would trigger the message: a = open("foo") # <-- would trigger here a = "something new" ...
TestControlFlow
python
run-llama__llama_index
llama-index-core/llama_index/core/tools/query_plan.py
{ "start": 2550, "end": 8216 }
class ____(BaseTool): """ Query plan tool. A tool that takes in a list of tools and executes a query plan. """ def __init__( self, query_engine_tools: List[BaseTool], response_synthesizer: BaseSynthesizer, name: str, description_prefix: str, ) -> None: ...
QueryPlanTool
python
jupyterlab__jupyterlab
jupyterlab/labextensions.py
{ "start": 8482, "end": 9601 }
class ____(BaseExtensionApp): description = "(developer) Build labextension" static_url = Unicode("", config=True, help="Sets the url for static assets when building") development = Bool(False, config=True, help="Build in development mode") source_map = Bool(False, config=True, help="Generate source ...
BuildLabExtensionApp
python
pytorch__pytorch
torchgen/gen.py
{ "start": 30358, "end": 38069 }
class ____: @method_with_native_function def __call__(self, f: NativeFunction) -> str | None: # We unconditionally generate function variants of the redispatch API. # This is mainly because we can namespace functions separately, but not methods, sig_group = CppSignatureGroup.from_native_...
ComputeRedispatchFunction
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 156713, "end": 167631 }
class ____(ReplicaContextBase): __doc__ = ReplicaContextBase.__doc__ def all_gather(self, value, axis, options=None): """All-gathers `value` across all replicas along `axis`. Note: An `all_gather` method can only be called in replica context. For a cross-replica context counterpart, see `tf.distribut...
ReplicaContext
python
modin-project__modin
asv_bench/benchmarks/io/csv.py
{ "start": 1478, "end": 2275 }
class ____(BaseReadCsv): shapes = get_benchmark_shapes("TimeReadCsvSkiprows") skiprows_mapping = { "lambda_even_rows": lambda x: x % 2, "range_uniform": np.arange(1, shapes[0][0] // 10), "range_step2": np.arange(1, shapes[0][0], 2), } data_type = "str_int" param_names = ["sh...
TimeReadCsvSkiprows
python
doocs__leetcode
solution/2100-2199/2111.Minimum Operations to Make the Array K-Increasing/Solution.py
{ "start": 0, "end": 392 }
class ____: def kIncreasing(self, arr: List[int], k: int) -> int: def lis(arr): t = [] for x in arr: idx = bisect_right(t, x) if idx == len(t): t.append(x) else: t[idx] = x return len(...
Solution
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_views.py
{ "start": 683, "end": 4078 }
class ____(TestCase): fixtures = ["eric", "test_data"] def assertRedirectToLogin(self, response): self.assertEqual(response.status_code, 302) url = response["Location"] e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(url) self.assertEqual(e_path, reverse("account_logi...
PrivateViewsAreProtectedTests
python
charliermarsh__ruff
python/ruff-ecosystem/ruff_ecosystem/format.py
{ "start": 8780, "end": 9512 }
class ____(Enum): ruff_then_ruff = "ruff-then-ruff" """ Run Ruff baseline then Ruff comparison; checks for changes in behavior when formatting previously "formatted" code """ ruff_and_ruff = "ruff-and-ruff" """ Run Ruff baseline then reset and run Ruff comparison; checks changes in behavior...
FormatComparison
python
kamyu104__LeetCode-Solutions
Python/non-decreasing-array.py
{ "start": 29, "end": 667 }
class ____(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ modified, prev = False, nums[0] for i in xrange(1, len(nums)): if prev > nums[i]: if modified: return False ...
Solution
python
django__django
tests/admin_docs/models.py
{ "start": 773, "end": 2759 }
class ____(models.Model): """ Stores information about a person, related to :model:`myapp.Company`. **Notes** Use ``save_changes()`` when saving this object. ``company`` Field storing :model:`myapp.Company` where the person works. (DESCRIPTION) .. raw:: html :file: admin...
Person
python
getsentry__sentry
src/sentry/eventstream/snuba.py
{ "start": 16278, "end": 21694 }
class ____(SnubaProtocolEventStream): def _send( self, project_id: int, _type: str, extra_data: tuple[Any, ...] = (), asynchronous: bool = True, headers: MutableMapping[str, str] | None = None, skip_semantic_partitioning: bool = False, event_type: Even...
SnubaEventStream
python
numba__numba
numba/tests/test_parallel_backend.py
{ "start": 41581, "end": 42150 }
class ____(TestCase): def test_vendors(self): """ Checks the OpenMP vendor strings are correct """ expected = dict() expected['win32'] = "MS" expected['darwin'] = "Intel" expected['linux'] = "GNU" # only check OS that are supported, custom toolchains...
TestOpenMPVendors
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py
{ "start": 1488, "end": 3088 }
class ____(FBMarketingStream): """AdCreative is append-only stream doc: https://developers.facebook.com/docs/marketing-api/reference/ad-creative """ entity_prefix = "adcreative" def __init__(self, fetch_thumbnail_images: bool = False, **kwargs): super().__init__(**kwargs) self._fet...
AdCreatives
python
scipy__scipy
scipy/stats/tests/test_resampling.py
{ "start": 59327, "end": 92213 }
class ____: rtol = 1e-14 def setup_method(self): self.rng = np.random.default_rng(7170559330470561044) # -- Input validation -- # def test_permutation_test_iv(self, xp): def stat(x, y, axis): return stats.ttest_ind((x, y), axis).statistic data = (xp.asarray([1, 2...
TestPermutationTest
python
plotly__plotly.py
plotly/graph_objs/parcats/line/_colorbar.py
{ "start": 233, "end": 61588 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcats.line" _path_str = "parcats.line.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent...
ColorBar
python
doocs__leetcode
solution/0700-0799/0763.Partition Labels/Solution.py
{ "start": 0, "end": 326 }
class ____: def partitionLabels(self, s: str) -> List[int]: last = {c: i for i, c in enumerate(s)} mx = j = 0 ans = [] for i, c in enumerate(s): mx = max(mx, last[c]) if mx == i: ans.append(i - j + 1) j = i + 1 return an...
Solution
python
sympy__sympy
sympy/plotting/tests/test_plot.py
{ "start": 1807, "end": 48217 }
class ____(Plot): """ Used to verify if users can create their own backends. This backend is meant to pass all tests. """ def __new__(cls, *args, **kwargs): return object.__new__(cls) def show(self): pass def save(self): pass def close(self): pass def test...
DummyBackendOk
python
PyCQA__pylint
tests/functional/r/regression/regression_3535_double_enum_inherit.py
{ "start": 144, "end": 203 }
class ____(A): x = enum.auto() print(B.__members__['x'])
B
python
gevent__gevent
src/greentest/3.10/test_smtpd.py
{ "start": 318, "end": 944 }
class ____(smtpd.SMTPServer): def __init__(self, *args, **kwargs): smtpd.SMTPServer.__init__(self, *args, **kwargs) self.messages = [] if self._decode_data: self.return_status = 'return status' else: self.return_status = b'return status' def process_messa...
DummyServer
python
mitmproxy__pdoc
test/testdata/mermaid_demo.py
{ "start": 556, "end": 645 }
class ____(Pet): """🐕""" def bark(self, loud: bool = True): """*woof*"""
Dog
python
great-expectations__great_expectations
contrib/time_series_expectations/time_series_expectations/generator/weekly_time_series_generator.py
{ "start": 255, "end": 3409 }
class ____(DailyTimeSeriesGenerator): """Generate a weekly time series with trend, seasonality, and outliers.""" def generate_df( self, size: Optional[int] = 52 * 3, day_of_week: Optional[int] = 0, start_date: Optional[str] = "2018-01-01", trend_params: Optional[List[Tre...
WeeklyTimeSeriesGenerator
python
openai__openai-python
src/openai/resources/beta/threads/threads.py
{ "start": 46832, "end": 91849 }
class ____(AsyncAPIResource): @cached_property def runs(self) -> AsyncRuns: return AsyncRuns(self._client) @cached_property def messages(self) -> AsyncMessages: return AsyncMessages(self._client) @cached_property def with_raw_response(self) -> AsyncThreadsWithRawResponse: ...
AsyncThreads
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 47380, "end": 50253 }
class ____(Interface): """An introspectable object used for configuration introspection. In addition to the methods below, objects which implement this interface must also implement all the methods of Python's ``collections.MutableMapping`` (the "dictionary interface"), and must be hashable.""" ...
IIntrospectable
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py
{ "start": 2033, "end": 2449 }
class ____: # -> generic_method[T: float](t: T) def generic_method(t: T) -> T: return t # This one is strange in particular because of the mix of old- and new-style # generics, but according to the PEP, this is okay "if the class, function, or # type alias does not use the new syntax." `more_generic` ...
NotGeneric
python
Textualize__textual
tests/command_palette/test_click_away.py
{ "start": 303, "end": 792 }
class ____(App[None]): COMMANDS = {SimpleSource} def on_mount(self) -> None: self.action_command_palette() async def test_clicking_outside_command_palette_closes_it() -> None: """Clicking 'outside' the command palette should make it go away.""" async with CommandPaletteApp().run_test() as pil...
CommandPaletteApp
python
paramiko__paramiko
demos/forward.py
{ "start": 1507, "end": 7254 }
class ____(SocketServer.BaseRequestHandler): def handle(self): try: chan = self.ssh_transport.open_channel( "direct-tcpip", (self.chain_host, self.chain_port), self.request.getpeername(), ) except Exception as e: ver...
Handler
python
tensorflow__tensorflow
tensorflow/lite/python/tflite_convert_test.py
{ "start": 1900, "end": 4057 }
class ____(test_util.TensorFlowTestCase): def _getFilepath(self, filename): return os.path.join(self.get_temp_dir(), filename) def _run(self, flags_str, should_succeed, expected_ops_in_converted_model=None, expected_output_shapes=None): output_file = os.path.joi...
TestModels
python
huggingface__transformers
src/transformers/models/xlm_roberta/modeling_xlm_roberta.py
{ "start": 10662, "end": 12072 }
class ____(nn.Module): def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False): super().__init__() self.is_cross_attention = is_cross_attention attention_class = XLMRobertaCrossAttention if is_cross_attention else XLMRobertaSelfAttention self.self = atte...
XLMRobertaAttention
python
pytorch__pytorch
torchgen/model.py
{ "start": 48311, "end": 49651 }
class ____: name: str supported_dtypes: OrderedSet[ScalarType] # key is stored here because it affects the semantics of name, # so its helpful to have them together for further processing ufunc_key: UfuncKey @staticmethod def parse(value: str, ufunc_key: UfuncKey) -> UfuncInnerLoop: ...
UfuncInnerLoop
python
django__django
tests/utils_tests/test_os_utils.py
{ "start": 161, "end": 846 }
class ____(unittest.TestCase): def test_base_path_ends_with_sep(self): drive, path = os.path.splitdrive(safe_join("/abc/", "abc")) self.assertEqual(path, "{0}abc{0}abc".format(os.path.sep)) def test_root_path(self): drive, path = os.path.splitdrive(safe_join("/", "path")) self.a...
SafeJoinTests
python
pydantic__pydantic
tests/benchmarks/basemodel_eq_performance.py
{ "start": 6120, "end": 6554 }
class ____(Generic[K, V]): """Wrapper redirecting `__getitem__` to `get` and a sentinel value This makes is safe to use in `operator.itemgetter` when some keys may be missing """ wrapped: dict[K, V] def __getitem__(self, key: K, /) -> V | _SentinelType: return self.wrapped.get(key, _SENTI...
_SafeGetItemProxy
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_test.py
{ "start": 189237, "end": 191336 }
class ____(test.TestCase): # All transform tests are distributed in column test. # Here we only test multi column case and naming def transform_multi_column(self): bucketized_price = fc._bucketized_column( fc._numeric_column('price'), boundaries=[0, 2, 4, 6]) hashed_sparse = fc._categorical_colum...
TransformFeaturesTest
python
kamyu104__LeetCode-Solutions
Python/2-keys-keyboard.py
{ "start": 35, "end": 424 }
class ____(object): def minSteps(self, n): """ :type n: int :rtype: int """ result = 0 p = 2 # the answer is the sum of prime factors while p**2 <= n: while n % p == 0: result += p n //= p p += 1 ...
Solution
python
fluentpython__example-code-2e
24-class-metaprog/slots/slots_timing.py
{ "start": 711, "end": 850 }
class ____(metaclass=Correct2): pass o = Klass2() try: o.z = 3 except AttributeError as e: print('Raised as expected:', e)
Klass2
python
getsentry__sentry
tests/sentry/preprod/api/endpoints/test_project_preprod_artifact_install_details.py
{ "start": 352, "end": 7020 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.file = self.create_file( name="test_installable.ipa", type="application/octet-stream", ) self.login_as(user=self.user) def _get_url(self, artifact_id=None): artifact_id = artifact...
ProjectPreprodInstallDetailsEndpointTest
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tfr/python/tfr_gen.py
{ "start": 7860, "end": 11880 }
class ____(object): """A Dict to cache the OpDef for the Python function name.""" def __init__(self): self._op_defs = {} def lookup(self, f_name, func_def=None, optional=False): if f_name in self._op_defs: return self._op_defs[f_name] if isinstance(func_def, types.FunctionType): if not ...
OpDefCache
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/deprecated_versions/package.py
{ "start": 216, "end": 639 }
class ____(Package): """Package with the most recent version deprecated""" homepage = "http://www.example.com" url = "http://www.example.com/c-1.0.tar.gz" version( "1.1.0", sha256="abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", deprecated=True, ) ver...
DeprecatedVersions
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/activities.py
{ "start": 930, "end": 1078 }
class ____(BaseModel): ti: TaskInstance path: os.PathLike[str] token: str """The identity token for this workload"""
ExecuteTaskActivity
python
django__django
django/db/models/fields/related.py
{ "start": 54116, "end": 83729 }
class ____(RelatedField): """ Provide a many-to-many relation by using an intermediary model that holds two ForeignKey fields pointed at the two sides of the relation. Unless a ``through`` model was provided, ManyToManyField will use the create_many_to_many_intermediary_model factory to automatical...
ManyToManyField
python
getsentry__sentry
src/sentry/replays/usecases/ingest/__init__.py
{ "start": 2322, "end": 3430 }
class ____(msgspec.Struct, gc=False, tag_field="type", tag=5): data: CustomEventData | None = None RRWebEvent = ( DomContentLoadedEvent | LoadedEvent | FullSnapshotEvent | IncrementalSnapshotEvent | MetaEvent | CustomEvent | PluginEvent ) def parse_recording_data(payload: bytes) -> l...
CustomEvent
python
openai__openai-python
src/openai/types/beta/realtime/transcription_session_update.py
{ "start": 428, "end": 801 }
class ____(BaseModel): anchor: Optional[Literal["created_at"]] = None """The anchor point for the ephemeral token expiration. Only `created_at` is currently supported. """ seconds: Optional[int] = None """The number of seconds from the anchor point to the expiration. Select a value betwee...
SessionClientSecretExpiresAt
python
spyder-ide__spyder
spyder/plugins/pylint/confpage.py
{ "start": 594, "end": 2566 }
class ____(PluginConfigPage): def setup_page(self): settings_group = QGroupBox(_("Settings")) save_box = self.create_checkbox(_("Save file before analyzing it"), 'save_before', default=True) hist_group = QGroupBox(_("History")) hist_label1 = ...
PylintConfigPage
python
weaviate__weaviate-python-client
weaviate/users/base.py
{ "start": 553, "end": 3866 }
class ____(Generic[ConnectionType]): def __init__(self, connection: ConnectionType): self._connection = connection def _get_roles_of_user( self, user_id: str, user_type: USER_TYPE, include_permissions: bool, ) -> executor.Result[Union[Dict[str, Role], Dict[str, RoleB...
_BaseExecutor
python
kubernetes-client__python
kubernetes/client/models/v1_rolling_update_stateful_set_strategy.py
{ "start": 383, "end": 6231 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1RollingUpdateStatefulSetStrategy
python
virgili0__Virgilio
Tools/regex-bin/regexPrinter.py
{ "start": 1983, "end": 2420 }
class ____(TreeNode): def __init__(self, token, value, quantifier, value_range, next_node): TreeNode.__init__(self, token, value, next_node) self.quantifier = quantifier self.value_range = value_range def print(self): printer = self.quantifier.get_printer(self.value_range) ...
ChooseNode
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_events_writer_test.py
{ "start": 25237, "end": 28784 }
class ____(dumping_callback_test_lib.DumpingCallbackTestBase): """Test for DebugDataReader for multiple file sets under a dump root.""" def testReadingTwoFileSetsWithTheSameDumpRootSucceeds(self): # To simulate a multi-host data dump, we first generate file sets in two # different directories, with the sam...
MultiSetReaderTest
python
matplotlib__matplotlib
lib/matplotlib/widgets.py
{ "start": 34474, "end": 45531 }
class ____(AxesWidget): r""" A GUI neutral set of check buttons. For the check buttons to remain responsive you must keep a reference to this object. Connect to the CheckButtons with the `.on_clicked` method. Attributes ---------- ax : `~matplotlib.axes.Axes` The parent Axes f...
CheckButtons
python
Textualize__textual
docs/examples/tutorial/stopwatch02.py
{ "start": 167, "end": 240 }
class ____(Digits): """A widget to display elapsed time."""
TimeDisplay
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 171014, "end": 171238 }
class ____(SendrecvmsgConnectedBase, ConnectedStreamTestMixin, UnixStreamBase): pass @requireAttrs(socket.socket, "sendmsg") @requireAttrs(socket, "AF_UNIX")
SendrecvmsgUnixStreamTestBase
python
huggingface__transformers
tests/test_feature_extraction_common.py
{ "start": 697, "end": 2215 }
class ____: test_cast_dtype = None def test_feat_extract_to_json_string(self): feat_extract = self.feature_extraction_class(**self.feat_extract_dict) obj = json.loads(feat_extract.to_json_string()) for key, value in self.feat_extract_dict.items(): self.assertEqual(obj[key], ...
FeatureExtractionSavingTestMixin
python
getsentry__sentry
tests/sentry/integrations/aws_lambda/test_utils.py
{ "start": 7837, "end": 9701 }
class ____(TestCase): """Test the get_node_options_for_layer function for different layer scenarios.""" def test_v7_layer_name(self) -> None: """Test SentryNodeServerlessSDKv7 returns v7 SDK options.""" result = get_node_options_for_layer("SentryNodeServerlessSDKv7", None) assert result...
GetNodeOptionsForLayerTest
python
getsentry__sentry
src/sentry/monitors/processing_errors/errors.py
{ "start": 3845, "end": 4014 }
class ____(TypedDict): """ This monitor can't accept checkins and is over quota """ type: Literal[ProcessingErrorType.MONITOR_OVER_QUOTA]
MonitorOverQuota
python
mwaskom__seaborn
tests/test_rcmod.py
{ "start": 2310, "end": 5374 }
class ____(RCParamFixtures): styles = ["white", "dark", "whitegrid", "darkgrid", "ticks"] def test_default_return(self): current = rcmod.axes_style() self.assert_rc_params(current) def test_key_usage(self): _style_keys = set(rcmod._style_keys) for style in self.styles: ...
TestAxesStyle
python
eth-brownie__brownie
brownie/exceptions.py
{ "start": 2186, "end": 5310 }
class ____(Exception): """ Raised when a call to a contract causes an EVM exception. Attributes ---------- message : str The full error message received from the RPC client. revert_msg : str The returned error string, if any. revert_type : str The error type. pc ...
VirtualMachineError
python
scrapy__scrapy
tests/test_downloader_handler_twisted_http11.py
{ "start": 626, "end": 782 }
class ____: @property def download_handler_cls(self) -> type[DownloadHandlerProtocol]: return HTTP11DownloadHandler
HTTP11DownloadHandlerMixin
python
walkccc__LeetCode
solutions/1400. Construct K Palindrome Strings/1400.py
{ "start": 0, "end": 355 }
class ____: def canConstruct(self, s: str, k: int) -> bool: # If |s| < k, we cannot construct k strings from the s. # If the number of letters that have odd counts > k, the minimum number of # palindromic strings we can construct is > k. return sum(freq & 1 for freq in collections.Count...
Solution