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
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 1008, "end": 1125 }
class ____: def has_kwargs(self, arg, **kwargs): pass def no_kwargs(self, args): pass
Varargs
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py
{ "start": 32276, "end": 35868 }
class ____(ManagedKafkaBaseOperator): """ Update the properties of a single topic. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param location: Required. The ID of the Google Cloud region that the service belongs to. :param cluster_id: Required. The ...
ManagedKafkaUpdateTopicOperator
python
facelessuser__soupsieve
tests/test_level3/test_subsequent_sibling.py
{ "start": 64, "end": 746 }
class ____(util.TestCase): """Test subsequent sibling combinator.""" def test_subsequent_sibling(self): """Test subsequent sibling.""" self.assert_selector( """ <div> <p id="0">Some text <span id="1"> in a paragraph</span>.</p> <a id="2" href="ht...
TestSubsequentSibling
python
airbytehq__airbyte
airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py
{ "start": 18046, "end": 18920 }
class ____(ByStateRkiCovidStream): """Docs: https://api.corona-zahlen.org/germany/states/history/incidence/:days""" primary_key = None def __init__(self, config, **kwargs): super().__init__(**kwargs) self.start_date = config.get("start_date") def date_to_int(self, start_date) -> int: ...
StatesHistoryIncidence
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/util.py
{ "start": 59952, "end": 61311 }
class ____(Bundle[_T]): """Like :class:`.Bundle` but returns ``dict`` instances instead of named tuple like objects:: bn = DictBundle("mybundle", MyClass.data1, MyClass.data2) for row in session.execute(select(bn)).where(bn.c.data1 == "d1"): print(row.mybundle["data1"], row.mybundle...
DictBundle
python
xlwings__xlwings
xlwings/constants.py
{ "start": 127018, "end": 127273 }
class ____: xlChartAsWindow = 5 # from enum XlWindowType xlChartInPlace = 4 # from enum XlWindowType xlClipboard = 3 # from enum XlWindowType xlInfo = -4129 # from enum XlWindowType xlWorkbook = 1 # from enum XlWindowType
WindowType
python
getsentry__sentry
tests/sentry/utils/locking/backends/test_migration.py
{ "start": 872, "end": 3141 }
class ____(TestCase): def test_build_from_configs(self) -> None: backend = MigrationLockBackend( backend_new_config={ "path": "sentry.utils.locking.backends.redis.RedisLockBackend", "options": {"cluster": "default"}, }, backend_old_config={...
TestMigrationLockBackend
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_vision.py
{ "start": 47517, "end": 53837 }
class ____(Data2VecVisionPreTrainedModel): def __init__(self, config: Data2VecVisionConfig) -> None: super().__init__(config) self.num_labels = config.num_labels self.data2vec_vision = Data2VecVisionModel(config, add_pooling_layer=False) # FPNs if len(self.config.out_indice...
Data2VecVisionForSemanticSegmentation
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/event_log/sqlite/consolidated_sqlite_event_log.py
{ "start": 1190, "end": 7075 }
class ____(SqlEventLogStorage, ConfigurableClass): """SQLite-backed consolidated event log storage intended for test cases only. Users should not directly instantiate this class; it is instantiated by internal machinery when ``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``d...
ConsolidatedSqliteEventLogStorage
python
google__jax
jax/experimental/sparse/csr.py
{ "start": 4963, "end": 23933 }
class ____(JAXSparse): """Experimental CSC matrix implemented in JAX; API subject to change.""" data: jax.Array indices: jax.Array indptr: jax.Array shape: tuple[int, int] nse = property(lambda self: self.data.size) dtype = property(lambda self: self.data.dtype) def __init__(self, args, *, shape): ...
CSC
python
pytorch__pytorch
torch/_dynamo/variables/iter.py
{ "start": 12705, "end": 13914 }
class ____(IteratorVariable): def __init__( self, item: Union[int, VariableTracker] = 0, step: Union[int, VariableTracker] = 1, **kwargs: Any, ) -> None: super().__init__(**kwargs) if not isinstance(item, VariableTracker): item = ConstantVariable.creat...
CountIteratorVariable
python
readthedocs__readthedocs.org
readthedocs/organizations/views/private.py
{ "start": 1822, "end": 2775 }
class ____(PrivateViewMixin, OrganizationView, CreateView): """View to create an organization after the user has signed up.""" template_name = "organizations/organization_create.html" form_class = OrganizationSignupForm def get_form(self, data=None, files=None, **kwargs): """Add request user a...
CreateOrganizationSignup
python
python-openxml__python-docx
src/docx/oxml/text/paragraph.py
{ "start": 624, "end": 3538 }
class ____(BaseOxmlElement): """`<w:p>` element, containing the properties and text for a paragraph.""" add_r: Callable[[], CT_R] get_or_add_pPr: Callable[[], CT_PPr] hyperlink_lst: List[CT_Hyperlink] r_lst: List[CT_R] pPr: CT_PPr | None = ZeroOrOne("w:pPr") # pyright: ignore[reportAssignment...
CT_P
python
scikit-image__scikit-image
src/skimage/filters/lpi_filter.py
{ "start": 820, "end": 7937 }
class ____: """Linear Position-Invariant Filter (2-dimensional)""" def __init__(self, impulse_response, **filter_params): """ Parameters ---------- impulse_response : callable `f(r, c, **filter_params)` Function that yields the impulse response. ``r`` and ``c`` are ...
LPIFilter2D
python
django__django
tests/fixtures_regress/models.py
{ "start": 1681, "end": 1850 }
class ____(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ("name",) def __str__(self): return self.name
Widget
python
getsentry__sentry
tests/sentry/uptime/test_models.py
{ "start": 412, "end": 1344 }
class ____(UptimeTestCase): def test(self) -> None: assert get_active_auto_monitor_count_for_org(self.organization) == 0 self.create_uptime_detector() assert get_active_auto_monitor_count_for_org(self.organization) == 1 other_sub = self.create_uptime_subscription(url="https://santry...
GetActiveMonitorCountForOrgTest
python
getsentry__sentry
src/sentry/utils/types.py
{ "start": 2855, "end": 3043 }
class ____(Type[str]): """String type without any coercion, must be a string""" name = "string" default = "" expected_types = (str,) compatible_types = (str,)
StringType
python
kamyu104__LeetCode-Solutions
Python/number-of-strings-that-appear-as-substrings-in-word.py
{ "start": 4308, "end": 4437 }
class ____(object): def numOfStrings(self, patterns, word): return sum(pattern in word for pattern in patterns)
Solution3
python
marshmallow-code__marshmallow
tests/test_registry.py
{ "start": 4537, "end": 4626 }
class ____: def __init__(self, _id, a=None): self.id = _id self.a = a
B
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 26511, "end": 26969 }
class ____: """Test hu_HU internet provider methods""" def test_internet(self, faker): domain_name = faker.domain_name() assert isinstance(domain_name, str) tld = faker.tld() assert isinstance(tld, str) email = faker.email() assert isinstance(email, str) def...
TestHuHu
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/replicate_test.py
{ "start": 14063, "end": 17575 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def setUp(self): super(GraphClusterReplicateTest, self).setUp() # Start the local server. worker_config = config_pb2.ConfigProto() worker_config.device_count["CPU"] = 2 worker, _ = test_util.create_loca...
GraphClusterReplicateTest
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/retention.py
{ "start": 193, "end": 279 }
class ____(BaseModel): purgeAfterDays: Union[int, TickRetentionByType]
TickRetention
python
joke2k__faker
faker/providers/automotive/es_AR/__init__.py
{ "start": 120, "end": 2385 }
class ____(AutomotiveProvider): """Implement automotive provider for ``es_AR`` locale. Sources: - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Argentina """ license_plate_old_format_first_letter = ascii_uppercase.replace("YZ", "") license_plate_new_first_letter = OrderedDict...
Provider
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 2828, "end": 3946 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, credentials_json: str, email: str, lookback: Optional[int] = None ): """Airbyte Source for Google Workspace Admin Reports. Documentation can be found at https://docs.airbyte.com/integrations/sources/google-wo...
GoogleWorkspaceAdminReportsSource
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/serialized_objects.py
{ "start": 4392, "end": 4713 }
class ____(NamedTuple): """A serializable snapshot of a node in the AutomationCondition tree.""" class_name: str description: str unique_id: str label: Optional[str] = None name: Optional[str] = None operator_type: OperatorType = "identity" @whitelist_for_serdes
AutomationConditionNodeSnapshot
python
realpython__materials
debug-python-errors/test_fruit.py
{ "start": 60, "end": 1098 }
class ____(unittest.TestCase): def test_empty_list(self): """with empty list""" self.assertEqual(capitalize_fruit_names([]), []) def test_lowercase(self): """with lowercase strings""" self.assertEqual( capitalize_fruit_names(["apple", "banana", "cherry"]), ...
TestFruit
python
Textualize__textual
src/textual/drivers/web_driver.py
{ "start": 866, "end": 955 }
class ____(Exception): """Internal exception to force exit of input loop."""
_ExitInput
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
{ "start": 6538, "end": 7018 }
class ____(IncrementalShopifyStream): """ PaymentsTransactions stream does not support Incremental Refresh based on datetime fields, only `since_id` is supported: https://shopify.dev/api/admin-rest/2021-07/resources/transactions """ data_field = "transactions" cursor_field = "id" order_fiel...
BalanceTransactions
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 245101, "end": 248582 }
class ____(rv_continuous): r"""A non-central F distribution continuous random variable. %(before_notes)s See Also -------- scipy.stats.f : Fisher distribution Notes ----- The probability density function for `ncf` is: .. math:: f(x, n_1, n_2, \lambda) = \exp\...
ncf_gen
python
getsentry__sentry
src/sentry/seer/explorer/custom_tool_utils.py
{ "start": 1342, "end": 2073 }
class ____(BaseModel): """Parameter definition for an Explorer tool. Examples: # String parameter ExplorerToolParam( name="query", description="Search query", type=StringType() ) # Array of strings ExplorerToolParam( name=...
ExplorerToolParam
python
django__django
django/contrib/postgres/forms/ranges.py
{ "start": 959, "end": 2939 }
class ____(forms.MultiValueField): default_error_messages = { "invalid": _("Enter two valid values."), "bound_ordering": _( "The start of the range must not exceed the end of the range." ), } hidden_widget = HiddenRangeWidget def __init__(self, **kwargs): if ...
BaseRangeField
python
getsentry__sentry
src/sentry/processing/backpressure/memory.py
{ "start": 553, "end": 2853 }
class ____: host: str | None port: int | None # Based on configuration, this could be: # - a `rediscluster` Cluster (actually `RetryingRedisCluster`) # - a `rb.Cluster` (client side routing cluster client) Cluster = Union[RedisCluster, rb.Cluster, StrictRedis] def get_memory_usage(node_id: str, info: Mappin...
NodeInfo
python
ray-project__ray
rllib/examples/_docs/rllib_on_rllib_readme.py
{ "start": 269, "end": 3906 }
class ____(gym.Env): """Environment in which an agent must learn to repeat the seen observations. Observations are float numbers indicating the to-be-repeated values, e.g. -1.0, 5.1, or 3.2. The action space is always the same as the observation space. Rewards are r=-abs(observation - action), fo...
ParrotEnv
python
django__django
tests/test_runner/tests.py
{ "start": 25419, "end": 27882 }
class ____(TransactionTestCase): available_apps = ["test_runner"] databases = {"default", "other"} @unittest.skipUnless( all(db.connections[conn].vendor == "sqlite" for conn in db.connections), "This is an sqlite-specific issue", ) def test_transaction_support(self): # Asser...
SQLiteInMemoryTestDbs
python
google__pytype
pytype/abstract/_typing.py
{ "start": 17774, "end": 17877 }
class ____(_TypeVariableInstance): """An instance of a TypeVar type parameter."""
TypeParameterInstance
python
getsentry__sentry
src/sentry/api/endpoints/setup_wizard.py
{ "start": 664, "end": 2632 }
class ____(Endpoint): owner = ApiOwner.WEB_FRONTEND_SDKS publish_status = { "DELETE": ApiPublishStatus.EXPERIMENTAL, "GET": ApiPublishStatus.EXPERIMENTAL, } permission_classes = () def delete(self, request: Request, wizard_hash=None) -> Response | None: """ This remo...
SetupWizard
python
pytorch__pytorch
torch/_inductor/fx_passes/pre_grad.py
{ "start": 21644, "end": 22581 }
class ____: def __init__(self, node: torch.fx.Node) -> None: assert node.op == "call_function" assert node.target is torch.nn.functional.linear self.node: torch.fx.Node = node def get_input(self) -> torch.fx.Node: if len(self.node.args) > 0: return self.node.args[0] ...
NormalizedLinearNode
python
bokeh__bokeh
tests/unit/bokeh/server/test_callbacks__server.py
{ "start": 1821, "end": 2491 }
class ____: def __init__(self, quit_after=None) -> None: self.io_loop = IOLoop() self.io_loop.make_current() self.group = _CallbackGroup(self.io_loop) if quit_after is not None: self.io_loop.call_later(quit_after / 1000.0, lambda: self...
LoopAndGroup
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-cohere/llama_index/embeddings/cohere/base.py
{ "start": 931, "end": 1111 }
class ____(str, Enum): SEARCH_QUERY = "search_query" SEARCH_DOCUMENT = "search_document" CLASSIFICATION = "classification" CLUSTERING = "clustering"
CohereAIInputType
python
fastai__fastai
fastai/callback/tensorboard.py
{ "start": 1685, "end": 3505 }
class ____(TensorBoardBaseCallback): "Saves model topology, losses & metrics for tensorboard and tensorboard projector during training" def __init__(self, log_dir=None, trace_model=True, log_preds=True, n_preds=9, projector=False, layer=None): super().__init__() store_attr() def before_fit(...
TensorBoardCallback
python
pallets__flask
tests/test_reqctx.py
{ "start": 3490, "end": 8689 }
class ____: def test_greenlet_context_copying(self, app, client): greenlets = [] @app.route("/") def index(): flask.session["fizz"] = "buzz" ctx = app_ctx.copy() def g(): assert not flask.request assert not flask.current_a...
TestGreenletContextCopying
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 25895, "end": 51746 }
class ____: """Converter superclass to share functionality between V1 and V2 converters.""" # Stores the original model type temporarily to transmit the information # from the factory class methods to TFLiteConverterBase init function. _original_model_type = conversion_metadata_fb.ModelType.NONE def __init_...
TFLiteConverterBase
python
django-guardian__django-guardian
guardian/testapp/tests/test_shortcuts.py
{ "start": 32061, "end": 53875 }
class ____(TestCase): def setUp(self): self.user = User.objects.create(username="joe") self.group = Group.objects.create(name="group") self.ctype = ContentType.objects.create(model="bar", app_label="fake-for-guardian-tests") def test_superuser(self): self.user.is_superuser = Tru...
GetObjectsForUser
python
doocs__leetcode
solution/0800-0899/0805.Split Array With Same Average/Solution.py
{ "start": 0, "end": 677 }
class ____: def splitArraySameAverage(self, nums: List[int]) -> bool: n = len(nums) if n == 1: return False s = sum(nums) for i, v in enumerate(nums): nums[i] = v * n - s m = n >> 1 vis = set() for i in range(1, 1 << m): t =...
Solution
python
django__django
tests/forms_tests/field_tests/test_datefield.py
{ "start": 249, "end": 320 }
class ____(Form): mydate = DateField(widget=SelectDateWidget)
GetDate
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_reload_repository_location.py
{ "start": 3150, "end": 8438 }
class ____(MultiLocationTestSuite): def test_reload_workspace(self, graphql_context): result = execute_dagster_graphql(graphql_context, RELOAD_WORKSPACE_QUERY) assert result assert result.data assert result.data["reloadWorkspace"] assert result.data["reloadWorkspace"]["__typ...
TestReloadWorkspace
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/memcache/guestbook/main.py
{ "start": 4465, "end": 5378 }
class ____(webapp2.RequestHandler): def post(self): # We set the same parent key on the 'Greeting' to ensure each greeting # is in the same entity group. Queries across the single entity group # are strongly consistent. However, the write rate to a single entity # group is limited to...
Guestbook
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sources.py
{ "start": 1435, "end": 1844 }
class ____(NamedTuple): default_value: Any type_annotation: Type def _get_field_details(model: Type[pydantic.BaseModel], field_name: str) -> _FieldDetails: """Get the default value of the requested field and its type annotation.""" return _FieldDetails( default_value=model.__fields__[field_nam...
_FieldDetails
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 103936, "end": 108948 }
class ____: """Tests to ensure that automatic tag-based concurrency checks don't produce noisy warnings.""" def test_task_with_tags_no_concurrency_limit_no_warning_sync(self, caplog): """Verify sync tasks with tags don't log warnings when no concurrency limit exists.""" @task(tags=["test-tag"]...
TestTaskTagConcurrencyWarnings
python
doocs__leetcode
solution/0400-0499/0495.Teemo Attacking/Solution.py
{ "start": 0, "end": 221 }
class ____: def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int: ans = duration for a, b in pairwise(timeSeries): ans += min(duration, b - a) return ans
Solution
python
ray-project__ray
python/ray/train/v2/_internal/exceptions.py
{ "start": 1450, "end": 2803 }
class ____(RayTrainError): """Exception raised when the worker group startup times out. Example scenario: 4 GPUs are detected in the cluster, but when the worker are actually scheduled, one of the nodes goes down and only 3 GPUs are available. One of the worker tasks may be stuck pending, until a timeo...
WorkerGroupStartupTimeoutError
python
pytorch__pytorch
torch/_export/db/examples/assume_constant_result.py
{ "start": 78, "end": 510 }
class ____(torch.nn.Module): """ Applying `assume_constant_result` decorator to burn make non-tracable code as constant. """ @torchdynamo.assume_constant_result def get_item(self, y): return y.int().item() def forward(self, x, y): return x[: self.get_item(y)] example_args = (t...
AssumeConstantResult
python
openai__openai-python
src/openai/types/beta/realtime/session_create_params.py
{ "start": 8177, "end": 8738 }
class ____(TypedDict, total=False): group_id: str """ The group id to attach to this trace to enable filtering and grouping in the traces dashboard. """ metadata: object """ The arbitrary metadata to attach to this trace to enable filtering in the traces dashboard. """ work...
TracingTracingConfiguration
python
scrapy__scrapy
scrapy/downloadermiddlewares/useragent.py
{ "start": 420, "end": 1211 }
class ____: """This middleware allows spiders to override the user_agent""" def __init__(self, user_agent: str = "Scrapy"): self.user_agent = user_agent @classmethod def from_crawler(cls, crawler: Crawler) -> Self: o = cls(crawler.settings["USER_AGENT"]) crawler.signals.connect...
UserAgentMiddleware
python
jazzband__django-simple-history
simple_history/tests/admin.py
{ "start": 1091, "end": 1756 }
class ____(HistoricalRecordContextHelper): def prepare_delta_change_value(self, change, value): display_value = super().prepare_delta_change_value(change, value) if change.field == "places": assert isinstance(display_value, list) assert all(isinstance(place, Place) for place ...
HistoricalPollWithManyToManyContextHelper
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py
{ "start": 470, "end": 1051 }
class ____: if bool(): __slots__ = {"x": "docs for x", "m": "docs for m", "a": "docs for a"} else: __slots__ = "foo3", "foo2", "foo1" # NB: an implicit tuple (without parens) __slots__: list[str] = ["the", "three", "little", "pigs"] __slots__ = ("parenthesized_item"), "in", ("an_unpare...
Klass2
python
google__pytype
pytype/tools/xref/indexer_test.py
{ "start": 307, "end": 2006 }
class ____: """Mixin for indexer tests.""" def index_code(self, code, **kwargs): """Generate references from a code string.""" args = {"version": self.python_version} args.update(kwargs) with test_utils.Tempdir() as d: d.create_file("t.py", code) options = config.Options.create(d["t.py"...
IndexerTestMixin
python
walkccc__LeetCode
solutions/67. Add Binary/67.py
{ "start": 0, "end": 369 }
class ____: def addBinary(self, a: str, b: str) -> str: ans = [] carry = 0 i = len(a) - 1 j = len(b) - 1 while i >= 0 or j >= 0 or carry: if i >= 0: carry += int(a[i]) i -= 1 if j >= 0: carry += int(b[j]) j -= 1 ans.append(str(carry % 2)) ca...
Solution
python
walkccc__LeetCode
solutions/315. Count of Smaller Numbers After Self/315-4.py
{ "start": 93, "end": 1531 }
class ____: def countSmaller(self, nums: list[int]) -> list[int]: n = len(nums) ans = [0] * n items = [Item(num, i) for i, num in enumerate(nums)] self._mergeSort(items, 0, n - 1, ans) return ans def _mergeSort( self, items: list[Item], l: int, r: int, ans: list[i...
Solution
python
falconry__falcon
falcon/util/structures.py
{ "start": 8185, "end": 11556 }
class ____(str): """Convenience class to represent a parsed HTTP entity-tag. This class is simply a subclass of ``str`` with a few helper methods and an extra attribute to indicate whether the entity-tag is weak or strong. The value of the string is equivalent to what RFC 7232 calls an "opaque-tag", ...
ETag
python
psf__black
tests/data/cases/preview_long_strings__regression.py
{ "start": 22697, "end": 23436 }
class ____: def foo(): result = type(message)("") # Don't merge multiline (e.g. triple-quoted) strings. def foo(): query = ( """SELECT xxxxxxxxxxxxxxxxxxxx(xxx)""" """ FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""" ) # There was a bug where tuples were bein...
A
python
Pylons__pyramid
docs/quick_tutorial/forms/tutorial/views.py
{ "start": 538, "end": 2998 }
class ____: def __init__(self, request): self.request = request @property def wiki_form(self): schema = WikiPage() return deform.Form(schema, buttons=('submit',)) @property def reqts(self): return self.wiki_form.get_widget_resources() @view_config(route_name='w...
WikiViews
python
optuna__optuna
optuna/samplers/nsgaii/_child_generation_strategy.py
{ "start": 640, "end": 3841 }
class ____: def __init__( self, *, mutation_prob: float | None = None, crossover: BaseCrossover, crossover_prob: float, swapping_prob: float, constraints_func: Callable[[FrozenTrial], Sequence[float]] | None = None, rng: LazyRandomState, ) -> None:...
NSGAIIChildGenerationStrategy
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-weaviate/llama_index/readers/weaviate/base.py
{ "start": 164, "end": 4001 }
class ____(BaseReader): """ Weaviate reader. Retrieves documents from Weaviate through vector lookup. Allows option to concatenate retrieved documents into one Document, or to return separate Document objects per document. Args: host (str): host. auth_client_secret (Optional[we...
WeaviateReader
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_numeric.py
{ "start": 99897, "end": 102865 }
class ____(TestCase): def test_2x2(self): u = [1, 2] v = [3, 4] z = -2 cp = np.cross(u, v) assert_equal(cp, z) cp = np.cross(v, u) assert_equal(cp, -z) def test_2x3(self): u = [1, 2] v = [3, 4, 5] z = np.array([10, -5, -2]) ...
TestCross
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_state_or_territory.py
{ "start": 842, "end": 1890 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_us_state_or_territory" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) ...
ColumnValuesToBeValidUSState
python
getsentry__sentry
src/sentry/notifications/notification_action/types.py
{ "start": 2111, "end": 4165 }
class ____(ABC): """ Abstract base class that defines the interface for notification handlers. """ @staticmethod @abstractmethod def handle_workflow_action( event_data: WorkflowEventData, action: Action, detector: Detector ) -> None: """ Implement this method to hand...
LegacyRegistryHandler
python
pennersr__django-allauth
allauth/socialaccount/providers/amazon/views.py
{ "start": 181, "end": 1209 }
class ____(OAuth2Adapter): provider_id = "amazon" access_token_url = "https://api.amazon.com/auth/o2/token" # nosec authorize_url = "https://www.amazon.com/ap/oa" profile_url = "https://api.amazon.com/user/profile" def complete_login(self, request, app, token, **kwargs): response = ( ...
AmazonOAuth2Adapter
python
huggingface__transformers
src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py
{ "start": 7469, "end": 8184 }
class ____(nn.Module): """ The residual connection is defined in ASTLayer instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: ASTConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, conf...
ASTSelfOutput
python
huggingface__transformers
src/transformers/models/mistral/modeling_mistral.py
{ "start": 8771, "end": 9498 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ MistralRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): inpu...
MistralRMSNorm
python
django__django
tests/async/tests.py
{ "start": 2064, "end": 2184 }
class ____(View): def get(self, request, *args, **kwargs): return HttpResponse("Hello (sync) world!")
SyncView
python
ray-project__ray
release/ray_release/exception.py
{ "start": 4281, "end": 4340 }
class ____(ClusterStartupTimeout): pass
JobStartupTimeout
python
great-expectations__great_expectations
tests/integration/test_utils/data_source_config/sqlite.py
{ "start": 1505, "end": 2791 }
class ____(SQLBatchTestSetup[SqliteDatasourceTestConfig]): def __init__( self, data: pd.DataFrame, config: SqliteDatasourceTestConfig, extra_data: Mapping[str, pd.DataFrame], context: AbstractDataContext, base_dir: pathlib.Path, table_name: Optional[str] = Non...
SqliteBatchTestSetup
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 101666, "end": 102006 }
class ____(Response): """ Response of events.multi_task_scalar_metrics_iter_histogram endpoint. """ _service = "events" _action = "multi_task_scalar_metrics_iter_histogram" _version = "2.13" _schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
MultiTaskScalarMetricsIterHistogramResponse
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/input_manager.py
{ "start": 922, "end": 1321 }
class ____(ABC): """Base interface for classes that are responsible for loading solid inputs.""" @abstractmethod def load_input(self, context: "InputContext") -> object: """The user-defined read method that loads an input to a solid. Args: context (InputContext): The input cont...
InputManager
python
walkccc__LeetCode
solutions/1971. Find if Path Exists in Graph/1971.py
{ "start": 514, "end": 784 }
class ____: def validPath( self, n: int, edges: list[list[int]], source: int, destination: int, ) -> bool: uf = UnionFind(n) for u, v in edges: uf.unionByRank(u, v) return uf.find(source) == uf.find(destination)
Solution
python
getsentry__sentry
src/sentry/replays/usecases/ingest/event_logger.py
{ "start": 1264, "end": 1406 }
class ____(TypedDict): message: str view_id: str view_class: str timestamp: int event_hash: str
ReplayActionsEventPayloadTap
python
kamyu104__LeetCode-Solutions
Python/gcd-of-odd-and-even-sums.py
{ "start": 36, "end": 261 }
class ____(object): def gcdOfOddEvenSums(self, n): """ :type n: int :rtype: int """ # gcd((1+(2n-1))*n/2, (2+2n)*n/2) = gcd(n*n, n*(n+1)) = n * gcd(n, n+1) = n return n
Solution
python
jina-ai__jina
tests/unit/serve/executors/test_runtime_args.py
{ "start": 105, "end": 585 }
class ____: def __init__(self): self.lock = Lock() def test_object_not_seri(): with pytest.raises(TypeError): serialized = pickle.dumps(NotSerialisable()) def test_runtime_args_not_serialisable(): param = NotSerialisable() b = BaseExecutor.load_config( 'BaseExecutor', ...
NotSerialisable
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/schedules/ticks.py
{ "start": 1568, "end": 1896 }
class ____(graphene.ObjectType): tick_id = graphene.NonNull(graphene.String) status = graphene.NonNull(GrapheneInstigationTickStatus) timestamp = graphene.NonNull(graphene.Float) tick_specific_data = graphene.Field(GrapheneScheduleTickSpecificData) class Meta: name = "ScheduleTick"
GrapheneScheduleTick
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/pareto.py
{ "start": 1018, "end": 3693 }
class ____(Enum): NO_DOMINANCE = 0 EQUAL = 1 LEFT_DOMINATES = 2 RIGHT_DOMINATES = 3 def dominance(left: ConjectureResult, right: ConjectureResult) -> DominanceRelation: """Returns the dominance relation between ``left`` and ``right``, according to the rules that one ConjectureResult dominates ...
DominanceRelation
python
streamlit__streamlit
lib/tests/streamlit/connections/util_test.py
{ "start": 826, "end": 3548 }
class ____(unittest.TestCase): def test_extract_from_dict(self): d = {"k1": "v1", "k2": "v2", "k3": "v3", "k4": "v4"} extracted = extract_from_dict( ["k1", "k2", "nonexistent_key"], d, ) assert extracted == {"k1": "v1", "k2": "v2"} assert d == {"k3":...
ConnectionUtilTest
python
huggingface__transformers
src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py
{ "start": 36862, "end": 40994 }
class ____(RobertaPreLayerNormPreTrainedModel): _tied_weights_keys = { "lm_head.decoder.weight": "roberta_prelayernorm.embeddings.word_embeddings.weight", "lm_head.decoder.bias": "lm_head.bias", } # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.__init__ with RO...
RobertaPreLayerNormForMaskedLM
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 14703, "end": 15393 }
class ____(BaseModel): """ Schema for the request part of a Human-in-the-loop detail for a specific task instance. """ ti_id: Annotated[UUID, Field(title="Ti Id")] options: Annotated[list[str], Field(min_length=1, title="Options")] subject: Annotated[str, Field(title="Subject")] body: Annot...
HITLDetailRequest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor33.py
{ "start": 573, "end": 614 }
class ____[T: TD1]: x: T @dataclass
DC1
python
Textualize__textual
docs/examples/styles/scrollbar_size.py
{ "start": 436, "end": 658 }
class ____(App): CSS_PATH = "scrollbar_size.tcss" def compose(self): yield ScrollableContainer(Label(TEXT * 5), classes="panel") if __name__ == "__main__": app = ScrollbarApp() app.run()
ScrollbarApp
python
dagster-io__dagster
python_modules/dagster/dagster/_core/secrets/env_file.py
{ "start": 2402, "end": 3603 }
class ____(SecretsLoader, ConfigurableClass): def __init__( self, inst_data: Optional[ConfigurableClassData] = None, base_dir=None, ): self._inst_data = inst_data self._base_dir = base_dir or os.getcwd() def get_secrets_for_environment(self, location_name: Optional[s...
EnvFileLoader
python
ray-project__ray
python/ray/tests/test_ray_event_export_task_events.py
{ "start": 8828, "end": 38741 }
class ____: @_cluster_with_aggregator_target def test_normal_task_succeed( self, ray_start_cluster_head_with_env_vars, httpserver, preserve_proto_field_name, ): script = """ import ray ray.init() @ray.remote def normal_task(): pass ray.get(normal_task.remote()) ...
TestNormalTaskEvents
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 169731, "end": 176072 }
class ____(ParseExpression): """Requires that at least one :class:`ParserElement` is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the ``'^'`` operator. Example: .. testcode:: # construct Or using '^' operator ...
Or
python
spyder-ide__spyder
spyder/plugins/layout/plugin.py
{ "start": 2807, "end": 45782 }
class ____(SpyderPluginV2, SpyderShortcutsMixin): """ Layout manager plugin. """ NAME = "layout" CONF_SECTION = "quick_layouts" REQUIRES = [Plugins.All] # Uses wildcard to require all plugins CONF_FILE = False CONTAINER_CLASS = LayoutContainer CAN_BE_DISABLED = False # ---- Spy...
Layout
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/semantic_similarity.py
{ "start": 347, "end": 2806 }
class ____(BaseEvaluator): """ Embedding similarity evaluator. Evaluate the quality of a question answering system by comparing the similarity between embeddings of the generated answer and the reference answer. Inspired by this paper: - Semantic Answer Similarity for Evaluating Question A...
SemanticSimilarityEvaluator
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 64053, "end": 64407 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("app_id", "setting") app_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="appId") setting = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="setti...
CheckSuiteAutoTriggerPreference
python
encode__django-rest-framework
rest_framework/schemas/coreapi.py
{ "start": 2619, "end": 11688 }
class ____(BaseSchemaGenerator): """ Original CoreAPI version. """ # Map HTTP methods onto actions. default_mapping = { 'get': 'retrieve', 'post': 'create', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy', } # Map the method names we u...
SchemaGenerator
python
google__jax
tests/lax_test.py
{ "start": 167103, "end": 177011 }
class ____(jtu.JaxTestCase): def setUp(self): core.pytype_aval_mappings[FooArray] = \ lambda x: core.ShapedArray(x.shape, FooTy(), sharding=None) dtypes.canonicalize_value_handlers[FooArray] = lambda x: x pxla.shard_arg_handlers[FooArray] = shard_foo_array_handler mlir._constant_handlers[FooA...
CustomElementTypesTest
python
huggingface__transformers
src/transformers/models/glm4v/modular_glm4v.py
{ "start": 13000, "end": 16535 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a GLM-4.1V model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar config...
Glm4vConfig
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/methods/test_map.py
{ "start": 143, "end": 1358 }
class ____: def test_map(self): rng = date_range("1/1/2000", periods=10) f = lambda x: x.strftime("%Y%m%d") result = rng.map(f) exp = Index([f(x) for x in rng]) tm.assert_index_equal(result, exp) def test_map_fallthrough(self, capsys): # GH#22067, check we don't...
TestMap
python
ApeWorX__ape
src/ape/api/accounts.py
{ "start": 32884, "end": 33978 }
class ____(AccountAPI): """ An account to use that does not require signing. """ raw_address: AddressType """ The field-address of the account. """ @property def address(self) -> AddressType: return self.raw_address def sign_message(self, msg: Any, **signer_options) ->...
ImpersonatedAccount
python
realpython__materials
python-pydantic/pydantic_models.py
{ "start": 317, "end": 1451 }
class ____(BaseModel): employee_id: UUID = Field(default_factory=uuid4, frozen=True) name: str = Field(min_length=1, frozen=True) email: EmailStr = Field(pattern=r".+@example\.com$") date_of_birth: date = Field(alias="birth_date", repr=False, frozen=True) salary: float = Field(alias="compensation", ...
Employee
python
pennersr__django-allauth
allauth/socialaccount/providers/ynab/provider.py
{ "start": 227, "end": 267 }
class ____: ACCESS = "read-only"
Scope
python
ray-project__ray
rllib/env/base_env.py
{ "start": 447, "end": 15999 }
class ____: """The lowest-level env interface used by RLlib for sampling. BaseEnv models multiple agents executing asynchronously in multiple vectorized sub-environments. A call to `poll()` returns observations from ready agents keyed by their sub-environment ID and agent IDs, and actions for those...
BaseEnv