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
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 31972, "end": 32236 }
class ____(MixinNoReferrer, TestRefererMiddleware): settings = { "REFERRER_POLICY": "scrapy.spidermiddlewares.referer.NoReferrerWhenDowngradePolicy" } resp_headers = {"Referrer-Policy": POLICY_NO_REFERRER.swapcase()}
TestPolicyHeaderPrecedence002
python
pytorch__pytorch
torch/_dynamo/variables/base.py
{ "start": 6504, "end": 7845 }
class ____(AttributeMutation): """ This case of VariableTracker.mutation_type marker indicates 1. Dynamo allows mutation on the value's attributes. 2. The value is created by the bytecode Dynamo is tracing through. For instance, Dynamo could model a newly created object with this marker, indica...
AttributeMutationNew
python
doocs__leetcode
solution/3500-3599/3596.Minimum Cost Path with Alternating Directions I/Solution.py
{ "start": 0, "end": 233 }
class ____: def minCost(self, m: int, n: int) -> int: if m == 1 and n == 1: return 1 if m == 2 and n == 1: return 3 if m == 1 and n == 2: return 3 return -1
Solution
python
matplotlib__matplotlib
lib/matplotlib/streamplot.py
{ "start": 20494, "end": 26778 }
class ____(IndexError): pass def _integrate_rk12(x0, y0, dmap, f, maxlength, broken_streamlines=True, integration_max_step_scale=1.0, integration_max_error_scale=1.0): """ 2nd-order Runge-Kutta algorithm with adaptive step size. This method is also referred to ...
OutOfBounds
python
ray-project__ray
python/ray/tune/syncer.py
{ "start": 242, "end": 2172 }
class ____(TrainSyncConfig): """Configuration object for Tune file syncing to `RunConfig(storage_path)`. In Ray Tune, here is where syncing (mainly uploading) happens: The experiment driver (on the head node) syncs the experiment directory to storage (which includes experiment state such as searcher s...
SyncConfig
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_events_reader.py
{ "start": 22501, "end": 25206 }
class ____(BaseDigest): """Data object describing the creation of an op inside a graph. For size efficiency, this digest object does not contain any stack frames or any references to them. To obtain the stack frames, use `DataReader.read_graph_op_creation_stack_trace()`. Properties (beyond the base class): ...
GraphOpCreationDigest
python
kamyu104__LeetCode-Solutions
Python/maximum-product-of-subsequences-with-an-alternating-sum-equal-to-k.py
{ "start": 83, "end": 1071 }
class ____(object): def maxProduct(self, nums, k, limit): """ :type nums: List[int] :type k: int :type limit: int :rtype: int """ total = sum(nums) if k > total or k < -total: # optimized to speed up return -1 dp = collections.defa...
Solution
python
keras-team__keras
keras/src/legacy/saving/serialization.py
{ "start": 2901, "end": 4397 }
class ____: """A context manager for keeping track of loaded objects. During the deserialization process, we may come across objects that are shared across multiple layers. In order to accurately restore the network structure to its original state, `SharedObjectLoadingScope` allows us to re-use sha...
SharedObjectLoadingScope
python
dask__dask
dask/_expr.py
{ "start": 32716, "end": 32863 }
class ____(HLGExpr): # Identical to HLGExpr # Used internally to determine how output keys are supposed to be returned pass
_HLGExprGroup
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_callback.py
{ "start": 8030, "end": 9339 }
class ____: @pytest.mark.parametrize( ("callback_callable", "executor"), [ pytest.param(empty_sync_callback_for_deadline_tests, "remote", id="with_executor"), pytest.param(empty_sync_callback_for_deadline_tests, None, id="without_executor"), pytest.param(qualname(...
TestSyncCallback
python
django__django
tests/custom_lookups/tests.py
{ "start": 3704, "end": 4545 }
class ____(models.lookups.LessThanOrEqual): """ The purpose of this lookup is to efficiently compare the year of the field. """ def as_sql(self, compiler, connection): # Skip the YearTransform above us (no possibility for efficient # lookup otherwise). real_lhs = self.lhs.lhs ...
YearLte
python
getsentry__sentry
src/sentry/sentry_metrics/consumers/last_seen_updater.py
{ "start": 3366, "end": 5755 }
class ____(ProcessingStrategyFactory[KafkaPayload]): def __init__( self, max_batch_size: int, max_batch_time: float, ingest_profile: str, indexer_db: str, ) -> None: from sentry.sentry_metrics.configuration import ( IndexerStorage, UseCaseK...
LastSeenUpdaterStrategyFactory
python
readthedocs__readthedocs.org
readthedocs/audit/tests/test_models.py
{ "start": 290, "end": 3451 }
class ____(TestCase): def setUp(self): self.user = get(User) self.project = get(Project, users=[self.user]) self.organization = get(Organization, projects=[self.project]) get(OrganizationOwner, organization=self.organization, owner=self.user) self.auditlog = get( ...
TestAuditModels
python
tornadoweb__tornado
tornado/routing.py
{ "start": 23103, "end": 25140 }
class ____(Rule): """Specifies mappings between URLs and handlers. .. versionchanged: 4.5 `URLSpec` is now a subclass of a `Rule` with `PathMatches` matcher and is preserved for backwards compatibility. """ def __init__( self, pattern: Union[str, Pattern], handler...
URLSpec
python
PrefectHQ__prefect
src/integrations/prefect-gitlab/prefect_gitlab/repositories.py
{ "start": 1812, "end": 6479 }
class ____(ReadableDeploymentStorage): """ Interact with files stored in GitLab repositories. An accessible installation of git is required for this block to function properly. """ _block_type_name = "GitLab Repository" _logo_url = "https://images.ctfassets.net/gm98wzqotmnx/55edIimT4g9gbjh...
GitLabRepository
python
kamyu104__LeetCode-Solutions
Python/largest-triangle-area.py
{ "start": 32, "end": 844 }
class ____(object): def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ result = 0 for i in xrange(len(points)-2): for j in xrange(i+1, len(points)-1): for k in xrange(j+1, len(points)): ...
Solution
python
kamyu104__LeetCode-Solutions
Python/decode-string.py
{ "start": 29, "end": 608 }
class ____(object): def decodeString(self, s): """ :type s: str :rtype: str """ n, curr, nums, strs = 0, [], [], [] for c in s: if c.isdigit(): n = n*10 + ord(c)-ord('0') elif c.isalpha(): curr.append(c) ...
Solution
python
skorch-dev__skorch
skorch/tests/test_doctor.py
{ "start": 22074, "end": 29178 }
class ____: """Tests based on a more non-standard model Specifically, add modules with non-standard names and non-standard outputs like tuples or dicts. This test class does not re-iterate all the tests performed on the standard model but focuses on the parts that change, e.g. how the outputs are ...
TestSkorchDoctorComplexArchitecture
python
django-haystack__django-haystack
haystack/query.py
{ "start": 24415, "end": 26069 }
class ____(SearchQuerySet): """ A variant of the SearchQuerySet that can handle `load_all_queryset`s. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._load_all_querysets = {} self._result_cache = [] def _load_model_objects(self, model, pks): ...
RelatedSearchQuerySet
python
pytorch__pytorch
torch/nn/modules/_functions.py
{ "start": 120, "end": 8432 }
class ____(Function): @staticmethod # pyrefly: ignore [bad-override] def forward( self, input, weight, bias, running_mean, running_var, eps, momentum, process_group, world_size, ): if not ( input.is_conti...
SyncBatchNorm
python
scipy__scipy
scipy/stats/tests/test_multivariate.py
{ "start": 1834, "end": 12926 }
class ____: def test_input_validation(self): message = "The input `precision` must be a square, two-dimensional..." with pytest.raises(ValueError, match=message): _covariance.CovViaPrecision(np.ones(2)) message = "`precision.shape` must equal `covariance.shape`." with ...
TestCovariance
python
kamyu104__LeetCode-Solutions
Python/kth-smallest-element-in-a-bst.py
{ "start": 586, "end": 1037 }
class ____(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ def gen_inorder(root): if root: for n in gen_inorder(root.left): yield n yield root.val ...
Solution2
python
dagster-io__dagster
python_modules/dagster/dagster/_config/errors.py
{ "start": 1595, "end": 1700 }
class ____: config_type_snap: ConfigTypeSnap value_rep: str @record_custom
RuntimeMismatchErrorData
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_rds.py
{ "start": 25736, "end": 28529 }
class ____: @classmethod def setup_class(cls): cls.dag = DAG( dag_id="test_dag", schedule=None, default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, ) cls.hook = RdsHook(aws_conn_id=AWS_CONN, region_name="us-east-1") _patch_hook_get_c...
TestRdsCreateEventSubscriptionOperator
python
numba__numba
numba/tests/enum_usecases.py
{ "start": 513, "end": 590 }
class ____(Enum): red = 1.0 green = 2.0 blue = 3j
HeterogeneousEnum
python
huggingface__transformers
src/transformers/models/lfm2_vl/processing_lfm2_vl.py
{ "start": 1034, "end": 1130 }
class ____(TextKwargs, total=False): use_image_special_tokens: Optional[bool]
Lfm2VlTextKwargs
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 2701, "end": 2984 }
class ____(StrictBaseModel): """Schema for updating TaskInstance to a terminal state except SUCCESS state.""" state: TerminalStateNonSuccess end_date: UtcDateTime """When the task completed executing""" rendered_map_index: str | None = None
TITerminalStatePayload
python
rapidsai__cudf
python/cudf/cudf/core/join/_join_helpers.py
{ "start": 1363, "end": 6545 }
class ____(_Indexer): def get(self, obj: DataFrame) -> ColumnBase: return obj.index._data[self.name] def set(self, obj: DataFrame, value: ColumnBase): obj.index._data.set_by_label(self.name, value) def _match_join_keys( lcol: ColumnBase, rcol: ColumnBase, how: str ) -> tuple[ColumnBase, C...
_IndexIndexer
python
ansible__ansible
test/lib/ansible_test/_internal/cli/compat.py
{ "start": 3114, "end": 3480 }
class ____(ApplicationError): """Option(s) were specified which do not provide support for the controller and would be ignored because they are irrelevant for the target.""" def __init__(self, context: str) -> None: super().__init__(f'Environment `{context}` does not provide a Python version supported ...
ControllerNotSupportedError
python
PrefectHQ__prefect
tests/server/schemas/test_core.py
{ "start": 1948, "end": 2496 }
class ____: async def test_block_document_reference_different_parent_and_ref(self): same_id = uuid4() with pytest.raises( ValueError, match=( "`parent_block_document_id` and `reference_block_document_id` cannot be" " the same" ), ...
TestBlockDocumentReference
python
mlflow__mlflow
mlflow/store/_unity_catalog/registry/rest_store.py
{ "start": 12667, "end": 74745 }
class ____(BaseRestStore): """ Client for a remote model registry server accessed via REST API calls Args: store_uri: URI with scheme 'databricks-uc' tracking_uri: URI of the Databricks MLflow tracking server from which to fetch run info and download run artifacts, when creating...
UcModelRegistryStore
python
scikit-learn__scikit-learn
sklearn/feature_selection/_base.py
{ "start": 609, "end": 9456 }
class ____(TransformerMixin, metaclass=ABCMeta): """ Transformer mixin that performs feature selection given a support mask This mixin provides a feature selector implementation with `transform` and `inverse_transform` functionality given an implementation of `_get_support_mask`. Examples ...
SelectorMixin
python
mahmoud__boltons
boltons/iterutils.py
{ "start": 49886, "end": 51608 }
class ____: """The GUIDerator is an iterator that yields a globally-unique identifier (GUID) on every iteration. The GUIDs produced are hexadecimal strings. Testing shows it to be around 12x faster than the uuid module. By default it is also more compact, partly due to its default 96-bit (24-he...
GUIDerator
python
ray-project__ray
python/ray/serve/_private/benchmarks/locust_utils.py
{ "start": 499, "end": 762 }
class ____: history: List[Dict] total_requests: int num_failures: int avg_latency: float p50_latency: float p90_latency: float p99_latency: float avg_rps: float stats_in_stages: List[PerformanceStats] @dataclass
LocustTestResults
python
wandb__wandb
wandb/sdk/artifacts/_gqlutils.py
{ "start": 4211, "end": 8872 }
class ____: org_name: str entity_name: str def __contains__(self, other: str) -> bool: return other in {self.org_name, self.entity_name} def resolve_org_entity_name( client: RetryingClient, non_org_entity: str | None, org_or_entity: str | None = None, ) -> str: # Resolve the portf...
OrgInfo
python
scikit-image__scikit-image
benchmarks/benchmark_rank.py
{ "start": 612, "end": 1019 }
class ____: param_names = ["filter3d", "shape3d"] params = [sorted(all_3d_rank_filters), [(32, 32, 32), (128, 128, 128)]] def setup(self, filter3d, shape3d): self.volume = np.random.randint(0, 255, size=shape3d, dtype=np.uint8) self.footprint_3d = ball(1) def time_3d_filters(self, filt...
Rank3DSuite
python
wandb__wandb
wandb/vendor/pygments/lexers/special.py
{ "start": 422, "end": 820 }
class ____(Lexer): """ "Null" lexer, doesn't highlight anything. """ name = 'Text only' aliases = ['text'] filenames = ['*.txt'] mimetypes = ['text/plain'] priority = 0.01 def get_tokens_unprocessed(self, text): yield 0, Text, text def analyse_text(text): return...
TextLexer
python
pypa__pip
src/pip/_vendor/urllib3/connection.py
{ "start": 1967, "end": 10127 }
class ____(_HTTPConnection, object): """ Based on :class:`http.client.HTTPConnection` but provides an extra constructor backwards-compatibility layer between older and newer Pythons. Additional keyword parameters are used to configure attributes of the connection. Accepted parameters include: ...
HTTPConnection
python
geekcomputers__Python
QuestionAnswerVirtualAssistant/backend.py
{ "start": 109, "end": 8495 }
class ____: """ Used for automatic question-answering It works by building a reverse index store that maps words to an id. To find the indexed questions that contain a certain the words in the user question, we then take an intersection of the ids, ranks the questions to pick the best fit, ...
QuestionAnswerVirtualAssistant
python
ray-project__ray
python/ray/serve/tests/test_api.py
{ "start": 1311, "end": 1479 }
class ____: def __init__(self): self.count = 0 def __call__(self): self.count += 1 return {"count": self.count} @serve.deployment
Counter
python
django__django
tests/user_commands/management/commands/reverse_url.py
{ "start": 86, "end": 260 }
class ____(BaseCommand): """ This command returns a URL from a reverse() call. """ def handle(self, *args, **options): return reverse("some_url")
Command
python
ApeWorX__ape
src/ape/managers/project.py
{ "start": 83698, "end": 84450 }
class ____(ProjectAPI): """ A project with more than 1 valid project API configs, such as a Foundry project containing an ``ape-config.yaml`` file. """ apis: list[ProjectAPI] = [] """ An ordered list of APIs to use. The last items take precedence as their configs merge. """ @proper...
MultiProject
python
great-expectations__great_expectations
great_expectations/expectations/row_conditions.py
{ "start": 2217, "end": 4584 }
class ____(BaseModel): """ Specify the column in a condition statement. """ name: str def __init__(self, name: str): super().__init__(name=name) @override def __hash__(self) -> int: return hash(self.name) @override def __eq__(self, other: Parameter) -> ComparisonC...
Column
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/destination_pgvector/pgvector_processor.py
{ "start": 1846, "end": 2034 }
class ____(Protocol): """A protocol for embedding configuration. This is necessary because embedding configs do not have a shared base class. """ mode: str
EmbeddingConfig
python
explosion__spaCy
spacy/lang/ti/__init__.py
{ "start": 324, "end": 735 }
class ____(BaseDefaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[LANG] = lambda text: "ti" tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS suffixes = TOKENIZER_SUFFIXES w...
TigrinyaDefaults
python
joke2k__faker
faker/providers/date_time/no_NO/__init__.py
{ "start": 46, "end": 782 }
class ____(DateTimeProvider): MONTH_NAMES = { "01": "januar", "02": "februar", "03": "mars", "04": "april", "05": "mai", "06": "juni", "07": "juli", "08": "august", "09": "september", "10": "oktober", "11": "november", "...
Provider
python
plotly__plotly.py
plotly/graph_objs/funnelarea/marker/_line.py
{ "start": 233, "end": 4750 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "funnelarea.marker" _path_str = "funnelarea.marker.line" _valid_props = {"color", "colorsrc", "width", "widthsrc"} @property def color(self): """ Sets the color of the line enclosing each sector. Defaults to the `paper_...
Line
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 25082, "end": 26117 }
class ____(object): """* jina gRPC service to trigger a snapshot at the Executor Runtime. """ def restore_status(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method no...
JinaExecutorRestoreProgressServicer
python
sympy__sympy
sympy/logic/boolalg.py
{ "start": 34885, "end": 35497 }
class ____(BooleanFunction): """ Logical NAND function. It evaluates its arguments in order, giving True immediately if any of them are False, and False if they are all True. Returns True if any of the arguments are False Returns False if all arguments are True Examples ======== ...
Nand
python
doocs__leetcode
solution/0000-0099/0040.Combination Sum II/Solution2.py
{ "start": 0, "end": 607 }
class ____: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: def dfs(i: int, s: int): if s == 0: ans.append(t[:]) return if i >= len(candidates) or s < candidates[i]: return x = candidates[i]...
Solution
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 7905, "end": 8587 }
class ____: """https://github.com/pylint-dev/pylint/issues/4837""" __defaults = {} __defaults_set = False def __init__(self, value): self.value = value def __init_defaults(self): # [unused-private-member] if not self.__defaults_set: type(self).__defaults = { "fur": "pi...
Pony
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-memos/llama_index/readers/memos/base.py
{ "start": 196, "end": 1492 }
class ____(BaseReader): """ Memos reader. Reads content from an Memos. """ def __init__(self, host: str = "https://demo.usememos.com/") -> None: """Init params.""" self._memoUrl = urljoin(host, "api/memo") def load_data(self, params: Dict = {}) -> List[Document]: """ ...
MemosReader
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_checkpoint_test.py
{ "start": 1749, "end": 14383 }
class ____(tpu_embedding_base_test.TPUEmbeddingBaseTest): def make_checkpoint_and_get_embedding(self, name, model, num_rows): """Saves model to checkpoint name, retrieves embedding variables.""" checkpoint = util.Checkpoint(model=model) checkpoint.save(self._get_tmpdir(name, 'save')) # Get the name ...
TPUEmbeddingCheckpointTest
python
sphinx-doc__sphinx
sphinx/environment/__init__.py
{ "start": 35485, "end": 43484 }
class ____: """Temporary data storage while reading a document. This class is only for internal use. Please don't use this in your extensions. It will be removed or changed without notice. The only stable API is via ``env.current_document``. """ __slots__ = ( '_parser', '_seria...
_CurrentDocument
python
gawel__pyquery
pyquery/pyquery.py
{ "start": 4976, "end": 54154 }
class ____(list): """The main class """ _translator_class = JQueryTranslator def __init__(self, *args, **kwargs): html = None elements = [] self._base_url = None self.parser = kwargs.pop('parser', None) if 'parent' in kwargs: self._parent = kwargs.p...
PyQuery
python
sympy__sympy
sympy/polys/domains/expressionrawdomain.py
{ "start": 375, "end": 1448 }
class ____(Field, CharacteristicZero, SimpleDomain): """A class for arbitrary expressions but without automatic simplification. """ is_SymbolicRawDomain = is_EXRAW = True dtype = Expr zero = S.Zero one = S.One rep = 'EXRAW' has_assoc_Ring = False has_assoc_Field = True def __in...
ExpressionRawDomain
python
huggingface__transformers
src/transformers/models/jamba/modular_jamba.py
{ "start": 22728, "end": 22767 }
class ____(MistralMLP): pass
JambaMLP
python
pytorch__pytorch
torch/ao/nn/quantized/modules/normalization.py
{ "start": 158, "end": 2339 }
class ____(torch.nn.LayerNorm): r"""This is the quantized version of :class:`~torch.nn.LayerNorm`. Additional args: * **scale** - quantization scale of the output, type: double. * **zero_point** - quantization zero point of the output, type: long. """ def __init__( self, ...
LayerNorm
python
getsentry__sentry
tests/sentry/utils/test_geo.py
{ "start": 217, "end": 676 }
class ____(TestCase): def test_geo_by_addr(self) -> None: import importlib import sentry.utils.geo importlib.reload(sentry.utils.geo) from sentry.utils.geo import geo_by_addr assert geo_by_addr("8.8.8.8") == { "country_code": "US", "region": "CA", ...
TestGeo
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/kwargsUnpack1.py
{ "start": 353, "end": 1785 }
class ____(TD1): v3: Required[str] def func1(**kwargs: Unpack[TD2]) -> None: v1 = kwargs["v1"] reveal_type(v1, expected_text="int") # This should generate an error because v2 might not be present. kwargs["v2"] if "v2" in kwargs: v2 = kwargs["v2"] reveal_type(v2, expected_text...
TD2
python
geekcomputers__Python
brickout-game/brickout-game.py
{ "start": 2643, "end": 3470 }
class ____(object): def __init__(self, screen, width, height, x, y): self.__screen = screen self._width = width self._height = height self._xLoc = x self._yLoc = y w, h = pygame.display.get_surface().get_size() self.__W = w self.__H = h def draw(s...
Paddle
python
numpy__numpy
benchmarks/benchmarks/bench_core.py
{ "start": 3094, "end": 3638 }
class ____(Benchmark): params = [[50, 1000, int(1e5)], [10, 100, 1000, int(1e4)], ['valid', 'same', 'full']] param_names = ['size1', 'size2', 'mode'] def setup(self, size1, size2, mode): self.x1 = np.linspace(0, 1, num=size1) self.x2 = np.cos(np.linspace(0, 2 * n...
CorrConv
python
huggingface__transformers
tests/models/conditional_detr/test_modeling_conditional_detr.py
{ "start": 1448, "end": 6642 }
class ____: def __init__( self, parent, batch_size=8, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=8, intermediate_size=4, hidden_act="gelu", hidden_dropout_prob=0.1, attent...
ConditionalDetrModelTester
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 2760, "end": 3365 }
class ____(ConcreteTemplate): key = cuda.shfl_sync_intrinsic cases = [ signature(types.Tuple((types.i4, types.b1)), types.i4, types.i4, types.i4, types.i4, types.i4), signature(types.Tuple((types.i8, types.b1)), types.i4, types.i4, types.i8, types.i4, types.i4...
Cuda_shfl_sync_intrinsic
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-maritalk/llama_index/llms/maritalk/base.py
{ "start": 863, "end": 1742 }
class ____(HTTPError): def __init__(self, request_obj: Response) -> None: self.request_obj = request_obj try: response_json = request_obj.json() if "detail" in response_json: api_message = response_json["detail"] elif "message" in response_json: ...
MaritalkHTTPError
python
django__django
tests/m2m_through_regress/test_multitable.py
{ "start": 155, "end": 2297 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.alice = Person.objects.create(name="Alice") cls.bob = Person.objects.create(name="Bob") cls.chris = Person.objects.create(name="Chris") cls.dan = Person.objects.create(name="Dan") cls.team_alpha = Group.object...
MultiTableTests
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 228245, "end": 243156 }
class ____(ConditionalStringFieldDef): r""" ConditionalParameterStringFieldDef schema wrapper. Parameters ---------- param : str, :class:`ParameterName` Filter using a parameter name. aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp...
ConditionalParameterStringFieldDef
python
numba__numba
numba/cuda/stubs.py
{ "start": 4267, "end": 4551 }
class ____(Stub): ''' shfl_sync_intrinsic(mask, mode, value, mode_offset, clamp) Nvvm intrinsic for shuffling data across a warp docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-datamove ''' _description_ = '<shfl_sync()>'
shfl_sync_intrinsic
python
pyca__cryptography
src/cryptography/x509/certificate_transparency.py
{ "start": 398, "end": 438 }
class ____(utils.Enum): v1 = 0
Version
python
doocs__leetcode
solution/1300-1399/1318.Minimum Flips to Make a OR b Equal to c/Solution.py
{ "start": 0, "end": 254 }
class ____: def minFlips(self, a: int, b: int, c: int) -> int: ans = 0 for i in range(32): x, y, z = a >> i & 1, b >> i & 1, c >> i & 1 ans += x + y if z == 0 else int(x == 0 and y == 0) return ans
Solution
python
ray-project__ray
python/ray/llm/_internal/batch/stages/prepare_image_stage.py
{ "start": 9138, "end": 12922 }
class ____(StatefulStageUDF): def __init__(self, data_column: str, expected_input_keys: List[str]): super().__init__(data_column, expected_input_keys) self.Image = importlib.import_module("PIL.Image") self.image_processor = ImageProcessor() def extract_image_info(self, messages: List[Di...
PrepareImageUDF
python
conda__conda
conda/plugins/types.py
{ "start": 11034, "end": 11328 }
class ____(ABC): def __init__(self, message: str, fail_message: str = "failed\n"): self.message = message self.fail_message = fail_message @abstractmethod def __enter__(self): ... @abstractmethod def __exit__(self, exc_type, exc_val, exc_tb): ...
SpinnerBase
python
pallets__click
src/click/testing.py
{ "start": 3679, "end": 6336 }
class ____: """Holds the captured result of an invoked CLI script. :param runner: The runner that created the result :param stdout_bytes: The standard output as bytes. :param stderr_bytes: The standard error as bytes. :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the ...
Result
python
django-haystack__django-haystack
test_haystack/test_loading.py
{ "start": 8109, "end": 8376 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) author = indexes.MultiValueField(stored=False) title = indexes.CharField(indexed=False) def get_model(self): return MockModel
MultiValueValidSearchIndex
python
django__django
tests/indexes/tests.py
{ "start": 14724, "end": 21932 }
class ____(TransactionTestCase): # Schema editor is used to create the index to test that it works. available_apps = ["indexes"] def test_partial_index(self): with connection.schema_editor() as editor: index = Index( name="recent_article_idx", fields=["pu...
PartialIndexTests
python
getsentry__sentry
src/sentry/issue_detection/detectors/experiments/mn_plus_one_db_span_detector.py
{ "start": 5525, "end": 15498 }
class ____(MNPlusOneState): """ The state for when we think we might have found a pattern: a sequence of spans that has begun to repeat. When the sequence is broken (either by a mismatched span or span iteration finishing), returns to the SearchingMNPlusOne state, possibly returning a Performan...
ContinuingMNPlusOne
python
getsentry__sentry
tests/sentry/releases/endpoints/test_project_release_file_details.py
{ "start": 7064, "end": 9059 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) releasefile = ReleaseFile.obj...
ReleaseFileUpdateTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/tensor_array_ops_test.py
{ "start": 70545, "end": 71875 }
class ____(test.Benchmark): def _tensorArrayWriteInWhile(self): size = 10000 ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=size) (_, ta) = while_loop.while_loop( lambda i, _: i < size, lambda i, ta: (i + 1, ta.write(i, 0.)), [0, ta], parallel_iterations=1) retur...
TensorArrayBenchmark
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/mpi/package.py
{ "start": 188, "end": 390 }
class ____(Package): """Virtual package for the Message Passing Interface.""" homepage = "https://www.mpi-forum.org/" virtual = True def test_hello(self): print("Hello there!")
Mpi
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_discrete_entropy_to_be_between.py
{ "start": 4377, "end": 14168 }
class ____(ColumnAggregateExpectation): """Expect the column discrete entropy to be between a minimum value and a maximum value. The Shannon entropy of a discrete probability distribution is given by - \\sum_{i=1}^{n} P(x_i) * \\log(P(x_i)) where P(x_i) is the probability of occu...
ExpectColumnDiscreteEntropyToBeBetween
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_F.py
{ "start": 38, "end": 1305 }
class ____(Benchmark): r""" FreudensteinRoth objective function. This class defines the Freudenstein & Roth [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{FreudensteinRoth}}(x) = \left\{x_1 - 13 + \left[(5 - x_2) x_2 ...
FreudensteinRoth
python
numpy__numpy
benchmarks/benchmarks/bench_random.py
{ "start": 2067, "end": 3386 }
class ____(Benchmark): param_names = ['rng'] params = ['PCG64', 'MT19937', 'Philox', 'SFC64', 'numpy'] def setup(self, bitgen): if bitgen == 'numpy': self.rg = np.random.RandomState() else: self.rg = Generator(getattr(np.random, bitgen)()) self.rg.random() ...
RNG
python
getsentry__sentry
tests/sentry/auth/authenticators/test_u2f.py
{ "start": 459, "end": 5930 }
class ____(TestCase): def setUp(self) -> None: self.u2f = U2fInterface() self.login_as(user=self.user) rp = PublicKeyCredentialRpEntity("richardmasentry.ngrok.io", "Sentry") self.test_registration_server = Fido2Server(rp, verify_origin=lambda origin: True) self.response = { ...
U2FInterfaceTest
python
google__jax
tests/pallas/mgpu_matmul_test.py
{ "start": 2725, "end": 10444 }
class ____(jtu.JaxTestCase): def setUp(self): super().setUp() if not jtu.test_device_matches(["cuda"]): self.skipTest("Test requires an NVIDIA GPU") self.enter_context(pallas_call._PALLAS_USE_MOSAIC_GPU(True)) @parameterized.product( m=(4096,), k=(4096,), n=(4096,), tile_...
MatrixMultiplicationSm90ATest
python
facebook__pyre-check
documentation/examples/pytorch/sources/simple_operations.py
{ "start": 466, "end": 1656 }
class ____: pass T1: Tensor[int32, [D1, D2]] = Tensor() T2: Tensor[int32, [D2, D3]] = Tensor() T3: Tensor[int32, [T, T]] = Tensor() T4: Tensor[float32, [D1, D2]] = Tensor() # T1 + T1 is correctly typed T1p1: Tensor[int32, [D1, D2]] = T1 + T1 # T1 * T2 is correctly typed T1m2: Tensor[int32, [D1, D3]] = mm(T1, T2...
T
python
keras-team__keras
keras/src/layers/pooling/max_pooling1d.py
{ "start": 181, "end": 3346 }
class ____(BasePooling): """Max pooling operation for 1D temporal data. Downsamples the input representation by taking the maximum value over a spatial window of size `pool_size`. The window is shifted by `strides`. The resulting output when using the `"valid"` padding option has a shape of: `outp...
MaxPooling1D
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk3.py
{ "start": 1539, "end": 11899 }
class ____(_FigureCanvasGTK, Gtk.DrawingArea): required_interactive_framework = "gtk3" manager_class = _api.classproperty(lambda cls: FigureManagerGTK3) # Setting this as a static constant prevents # this resulting expression from leaking event_mask = (Gdk.EventMask.BUTTON_PRESS_MASK ...
FigureCanvasGTK3
python
huggingface__transformers
src/transformers/models/whisper/configuration_whisper.py
{ "start": 1922, "end": 14619 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`WhisperModel`]. It is used to instantiate a Whisper model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar confi...
WhisperConfig
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_queried_column_value_frequency_to_meet_threshold.py
{ "start": 675, "end": 7003 }
class ____(QueryExpectation): """Expect the frequency of occurrences of a specified value in a queried column to be at least <threshold> percent of values in that column.""" column: str threshold: Union[float, List[float]] value: Union[str, List[str]] metric_dependencies = ("query.column",) q...
ExpectQueriedColumnValueFrequencyToMeetThreshold
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess3.py
{ "start": 1002, "end": 1097 }
class ____(Parent[_TChild]): def __init__(self, val: _TChild): self.member1 = val
Child
python
walkccc__LeetCode
solutions/158. Read N Characters Given Read4 II - Call multiple times/158.py
{ "start": 82, "end": 618 }
class ____: def read(self, buf: list[str], n: int) -> int: i = 0 # buf's index while i < n: if self.i4 == self.n4: # All the characters in the buf4 are consumed. self.i4 = 0 # Reset the buf4's index. # Read <= 4 characters from the file to the buf4. self.n4 = read4(self.buf4)...
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/student_t_test.py
{ "start": 1529, "end": 19332 }
class ____(test.TestCase): def testStudentPDFAndLogPDF(self): batch_size = 6 df = constant_op.constant([3.] * batch_size) mu = constant_op.constant([7.] * batch_size) sigma = constant_op.constant([8.] * batch_size) df_v = 3. mu_v = 7. sigma_v = 8. t = np.array([-2.5, 2.5, 8., 0., -1.,...
StudentTTest
python
openai__openai-python
src/openai/types/chat/completion_create_params.py
{ "start": 16577, "end": 17262 }
class ____(CompletionCreateParamsBase, total=False): stream: Optional[Literal[False]] """ If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#...
CompletionCreateParamsNonStreaming
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_object_position08.py
{ "start": 315, "end": 1688 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("object_position08.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self...
TestCompareXLSXFiles
python
getsentry__sentry
tests/sentry/workflow_engine/handlers/condition/test_latest_release_handler.py
{ "start": 636, "end": 6228 }
class ____(ConditionTestCase): condition = Condition.LATEST_RELEASE payload = { "id": LatestReleaseFilter.id, } def setUp(self) -> None: super().setUp() self.event_data = WorkflowEventData(event=self.group_event, group=self.group_event.group) self.dc = self.create_data_c...
TestLatestReleaseCondition
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/database.py
{ "start": 5557, "end": 12729 }
class ____(metaclass=_EDMeta): """ A Hypothesis database, for use in |settings.database|. Hypothesis automatically saves failures to the database set in |settings.database|. The next time the test is run, Hypothesis will replay any failures from the database in |settings.database| for that test (in...
ExampleDatabase
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/overview/main.py
{ "start": 2893, "end": 3543 }
class ____(webapp2.RequestHandler): def post(self): # We set the parent key on each 'Greeting' to ensure each guestbook's # greetings are in the same entity group. guestbook_name = self.request.get("guestbook_name") greeting = Greeting( parent=ndb.Key("Book", guestbook_na...
SubmitForm
python
davidhalter__jedi
jedi/inference/value/iterable.py
{ "start": 4559, "end": 6373 }
class ____: @inference_state_method_cache() def _get_comp_for_context(self, parent_context, comp_for): return CompForContext(parent_context, comp_for) def _nested(self, comp_fors, parent_context=None): comp_for = comp_fors[0] is_async = comp_for.parent.type == 'comp_for' i...
ComprehensionMixin
python
run-llama__llama_index
llama-index-core/llama_index/core/llms/mock.py
{ "start": 638, "end": 2945 }
class ____(CustomLLM): max_tokens: Optional[int] def __init__( self, max_tokens: Optional[int] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[MessagesToPromptType] = None, completion_t...
MockLLM
python
eriklindernoren__ML-From-Scratch
mlfromscratch/supervised_learning/k_nearest_neighbors.py
{ "start": 119, "end": 1265 }
class ____(): """ K Nearest Neighbors classifier. Parameters: ----------- k: int The number of closest neighbors that will determine the class of the sample that we wish to predict. """ def __init__(self, k=5): self.k = k def _vote(self, neighbor_labels): "...
KNN