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
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 31852, "end": 32262 }
class ____(TestBasicOps, TestCase): def setUp(self): super().setUp() self.case = "triple OrderedSet" self.values = [0, "zero", operator.add] self.OrderedSet = OrderedSet(self.values) self.dup = OrderedSet(self.values) self.length = 3 self.repr = None # -----...
TestBasicOpsTriple
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/run_handler.py
{ "start": 2449, "end": 9301 }
class ____: """Represents the run results of a dbt Cloud job run.""" run_id: int run_results: Mapping[str, Any] @classmethod def from_run_results_json(cls, run_results_json: Mapping[str, Any]) -> "DbtCloudJobRunResults": return cls( run_id=int(run_results_json["metadata"]["env"...
DbtCloudJobRunResults
python
great-expectations__great_expectations
great_expectations/expectations/expectation.py
{ "start": 85637, "end": 97348 }
class ____(BatchExpectation, ABC): """Base class for ColumnMapExpectations. ColumnMapExpectations are evaluated for a column and ask a yes/no question about every row in the column. Based on the result, they then calculate the percentage of rows that gave a positive answer. If the percentage is high en...
ColumnMapExpectation
python
jazzband__django-oauth-toolkit
oauth2_provider/views/application.py
{ "start": 281, "end": 581 }
class ____(LoginRequiredMixin): """ This mixin is used to provide an Application queryset filtered by the current request.user. """ fields = "__all__" def get_queryset(self): return get_application_model().objects.filter(user=self.request.user)
ApplicationOwnerIsUserMixin
python
numpy__numpy
numpy/random/tests/test_direct.py
{ "start": 5190, "end": 12280 }
class ____: dtype = np.uint64 data2 = data1 = {} @classmethod def setup_class(cls): cls.bit_generator = PCG64 cls.bits = 64 cls.dtype = np.uint64 cls.seed_error_type = TypeError cls.invalid_init_types = [] cls.invalid_init_values = [] @classmethod ...
Base
python
huggingface__transformers
tests/models/eomt/test_image_processing_eomt.py
{ "start": 1433, "end": 4024 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, min_resolution=30, max_resolution=400, size=None, do_resize=True, do_pad=True, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5...
EomtImageProcessingTester
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/asb.py
{ "start": 8166, "end": 9402 }
class ____(BaseOperator): """ Delete the Queue in the Azure Service Bus namespace. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:AzureServiceBusDeleteQueueOperator` :param queue_name: The name of the queue in Service Bus n...
AzureServiceBusDeleteQueueOperator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 415183, "end": 416379 }
class ____(sgqlc.types.Interface): """Common fields across different project field value types""" __schema__ = github_schema __field_names__ = ("created_at", "creator", "database_id", "field", "id", "item", "updated_at") created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="creat...
ProjectV2ItemFieldValueCommon
python
great-expectations__great_expectations
contrib/great_expectations_ethical_ai_expectations/great_expectations_ethical_ai_expectations/expectations/expect_table_linear_feature_importances_to_be.py
{ "start": 2745, "end": 8324 }
class ____(BatchExpectation): """Expect Feature Importances of specified columns in table for Linear Regression to meet threshold.""" # These examples will be shown in the public gallery, and also executed as unit tests for your Expectation examples = [ { "data": { "x_1"...
ExpectTableLinearFeatureImportancesToBe
python
huggingface__transformers
tests/models/roc_bert/test_modeling_roc_bert.py
{ "start": 19096, "end": 32386 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( RoCBertModel, RoCBertForMaskedLM, RoCBertForCausalLM, RoCBertForMultipleChoice, RoCBertForQuestionAnswering, RoCBertForSequenceClassification,...
RoCBertModelTest
python
getsentry__sentry
tests/acceptance/test_organization_monitors.py
{ "start": 377, "end": 6049 }
class ____(AcceptanceTestCase): def setUp(self) -> None: super().setUp() self.path = f"/organizations/{self.organization.slug}/insights/crons/" self.team = self.create_team(organization=self.organization, name="Mariachi Band") self.project = self.create_project( organiza...
OrganizationMonitorsTest
python
google__pytype
pytype/tools/traces/traces.py
{ "start": 9180, "end": 9449 }
class ____(visitor.BaseVisitor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.line = 0 def generic_visit(self, node): lineno = getattr(node, "lineno", 0) if lineno > self.line: self.line = lineno
_LineNumberVisitor
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/extra_trees_preproc_for_regression.py
{ "start": 579, "end": 5839 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__( self, n_estimators, criterion, min_samples_leaf, min_samples_split, max_features, bootstrap=False, max_leaf_nodes=None, max_depth="None", min_weight_fraction_leaf=0.0, ...
ExtraTreesPreprocessorRegression
python
scikit-learn__scikit-learn
sklearn/model_selection/_search.py
{ "start": 16353, "end": 48085 }
class ____(MetaEstimatorMixin, BaseEstimator, metaclass=ABCMeta): """Abstract base class for hyper parameter search with cross-validation.""" _parameter_constraints: dict = { "estimator": [HasMethods(["fit"])], "scoring": [ StrOptions(set(get_scorer_names())), callable, ...
BaseSearchCV
python
encode__starlette
starlette/formparsers.py
{ "start": 4157, "end": 11086 }
class ____: spool_max_size = 1024 * 1024 # 1MB """The maximum size of the spooled temporary file used to store file data.""" max_part_size = 1024 * 1024 # 1MB """The maximum size of a part in the multipart request.""" def __init__( self, headers: Headers, stream: AsyncGene...
MultiPartParser
python
eventlet__eventlet
eventlet/db_pool.py
{ "start": 10243, "end": 10855 }
class ____(BaseConnectionPool): """A pool which gives out plain database connections. """ def create(self): now = time.time() return now, now, self.connect( self._db_module, self.connect_timeout, *self._args, **self._kwargs) @classmethod def connect(cls, db_module, conn...
RawConnectionPool
python
kamyu104__LeetCode-Solutions
Python/find-k-pairs-with-smallest-sums.py
{ "start": 154, "end": 1121 }
class ____(object): def kSmallestPairs(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]] """ pairs = [] if len(nums1) > len(nums2): tmp = self.kSmallestPairs(nums2, nums1, k) ...
Solution
python
allegroai__clearml
clearml/model.py
{ "start": 59703, "end": 76727 }
class ____(Model): """ Load an existing model in the system, search by model ID. The Model will be read-only and can be used to pre initialize a network. We can connect the model to a task as input model, then when running remotely override it with the UI. """ # noinspection PyProtectedMember ...
InputModel
python
pypa__installer
tests/test_records.py
{ "start": 1912, "end": 6741 }
class ____: @pytest.mark.parametrize( "path, hash_, size, caused_by", [ ("", "", "", ["path"]), ("", "", "non-int", ["path", "size"]), ("a.py", "", "non-int", ["size"]), # Notice that we're explicitly allowing non-compliant hash values ("a....
TestRecordEntry
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 15941, "end": 16173 }
class ____(_RerankerProvider): module_config: Optional[Dict[str, Any]] def _to_dict(self) -> Dict[str, Any]: if self.module_config is None: return {} return self.module_config
_RerankerCustomConfig
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 13237, "end": 13364 }
class ____(serializers.ModelSerializer): class Meta: model = Comment exclude = ('created',)
CommentSerializer
python
pytest-dev__pytest
testing/test_collection.py
{ "start": 70791, "end": 94539 }
class ____: """Test that overlapping collection arguments (e.g. `pytest a/b a a/c::TestIt) are handled correctly (#12083).""" @pytest.mark.parametrize("args", [("a", "a/b"), ("a/b", "a")]) def test_parent_child(self, pytester: Pytester, args: tuple[str, ...]) -> None: """Test that 'pytest a a/b...
TestOverlappingCollectionArguments
python
google__jax
tests/mutable_array_test.py
{ "start": 28725, "end": 35419 }
class ____(jtu.JaxTestCase): def test_return_from_jit(self): with self.assertRaisesRegex( ValueError, r"traced for jit returned a mutable array reference.*\n\n" r".*was created on line"): jax.jit(core.new_ref)(jnp.arange(3)) def test_return_from_jit_arg(self): with self.assert...
MutableArrayErrorsTest
python
getsentry__sentry
src/sentry/core/endpoints/scim/members.py
{ "start": 3996, "end": 5671 }
class ____(serializers.Serializer): # we don't actually use "schemas" for anything atm but its part of the spec schemas = serializers.ListField(child=serializers.CharField(), required=False) Operations = serializers.ListField( child=SCIMPatchOperationSerializer(), required=True, sour...
SCIMPatchRequestSerializer
python
run-llama__llama_index
llama-index-packs/llama-index-packs-nebulagraph-query-engine/llama_index/packs/nebulagraph_query_engine/base.py
{ "start": 910, "end": 6068 }
class ____(BaseLlamaPack): """NebulaGraph Query Engine pack.""" def __init__( self, username: str, password: str, ip_and_port: str, space_name: str, edge_types: str, rel_prop_names: str, tags: str, max_triplets_per_chunk: int, docs...
NebulaGraphQueryEnginePack
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 17717, "end": 18129 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): # TODO: categorical attributes without a symbol don't count towards this # measure values = [val for val in helper_functions.get_value("NumSymbols") if val > 0] mean = np.nanmean(values) return mean if np...
SymbolsMean
python
walkccc__LeetCode
solutions/1770. Maximum Score from Performing Multiplication Operations/1770.py
{ "start": 0, "end": 639 }
class ____: def maximumScore(self, nums: list[int], multipliers: list[int]) -> int: @functools.lru_cache(2000) def dp(s: int, i: int) -> int: """Returns the maximum score of nums[s..e] and multipliers[i].""" if i == len(multipliers): return 0 # The number of nums picked on the start...
Solution
python
python-openxml__python-docx
src/docx/parts/story.py
{ "start": 498, "end": 3857 }
class ____(XmlPart): """Base class for story parts. A story part is one that can contain textual content, such as the document-part and header or footer parts. These all share content behaviors like `.paragraphs`, `.add_paragraph()`, `.add_table()` etc. """ def get_or_add_image(self, image_des...
StoryPart
python
jina-ai__jina
tests/integration/override_config_params/container/executor.py
{ "start": 38, "end": 613 }
class ____(Executor): def __init__(self, param1, param2, param3, *args, **kwargs): super().__init__(*args, **kwargs) self.param1 = param1 self.param2 = param2 self.param3 = param3 @requests(on='/search') def encode(self, docs, **kwargs): for doc in docs: ...
Override
python
pytest-dev__pytest
testing/test_pytester.py
{ "start": 5993, "end": 9391 }
class ____: def test_inline_run_test_module_not_cleaned_up(self, pytester: Pytester) -> None: test_mod = pytester.makepyfile("def test_foo(): assert True") result = pytester.inline_run(str(test_mod)) assert result.ret == ExitCode.OK # rewrite module, now test should fail if module wa...
TestInlineRunModulesCleanup
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_shutdown_repository_location.py
{ "start": 1236, "end": 2377 }
class ____(BaseTestSuite): def test_shutdown_repository_location(self, graphql_client, graphql_context): origin = next(iter(graphql_context.get_code_location_entries().values())).origin origin.create_client().heartbeat() result = graphql_client.shutdown_repository_location(main_repo_locatio...
TestShutdownRepositoryLocation
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_stateful.py
{ "start": 10934, "end": 31964 }
class ____(RuleBasedStateMachine): def __init__(self): super().__init__() self.counter = 0 @rule() def increment(self): self.counter += 1 assert self.counter < 10 FailsEventually.TestCase.settings = Settings(stateful_step_count=5) @skipif_threading def test_can_explicitl...
FailsEventually
python
PyCQA__pylint
doc/data/messages/d/duplicate-bases/good.py
{ "start": 25, "end": 56 }
class ____(Animal): pass
Bird
python
google__jax
docs/autodidax.py
{ "start": 22473, "end": 22508 }
class ____: pass empty = Empty()
Empty
python
mahmoud__boltons
tests/test_ioutils.py
{ "start": 11728, "end": 17654 }
class ____(TestCase, BaseTestMixin, AssertionsMixin): linesep = os.linesep def setUp(self): self.spooled_flo = ioutils.SpooledStringIO() self.test_str = "Remember kids, always use an emdash: '\u2014'" self.test_str_lines = f"Text with\u2014{os.linesep}newlines!" self.data_type =...
TestSpooledStringIO
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1021697, "end": 1022481 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateEnterpriseMembersCanDeleteRepositoriesSetting """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "message") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") ...
UpdateEnterpriseMembersCanDeleteRepositoriesSettingPayload
python
pytransitions__transitions
transitions/extensions/asyncio.py
{ "start": 1561, "end": 2639 }
class ____(State): """A persistent representation of a state managed by a ``Machine``. Callback execution is done asynchronously.""" async def enter(self, event_data): """Triggered when a state is entered. Args: event_data: (AsyncEventData): The currently processed event. ""...
AsyncState
python
mlflow__mlflow
mlflow/utils/gorilla.py
{ "start": 3270, "end": 4837 }
class ____: """Define the patching behaviour. Attributes ---------- allow_hit : bool A hit occurs when an attribute at the destination already exists with the name given by the patch. If ``False``, the patch process won't allow setting a new value for the attribute by raising an...
Settings
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 5734, "end": 5928 }
class ____(graphene.Union): class Meta: types = (GrapheneAssetPartitionsStatusCounts, GrapheneUnpartitionedAssetStatus) name = "AssetBackfillStatus"
GrapheneAssetBackfillStatus
python
pypa__hatch
tests/project/test_core.py
{ "start": 56, "end": 1166 }
class ____: def test_no_project(self, temp_dir): project = Project(temp_dir) assert project.find_project_root() is None @pytest.mark.parametrize("file_name", ["pyproject.toml", "setup.py"]) def test_direct(self, temp_dir, file_name): project = Project(temp_dir) project_file...
TestFindProjectRoot
python
getsentry__sentry
src/sentry/issues/search.py
{ "start": 1745, "end": 1809 }
class ____(TypedDict, total=False): group_id: int
MergeableRow
python
astropy__astropy
astropy/time/tests/test_comparisons.py
{ "start": 185, "end": 7287 }
class ____: """Test Comparisons of Time and TimeDelta classes""" def setup_method(self): self.t1 = Time(np.arange(49995, 50005), format="mjd", scale="utc") self.t2 = Time(np.arange(49000, 51000, 200), format="mjd", scale="utc") def test_miscompares(self): """ If an incompat...
TestTimeComparisons
python
pypa__warehouse
tests/unit/email/ses/test_views.py
{ "start": 424, "end": 2422 }
class ____: def test_valid(self, monkeypatch): class FakeMessageVerifier: @staticmethod @pretend.call_recorder def __init__(topics, session): self.topics = topics self.session = session @staticmethod @pretend.call_r...
TestVerifySNSMessageHelper
python
dask__dask
dask/backends.py
{ "start": 1458, "end": 5298 }
class ____(Generic[BackendEntrypointType]): """Simple backend dispatch for collection-creation functions""" _lookup: dict[str, BackendEntrypointType] _module_name: str _config_field: str _default: str _entrypoint_class: type[BackendEntrypointType] _entrypoint_root: str def __init__( ...
CreationDispatch
python
django__django
tests/resolve_url/tests.py
{ "start": 272, "end": 2711 }
class ____(SimpleTestCase): """ Tests for the resolve_url() function. """ def test_url_path(self): """ Passing a URL path to resolve_url() results in the same url. """ self.assertEqual("/something/", resolve_url("/something/")) def test_relative_path(self): ...
ResolveUrlTests
python
pytorch__pytorch
test/test_hub.py
{ "start": 607, "end": 12329 }
class ____(TestCase): def setUp(self): super().setUp() self.previous_hub_dir = torch.hub.get_dir() self.tmpdir = tempfile.TemporaryDirectory("hub_dir") torch.hub.set_dir(self.tmpdir.name) self.trusted_list_path = os.path.join(torch.hub.get_dir(), "trusted_list") def tear...
TestHub
python
ansible__ansible
lib/ansible/modules/package_facts.py
{ "start": 12169, "end": 12714 }
class ____(CLIMgr): CLI = 'qlist' atoms = ['category', 'name', 'version', 'ebuild_revision', 'slots', 'prefixes', 'sufixes'] def list_installed(self): rc, out, err = module.run_command(' '.join([self._cli, '-Iv', '|', 'xargs', '-n', '1024', 'qatom']), use_unsafe_shell=True) if rc != 0: ...
PORTAGE
python
Textualize__textual
docs/examples/guide/layout/grid_layout7_gutter.py
{ "start": 80, "end": 528 }
class ____(App): CSS_PATH = "grid_layout7_gutter.tcss" def compose(self) -> ComposeResult: yield Static("One", classes="box") yield Static("Two", classes="box") yield Static("Three", classes="box") yield Static("Four", classes="box") yield Static("Five", classes="box") ...
GridLayoutExample
python
streamlit__streamlit
lib/tests/streamlit/platform_test.py
{ "start": 814, "end": 1158 }
class ____(DeltaGeneratorTestCase): """Tests the platform module functions""" @parameterized.expand(["Hello", '{"name":"foo", "type":"bar"}']) def test_post_parent_message(self, message: str): post_parent_message(message) c = self.get_message_from_queue().parent_message assert c.mes...
PlatformTest
python
django__django
django/db/models/fields/mixins.py
{ "start": 972, "end": 1945 }
class ____: _default_hint = ("<valid default>", "<invalid default>") def _check_default(self): if ( self.has_default() and self.default is not None and not callable(self.default) ): return [ checks.Warning( "%s ...
CheckFieldDefaultMixin
python
getsentry__sentry-python
sentry_sdk/integrations/rq.py
{ "start": 948, "end": 5307 }
class ____(Integration): identifier = "rq" origin = f"auto.queue.{identifier}" @staticmethod def setup_once(): # type: () -> None version = parse_version(RQ_VERSION) _check_minimum_version(RqIntegration, version) old_perform_job = Worker.perform_job @ensure_int...
RqIntegration
python
scrapy__scrapy
tests/test_downloader_handler_twisted_http2.py
{ "start": 7602, "end": 8652 }
class ____(H2DownloadHandlerMixin, TestHttpProxyBase): is_secure = True expected_http_proxy_request_body = b"/" @deferred_f_from_coro_f async def test_download_with_proxy_https_timeout( self, proxy_mockserver: ProxyEchoMockServer, download_handler: DownloadHandlerProtocol, )...
TestHttps2Proxy
python
openai__openai-python
examples/responses/background_async.py
{ "start": 187, "end": 1149 }
class ____(BaseModel): steps: List[Step] final_answer: str async def main() -> None: client = AsyncOpenAI() id = None async with await client.responses.create( input="solve 8x + 31 = 2", model="gpt-4o-2024-08-06", background=True, stream=True, ) as stream: ...
MathResponse
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 6087, "end": 6176 }
class ____(TestEnPh): """Test fil_PH automotive provider methods""" pass
TestFilPh
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py
{ "start": 10996, "end": 16555 }
class ____: """Test always_include functionality.""" def test_always_include_tools_present(self) -> None: """Test that always_include tools are always present in the request.""" model_requests = [] @wrap_model_call def trace_model_requests(request, handler): model_r...
TestAlwaysInclude
python
huggingface__transformers
tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
{ "start": 10653, "end": 11612 }
class ____(unittest.TestCase): def test_linear_preserves_shape(self): """ Test that FbgemmFp8Linear preserves shape when in_features == out_features. """ from transformers.integrations import FbgemmFp8Linear with init_empty_weights(include_buffers=True): linear =...
FbgemmFp8LinearTest
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/sleep_test.py
{ "start": 1105, "end": 2857 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testSleep(self): self.skipTest("b/123597912") sleep_microseconds = 100 dataset = dataset_ops.Dataset.range(10).apply( testing.sleep(sleep_microseconds)) next_elem...
SleepTest
python
openai__openai-python
src/openai/types/completion_create_params.py
{ "start": 475, "end": 6479 }
class ____(TypedDict, total=False): model: Required[Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]]] """ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our ...
CompletionCreateParamsBase
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 26491, "end": 30762 }
class ____(BaseModel): a: UndefinedType """ ) # Since we're testing the absence of an error, it's important to confirm pydantic was actually run. # The presence of the `__pydantic_complete__` is a good indicator of this. assert module.Foobar.__pydantic_complete__ is False def test_undefined_types_...
Foobar
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py
{ "start": 2017, "end": 2556 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-detector-index" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.environment = Environment.objects.create( organization_id=self.organization.id, name="production" ) self...
OrganizationDetectorIndexBaseTest
python
kamyu104__LeetCode-Solutions
Python/find-the-number-of-subsequences-with-equal-gcd.py
{ "start": 2921, "end": 3749 }
class ____(object): def subsequencePairCount(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 def gcd(a, b): while b: a, b = b, a%b return a mx = max(nums) dp = [[0]*(mx+1) for _ in xrange(mx...
SolutionTLE
python
Netflix__metaflow
test/core/tests/large_artifact.py
{ "start": 67, "end": 1364 }
class ____(MetaflowTest): """ Test that you can serialize large objects (over 4GB) with Python3 - although on OSX, some versions of Python3 fail to serialize objects over 2GB - https://bugs.python.org/issue24658 so YMMV. """ PRIORITY = 2 SKIP_GRAPHS = [ "simple_switch", ...
LargeArtifactTest
python
falconry__falcon
examples/things_advanced_asgi.py
{ "start": 4693, "end": 7053 }
class ____: def __init__(self, db): self.db = db self.logger = logging.getLogger('thingsapp.' + __name__) async def on_get(self, req, resp, user_id): marker = req.get_param('marker') or '' limit = req.get_param_as_int('limit') or 50 try: result = await self....
ThingsResource
python
pytorch__pytorch
torch/nn/parameter.py
{ "start": 4176, "end": 7806 }
class ____: _allowed_methods = [ torch.Tensor.__hash__, torch.Tensor.size, torch.Tensor.copy_, torch.Tensor.is_complex, torch.Tensor.is_floating_point, torch.Tensor.half, torch.Tensor.float, torch.Tensor.double, torch.Tensor.char, torch...
UninitializedTensorMixin
python
doocs__leetcode
solution/1200-1299/1228.Missing Number In Arithmetic Progression/Solution2.py
{ "start": 0, "end": 256 }
class ____: def missingNumber(self, arr: List[int]) -> int: n = len(arr) d = (arr[-1] - arr[0]) // n for i in range(1, n): if arr[i] != arr[i - 1] + d: return arr[i - 1] + d return arr[0]
Solution
python
django-haystack__django-haystack
haystack/utils/loading.py
{ "start": 2677, "end": 4061 }
class ____: def __init__(self, connections_info): self.connections_info = connections_info self.thread_local = threading.local() self._index = None def ensure_defaults(self, alias): try: conn = self.connections_info[alias] except KeyError: raise I...
ConnectionHandler
python
pennersr__django-allauth
allauth/headless/mfa/response.py
{ "start": 2672, "end": 2875 }
class ____(APIResponse): def __init__(self, request, authenticator): data = _authenticator_data(authenticator, sensitive=True) super().__init__(request, data=data)
RecoveryCodesResponse
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/workflows.py
{ "start": 1639, "end": 16188 }
class ____(GoogleBaseHook): """ Hook for Google GCP APIs. All the methods in the hook where project_id is used must be called with keyword arguments rather than positional. """ def get_workflows_client(self) -> WorkflowsClient: """Return WorkflowsClient object.""" return Workfl...
WorkflowsHook
python
openai__openai-python
src/openai/types/realtime/realtime_tracing_config.py
{ "start": 268, "end": 871 }
class ____(BaseModel): group_id: Optional[str] = None """ The group id to attach to this trace to enable filtering and grouping in the Traces Dashboard. """ metadata: Optional[object] = None """ The arbitrary metadata to attach to this trace to enable filtering in the Traces Dashboa...
TracingConfiguration
python
keon__algorithms
tests/test_maths.py
{ "start": 7352, "end": 7689 }
class ____(unittest.TestCase): """[summary] Test for the file primes_sieve_of_eratosthenes.py Arguments: unittest {[type]} -- [description] """ def test_primes(self): self.assertListEqual([2, 3, 5, 7], get_primes(7)) self.assertRaises(ValueError, get_primes, -42)
TestPrimesSieveOfEratosthenes
python
celery__celery
t/unit/utils/test_dispatcher.py
{ "start": 851, "end": 5667 }
class ____: """Test suite for dispatcher (barely started)""" def _testIsClean(self, signal): """Assert that everything has been cleaned up automatically""" assert not signal.has_listeners() assert signal.receivers == [] def test_exact(self): a_signal.connect(receiver_1_arg,...
test_Signal
python
kamyu104__LeetCode-Solutions
Python/k-th-smallest-in-lexicographical-order.py
{ "start": 35, "end": 1188 }
class ____(object): def findKthNumber(self, n, k): """ :type n: int :type k: int :rtype: int """ result = 0 cnts = [0] * 10 for i in xrange(1, 10): cnts[i] = cnts[i - 1] * 10 + 1 nums = [] i = n while i: ...
Solution
python
doocs__leetcode
lcof2/剑指 Offer II 098. 路径的数目/Solution2.py
{ "start": 0, "end": 247 }
class ____: def uniquePaths(self, m: int, n: int) -> int: f = [[1] * n for _ in range(m)] for i in range(1, m): for j in range(1, n): f[i][j] = f[i - 1][j] + f[i][j - 1] return f[-1][-1]
Solution
python
getsentry__sentry
src/sentry/issues/endpoints/organization_shortid.py
{ "start": 1058, "end": 4926 }
class ____(GroupEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PUBLIC, } @extend_schema( operation_id="Resolve a Short ID", parameters=[ GlobalParams.ORG_ID_OR_SLUG, OpenApiParameter( name="issue_id", ...
ShortIdLookupEndpoint
python
pandas-dev__pandas
pandas/core/arrays/_arrow_string_mixins.py
{ "start": 475, "end": 12919 }
class ____: _pa_array: pa.ChunkedArray def __init__(self, *args, **kwargs) -> None: raise NotImplementedError def _from_pyarrow_array(self, pa_array) -> Self: raise NotImplementedError def _convert_bool_result(self, result, na=lib.no_default, method_name=None): # Convert a boo...
ArrowStringArrayMixin
python
celery__celery
celery/contrib/migrate.py
{ "start": 737, "end": 824 }
class ____(Exception): """Semi-predicate used to signal filter stop."""
StopFiltering
python
huggingface__transformers
src/transformers/models/qwen3_moe/modeling_qwen3_moe.py
{ "start": 13744, "end": 14473 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Qwen3MoeRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): inp...
Qwen3MoeRMSNorm
python
fsspec__filesystem_spec
fsspec/implementations/memory.py
{ "start": 406, "end": 9623 }
class ____(AbstractFileSystem): """A filesystem based on a dict of BytesIO objects This is a global filesystem so instances of this class all point to the same in memory filesystem. """ store: ClassVar[dict[str, Any]] = {} # global, do not overwrite! pseudo_dirs = [""] # global, do not overw...
MemoryFileSystem
python
redis__redis-py
redis/commands/search/reducers.py
{ "start": 3775, "end": 4220 }
class ____(Reducer): """ Returns a random sample of items from the dataset, from the given property """ NAME = "RANDOM_SAMPLE" def __init__(self, field: str, size: int) -> None: """ ### Parameter **field**: Field to sample from **size**: Return this many items (can...
random_sample
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 125095, "end": 125358 }
class ____(BaseModel): name: str = Field(..., description="") creation_time: Optional[str] = Field(default=None, description="") size: int = Field(..., description="") checksum: Optional[str] = Field(default=None, description="")
SnapshotDescription
python
kamyu104__LeetCode-Solutions
Python/ternary-expression-parser.py
{ "start": 29, "end": 681 }
class ____(object): def parseTernary(self, expression): """ :type expression: str :rtype: str """ if not expression: return "" stack = [] for c in expression[::-1]: if stack and stack[-1] == '?': stack.pop() # pop '?' ...
Solution
python
getsentry__sentry
tests/sentry/tasks/test_store.py
{ "start": 485, "end": 11803 }
class ____(Plugin2): def get_event_preprocessors(self, data): def remove_extra(data): del data["extra"] return data def put_on_hold(data): data["unprocessed"] = True return data if data.get("platform") == "mattlang": return [remov...
BasicPreprocessorPlugin
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 6245, "end": 6587 }
class ____: """This is a class that wraps a function. It will be documented correctly.""" def __init__(self, func): self._func = func @ClassDecorator def another_decorated_function(arg: str) -> str: """This is another decorated function. It will not be documented correctly.""" raise NotImpleme...
ClassDecorator
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 46244, "end": 50930 }
class ____(DashboardComponent): """Bar chart showing time spend in action by key prefix""" @log_errors def __init__(self, scheduler, **kwargs): self.last = 0 self.scheduler = scheduler if TaskStreamPlugin.name not in self.scheduler.plugins: self.scheduler.add_plugin(Tas...
ComputePerKey
python
joke2k__faker
faker/providers/currency/es/__init__.py
{ "start": 46, "end": 5989 }
class ____(CurrencyProvider): # Format: (code, name) currencies = ( ("AED", "Dírham de los Emiratos Árabes Unidos"), ("AFN", "Afghaní"), ("ALL", "Lek albanés"), ("AMD", "Dram armenio"), ("ANG", "Florín de las Antillas Holandesas"), ("AOA", "Kwanza angoleño"), ...
Provider
python
tensorflow__tensorflow
tensorflow/lite/python/metrics/metrics_portable.py
{ "start": 1193, "end": 1827 }
class ____(metrics_interface.TFLiteMetricsInterface): """TFLite metrics helper.""" def __init__(self, model_hash: Optional[Text] = None, model_path: Optional[Text] = None) -> None: pass def increase_counter_debugger_creation(self): pass def increase_counter_interpreter_c...
TFLiteMetrics
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0099_backfill_metric_issue_detectorgroup.py
{ "start": 524, "end": 3921 }
class ____(Enum): LATEST = ["project_id", "-timestamp", "-event_id"] OLDEST = ["project_id", "timestamp", "event_id"] RECOMMENDED = [ "-replay.id", "-trace.sampled", "num_processing_errors", "-profile.id", "-timestamp", "-event_id", ] def get_oldest_or_l...
EventOrdering
python
arrow-py__arrow
tests/test_locales.py
{ "start": 33808, "end": 35119 }
class ____: def test_plurals2(self): assert self.locale._format_timeframe("hours", 0) == "0 часа" assert self.locale._format_timeframe("hours", 1) == "1 час" assert self.locale._format_timeframe("hours", 2) == "2 часа" assert self.locale._format_timeframe("hours", 4) == "4 часа" ...
TestBulgarianLocale
python
PrefectHQ__prefect
src/prefect/filesystems.py
{ "start": 21751, "end": 22393 }
class ____(BaseModel): """ A file system that does not store any data. """ async def read_path(self, path: str) -> None: pass async def write_path(self, path: str, content: bytes) -> None: pass async def get_directory( self, from_path: Optional[str] = None, local_path:...
NullFileSystem
python
ray-project__ray
rllib/algorithms/tests/test_local.py
{ "start": 77, "end": 786 }
class ____(unittest.TestCase): def setUp(self) -> None: ray.init(local_mode=True) def tearDown(self) -> None: ray.shutdown() def test_local(self): config = ( PPOConfig() .api_stack( enable_rl_module_and_learner=True, enable_en...
LocalModeTest
python
django-haystack__django-haystack
test_haystack/elasticsearch_tests/test_elasticsearch_backend.py
{ "start": 61373, "end": 64131 }
class ____(TestCase): def setUp(self): super().setUp() # Wipe it clean. self.raw_es = elasticsearch.Elasticsearch( settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] ) clear_elasticsearch_index() # Stow. self.old_ui = connections["elasticsearc...
ElasticsearchBoostBackendTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride3.py
{ "start": 2226, "end": 2559 }
class ____: @property def prop1(self) -> int: return 3 @property def prop2(self) -> int: return 3 @prop2.setter def prop2(self, val: int) -> None: pass @property def prop3(self) -> int: return 3 @prop3.setter def prop3(self, val: int) -> None: ...
H1
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/typing.py
{ "start": 19986, "end": 20398 }
class ____(Generic[_FN]): """a descriptor that refers to a callable. works around mypy's limitation of not allowing callables assigned as instance variables """ if TYPE_CHECKING: def __get__(self, instance: object, owner: Any) -> _FN: ... def __set__(self, instance: Any, value:...
CallableReference
python
sqlalchemy__sqlalchemy
tools/generate_proxy_methods.py
{ "start": 2934, "end": 14973 }
class ____: __slots__ = ("sym",) def __init__(self, sym: str): self.sym = sym def __repr__(self) -> str: return self.sym classes: collections.defaultdict[str, Dict[str, Tuple[Any, ...]]] = ( collections.defaultdict(dict) ) _T = TypeVar("_T", bound="Any") def create_proxy_methods( ...
_repr_sym
python
kamyu104__LeetCode-Solutions
Python/vowel-spellchecker.py
{ "start": 29, "end": 935 }
class ____(object): def spellchecker(self, wordlist, queries): """ :type wordlist: List[str] :type queries: List[str] :rtype: List[str] """ vowels = set(['a', 'e', 'i', 'o', 'u']) def todev(word): return "".join('*' if c.lower() in vowels else c.lo...
Solution
python
pytorch__pytorch
torch/_inductor/runtime/coordinate_descent_tuner.py
{ "start": 906, "end": 13944 }
class ____: """ The coordinate descent tuner. Tune one field/coordinate at a time. TODO will it be necessary to tune multiple fields simultaneously. TODO: what if both increasing and decreasing a field can improve perf. i.e., there are multiple local optima.. """ def __init__( ...
CoordescTuner
python
sympy__sympy
sympy/categories/baseclasses.py
{ "start": 5838, "end": 11648 }
class ____(Morphism): r""" Represents a morphism which is a composition of other morphisms. Explanation =========== Two composite morphisms are equal if the morphisms they were obtained from (components) are the same and were listed in the same order. The arguments to the constructor ...
CompositeMorphism
python
spack__spack
lib/spack/spack/relocate_text.py
{ "start": 5070, "end": 10865 }
class ____(PrefixReplacer): def __init__(self, prefix_to_prefix: Dict[bytes, bytes], suffix_safety_size: int = 7) -> None: """ prefix_to_prefix: Ordered dictionary where the keys are bytes representing the old prefixes and the values are the new suffix_safety_size: in case of nul...
BinaryFilePrefixReplacer
python
plotly__plotly.py
plotly/graph_objs/parcoords/line/colorbar/_tickformatstop.py
{ "start": 233, "end": 8549 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.line.colorbar" _path_str = "parcoords.line.colorbar.tickformatstop" _valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"} @property def dtickrange(self): """ range [*min*, *max*], where "m...
Tickformatstop
python
ansible__ansible
lib/ansible/plugins/lookup/file.py
{ "start": 1744, "end": 2924 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): ret = [] self.set_options(var_options=variables, direct=kwargs) for term in terms: display.debug("File lookup term: %s" % term) # Find the file in the expected search path try: ...
LookupModule