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
huggingface__transformers
tests/models/mistral/test_modeling_mistral.py
{ "start": 16776, "end": 22632 }
class ____(unittest.TestCase): model_name = "mistralai/Mistral-7B-v0.1" model = None model_dtype = None @classmethod def setUpClass(cls): cleanup(torch_device, gc_collect=True) if cls.model_dtype is None: cls.model_dtype = torch.float16 if cls.model is None: ...
Mask4DTestHard
python
openai__openai-python
src/openai/types/static_file_chunking_strategy.py
{ "start": 163, "end": 595 }
class ____(BaseModel): chunk_overlap_tokens: int """The number of tokens that overlap between chunks. The default value is `400`. Note that the overlap must not exceed half of `max_chunk_size_tokens`. """ max_chunk_size_tokens: int """The maximum number of tokens in each chunk. The defaul...
StaticFileChunkingStrategy
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass1.py
{ "start": 1626, "end": 1830 }
class ____(Generic[T1]): # This should generate an error. x: T1 = 1 v7_1 = DC7() reveal_type(v7_1, expected_text="DC7[int]") # This should generate an error. v7_2: DC7[str] = DC7() @dataclass
DC7
python
tornadoweb__tornado
tornado/test/httputil_test.py
{ "start": 8982, "end": 16967 }
class ____(unittest.TestCase): def test_multi_line(self): # Lines beginning with whitespace are appended to the previous line # with any leading whitespace replaced by a single space. # Note that while multi-line headers are a part of the HTTP spec, # their use is strongly discourage...
HTTPHeadersTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py
{ "start": 512, "end": 721 }
class ____: def __new__(cls, *args: object, **kwargs: object) -> Self: ... # This should generate an error if reportInconsistentConstructor is enabled. def __init__(self, a: int) -> None: ...
Class3
python
astropy__astropy
astropy/units/tests/test_quantity_ufuncs.py
{ "start": 29432, "end": 31835 }
class ____: @pytest.mark.parametrize( "ufunc", [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal, np.equal], ) def test_comparison_valid_units(self, ufunc): q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s q_i2 = np.array([10.0, -5.0, 1.0e6]) * u.g / u.Ms ...
TestComparisonUfuncs
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 4411, "end": 5126 }
class ____(MetaFeature): """ Calculate the number of classes. Calls np.unique on the targets. If the dataset is a multilabel dataset, does this for each label seperately and returns the mean. """ def _calculate(self, X, y, logger, feat_type): if type_of_target(y) == "multilabel-indicat...
NumberOfClasses
python
kamyu104__LeetCode-Solutions
Python/multiply-strings.py
{ "start": 653, "end": 1324 }
class ____(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ num1, num2 = num1[::-1], num2[::-1] result = [0]*(len(num1)+len(num2)) for i in xrange(len(num1)): for j in xrange(len(num2)): ...
Solution2
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-visible-points.py
{ "start": 47, "end": 813 }
class ____(object): def visiblePoints(self, points, angle, location): """ :type points: List[List[int]] :type angle: int :type location: List[int] :rtype: int """ arr, extra = [], 0 for p in points: if p == location: extra +...
Solution
python
pennersr__django-allauth
allauth/socialaccount/providers/slack/provider.py
{ "start": 406, "end": 1469 }
class ____(OAuth2Provider): id = "slack" name = "Slack" account_class = SlackAccount oauth2_adapter_class = SlackOAuth2Adapter def extract_uid(self, data): team_id = data.get("https://slack.com/team_id") user_id = data.get("https://slack.com/user_id") if not (team_id and use...
SlackProvider
python
apache__airflow
airflow-core/src/airflow/timetables/_delta.py
{ "start": 1097, "end": 1977 }
class ____: """Mixin to provide interface to work with timedelta and relativedelta.""" def __init__(self, delta: datetime.timedelta | relativedelta) -> None: self._delta = delta @property def summary(self) -> str: return str(self._delta) def validate(self) -> None: now = d...
DeltaMixin
python
mlflow__mlflow
mlflow/utils/autologging_utils/config.py
{ "start": 193, "end": 1099 }
class ____: """ A dataclass to hold common autologging configuration options. """ log_input_examples: bool log_model_signatures: bool log_traces: bool extra_tags: dict[str, Any] | None = None log_models: bool = True @classmethod def init(cls, flavor_name: str): config_d...
AutoLoggingConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1283593, "end": 1286660 }
class ____(sgqlc.types.Type, Node): """An Identity Provider configured to provision SAML and SCIM identities for Organizations. Visible to (1) organization owners, (2) organization owners' personal access tokens (classic) with read:org or admin:org scope, (3) GitHub App with an installation token wi...
OrganizationIdentityProvider
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py
{ "start": 18415, "end": 28573 }
class ____: @pytest.mark.parametrize(("sink_config", "update_mask"), update_test_cases, ids=update_test_ids) def test_template_fields(self, sink_config, update_mask): operator = CloudLoggingUpdateSinkOperator( task_id=TASK_ID, sink_name=SINK_NAME, sink_config=sink_con...
TestCloudLoggingUpdateSinksOperator
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_error_embed.py
{ "start": 348, "end": 927 }
class ____(View): def _get_project_key(self): return ProjectKey.objects.filter(project=settings.SENTRY_PROJECT)[0] def get(self, request: HttpRequest) -> HttpResponse: context = { "query_params": urlencode( { "dsn": self._get_project_key().dsn_pub...
DebugErrorPageEmbedView
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/ir.py
{ "start": 91998, "end": 95230 }
class ____(IR): """Produce a new dataframe with distinct rows.""" __slots__ = ("keep", "stable", "subset", "zlice") _non_child = ("schema", "keep", "subset", "zlice", "stable") keep: plc.stream_compaction.DuplicateKeepOption """Which distinct value to keep.""" subset: frozenset[str] | None ...
Distinct
python
numpy__numpy
numpy/f2py/tests/test_regression.py
{ "start": 1370, "end": 1995 }
class ____(util.F2PyTest): # Check that negative bounds work correctly sources = [util.getpath("tests", "src", "negative_bounds", "issue_20853.f90")] @pytest.mark.slow def test_negbound(self): xvec = np.arange(12) xlow = -6 xhigh = 4 # Calculate the upper bound, ...
TestNegativeBounds
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 16113, "end": 19981 }
class ____(fixtures.MappedTest): run_setup_mappers = "once" run_inserts = "once" run_deletes = None @classmethod def define_tables(cls, metadata): Table( "organizations", metadata, Column( "id", Integer, primary_key=True, test_needs_autoin...
M2MFilterTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 142820, "end": 143217 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(SponsorshipOrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc....
SponsorshipOrder
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_detector_count.py
{ "start": 403, "end": 4608 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-detector-count" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.environment = Environment.objects.create( organization_id=self.organization.id, name="production" ) def tes...
OrganizationDetectorCountTest
python
scipy__scipy
scipy/linalg/tests/test_blas.py
{ "start": 3208, "end": 5732 }
class ____: @parametrize_blas(fblas, "axpy", "sdcz") def test_axpy(self, f, dtype): assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5), [7, 9, 18]) if dtype in COMPLEX_DTYPES: assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5), ...
TestFBLAS1Simple
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/secret.py
{ "start": 161, "end": 306 }
class ____(str, Enum): """Secret scope enum for filtering.""" DEPLOYMENT = "deployment" ORGANIZATION = "organization"
DgApiSecretScope
python
kamyu104__LeetCode-Solutions
Python/beautiful-pairs.py
{ "start": 232, "end": 1947 }
class ____(object): def beautifulPair(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ INF = float("inf") def dist(a, b): if a[2] > b[2]: a, b = b, a return [abs(a[0]-b[0])+abs...
Solution
python
PyCQA__pylint
doc/data/messages/a/abstract-method/bad/function_raising_not_implemented_error.py
{ "start": 0, "end": 73 }
class ____: def make_sound(self): raise NotImplementedError
Pet
python
astral-sh__uv
scripts/packages/keyring_test_plugin/keyrings/test_keyring.py
{ "start": 77, "end": 1172 }
class ____(backend.KeyringBackend): priority = 9 def get_password(self, service, username): print(f"Keyring request for {username}@{service}", file=sys.stderr) entries = json.loads(os.environ.get("KEYRING_TEST_CREDENTIALS", "{}")) return entries.get(service, {}).get(username) def s...
KeyringTest
python
kamyu104__LeetCode-Solutions
Python/maximum-calories-burnt-from-jumps.py
{ "start": 601, "end": 1031 }
class ____(object): def maxCaloriesBurnt(self, heights): """ :type heights: List[int] :rtype: int """ heights.sort() d = 0 left, right = 0, len(heights)-1 result = (0-heights[right])**2 while left != right: result += (heights[right]...
Solution2
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_detector.py
{ "start": 21186, "end": 28098 }
class ____(BaseDetectorHandlerTest): def test(self) -> None: handler = self.build_handler() assert handler.evaluate(DataPacket("1", {"dedupe": 1})) == {} detector_occurrence, _ = build_mock_occurrence_and_event( handler, "val1", PriorityLevel.HIGH ) issue_occurr...
TestEvaluate
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 7291, "end": 7352 }
class ____(HTTPClientError): status_code = 404
HTTPNotFound
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 406391, "end": 406506 }
class ____(Node): """ Base class for cython.parallel constructs. """ nogil_check = None
ParallelNode
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py
{ "start": 35770, "end": 36850 }
class ____(Benchmark): r""" Step objective function. This class defines the Step 2 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Step}}(x) = \sum_{i=1}^{n} \left ( \lfloor x_i + 0.5 \rfloor ...
Step2
python
apache__airflow
providers/standard/src/airflow/providers/standard/sensors/date_time.py
{ "start": 1773, "end": 4219 }
class ____(BaseSensorOperator): """ Waits until the specified datetime. A major advantage of this sensor is idempotence for the ``target_time``. It handles some cases for which ``TimeSensor`` and ``TimeDeltaSensor`` are not suited. **Example** 1 : If a task needs to wait for 11am on each `...
DateTimeSensor
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_test.py
{ "start": 1357, "end": 2450 }
class ____(linalg.LinearOperator): """LinearOperator that implements the methods ._shape and _shape_tensor.""" def __init__(self, shape, is_non_singular=None, is_self_adjoint=None, is_positive_definite=None, is_square=None): parameters ...
LinearOperatorShape
python
doocs__leetcode
solution/2200-2299/2249.Count Lattice Points Inside a Circle/Solution.py
{ "start": 0, "end": 476 }
class ____: def countLatticePoints(self, circles: List[List[int]]) -> int: ans = 0 mx = max(x + r for x, _, r in circles) my = max(y + r for _, y, r in circles) for i in range(mx + 1): for j in range(my + 1): for x, y, r in circles: dx,...
Solution
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 126007, "end": 127300 }
class ____(TestCase): """Tests for ``exactly_n()``""" def test_true(self): """Iterable has ``n`` ``True`` elements""" self.assertTrue(mi.exactly_n([True, False, True], 2)) self.assertTrue(mi.exactly_n([1, 1, 1, 0], 3)) self.assertTrue(mi.exactly_n([False, False], 0)) sel...
ExactlyNTests
python
catalyst-team__catalyst
catalyst/contrib/data/sampler.py
{ "start": 9388, "end": 11986 }
class ____(BatchSampler): """ A dynamic batch length data sampler. Should be used with `catalyst.utils.trim_tensors`. Adapted from `Dynamic minibatch trimming to improve BERT training speed`_. Args: sampler: Base sampler. batch_size: Size of minibatch. drop_last: If ``True`...
DynamicLenBatchSampler
python
huggingface__transformers
src/transformers/models/vits/modeling_vits.py
{ "start": 35676, "end": 37303 }
class ____(nn.Module): def __init__(self, config): super().__init__() kernel_size = config.duration_predictor_kernel_size filter_channels = config.duration_predictor_filter_channels self.dropout = nn.Dropout(config.duration_predictor_dropout) self.conv_1 = nn.Conv1d(config.h...
VitsDurationPredictor
python
numpy__numpy
numpy/polynomial/tests/test_legendre.py
{ "start": 16539, "end": 17114 }
class ____: def test_100(self): x, w = leg.leggauss(100) # test orthogonality. Note that the results need to be normalized, # otherwise the huge values that can arise from fast growing # functions like Laguerre can be very confusing. v = leg.legvander(x, 99) vv = np...
TestGauss
python
lepture__authlib
authlib/oauth2/rfc7662/introspection.py
{ "start": 177, "end": 5292 }
class ____(TokenEndpoint): """Implementation of introspection endpoint which is described in `RFC7662`_. .. _RFC7662: https://tools.ietf.org/html/rfc7662 """ #: Endpoint name to be registered ENDPOINT_NAME = "introspection" def authenticate_token(self, request, client): """The pro...
IntrospectionEndpoint
python
django__django
django/db/migrations/operations/models.py
{ "start": 20028, "end": 21996 }
class ____(ModelOptionOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table": self.table, } return (self.__class__.__qu...
AlterModelTable
python
airbytehq__airbyte
airbyte-integrations/connectors/source-surveycto/source_surveycto/source.py
{ "start": 3713, "end": 5024 }
class ____(AbstractSource): def check_connection(self, logger, config) -> Tuple[bool, Any]: form_ids = config["form_id"] try: for form_id in form_ids: schema = Helpers.call_survey_cto(config, form_id) filter_data = Helpers.get_filter_data(schema) ...
SourceSurveycto
python
doocs__leetcode
solution/0400-0499/0493.Reverse Pairs/Solution3.py
{ "start": 95, "end": 1179 }
class ____: def __init__(self, n): self.tr = [Node() for _ in range(4 * n)] self.build(1, 1, n) def build(self, u, l, r): self.tr[u].l = l self.tr[u].r = r if l == r: return mid = (l + r) >> 1 self.build(u << 1, l, mid) self.build(u <<...
SegmentTree
python
encode__django-rest-framework
rest_framework/filters.py
{ "start": 8457, "end": 14912 }
class ____(BaseFilterBackend): # The URL query parameter used for the ordering. ordering_param = api_settings.ORDERING_PARAM ordering_fields = None ordering_title = _('Ordering') ordering_description = _('Which field to use when ordering the results.') template = 'rest_framework/filters/ordering...
OrderingFilter
python
hynek__structlog
src/structlog/exceptions.py
{ "start": 505, "end": 697 }
class ____(Exception): """ A user asked for the current `structlog.dev.ConsoleRenderer` but none is configured. .. versionadded:: 25.5.0 """
NoConsoleRendererConfiguredError
python
huggingface__transformers
src/transformers/models/dinov3_vit/modeling_dinov3_vit.py
{ "start": 19331, "end": 21206 }
class ____(DINOv3ViTPreTrainedModel): def __init__(self, config: DINOv3ViTConfig): super().__init__(config) self.config = config self.embeddings = DINOv3ViTEmbeddings(config) self.rope_embeddings = DINOv3ViTRopePositionEmbedding(config) self.layer = nn.ModuleList([DINOv3ViTLa...
DINOv3ViTModel
python
ansible__ansible
test/units/module_utils/common/test_dict_transformations.py
{ "start": 3948, "end": 4724 }
class ____: def test_recursive_diff(self): a = {'foo': {'bar': [{'baz': {'qux': 'ham_sandwich'}}]}} c = {'foo': {'bar': [{'baz': {'qux': 'ham_sandwich'}}]}} b = {'foo': {'bar': [{'baz': {'qux': 'turkey_sandwich'}}]}} assert recursive_diff(a, b) is not None assert len(recursi...
TestCaseRecursiveDiff
python
ray-project__ray
python/ray/train/_internal/session.py
{ "start": 2663, "end": 3079 }
class ____: """A (checkpoint, metrics) result reported by the user.""" def __init__(self, checkpoint: Optional[Checkpoint], metrics: Dict[str, Any]): self.checkpoint = checkpoint self.metrics = metrics def __repr__(self) -> str: return f"TrainingResult(checkpoint={self.checkpoint},...
_TrainingResult
python
pytorch__pytorch
test/distributed/pipelining/test_backward.py
{ "start": 491, "end": 8459 }
class ____(TestCase): @skipXPUIf(True, "https://github.com/intel/torch-xpu-ops/issues/1682") def test_stage_backward(self, device): # MLP as a stage module mod = MLPModule(d_hid).to(device) x = torch.randn(batch_size, d_hid, device=device) # As in a pipeline stage, the inputs to ...
StageBackwardTests
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/sensor_builder.py
{ "start": 1467, "end": 10446 }
class ____: """A cursor that stores the last effective timestamp and offset.""" finished_at_lower_bound: Optional[float] = None finished_at_upper_bound: Optional[float] = None offset: Optional[int] = None def materializations_from_batch_iter( context: SensorEvaluationContext, finished_at_lowe...
DbtCloudPollingSensorCursor
python
run-llama__llama_index
llama-index-core/llama_index/core/response_synthesizers/simple_summarize.py
{ "start": 563, "end": 3633 }
class ____(BaseSynthesizer): def __init__( self, llm: Optional[LLM] = None, callback_manager: Optional[CallbackManager] = None, prompt_helper: Optional[PromptHelper] = None, text_qa_template: Optional[BasePromptTemplate] = None, streaming: bool = False, ) -> None:...
SimpleSummarize
python
HypothesisWorks__hypothesis
hypothesis-python/tests/conjecture/test_provider.py
{ "start": 18398, "end": 18949 }
class ____(TrivialProvider): scope = "exhausted" def __init__(self, conjecturedata: "ConjectureData", /) -> None: super().__init__(conjecturedata) self._calls = 0 def draw_integer(self, *args, **constraints): self._calls += 1 if self._calls > 20: # This is compl...
ExhaustibleProvider
python
django__django
tests/postgres_tests/models.py
{ "start": 6311, "end": 6379 }
class ____(PostgreSQLModel): one_off = OffByOneField()
OffByOneModel
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 536, "end": 644 }
class ____(Exception): """Generic parent class for exceptions thrown by Hypothesis."""
HypothesisException
python
pennersr__django-allauth
allauth/socialaccount/providers/hubspot/provider.py
{ "start": 403, "end": 1033 }
class ____(OAuth2Provider): id = "hubspot" name = "Hubspot" account_class = HubspotAccount oauth2_adapter_class = HubspotOAuth2Adapter def get_default_scope(self): return ["oauth"] def extract_uid(self, data): return str(data["user_id"]) def extract_common_fields(self, dat...
HubspotProvider
python
networkx__networkx
networkx/algorithms/isomorphism/tests/test_isomorphvf2.py
{ "start": 2143, "end": 4252 }
class ____: # https://web.archive.org/web/20090303210205/http://amalfi.dis.unina.it/graph/db/ @staticmethod def create_graph(filename): """Creates a Graph instance from the filename.""" # The file is assumed to be in the format from the VF2 graph database. # Each file is composed o...
TestVF2GraphDB
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/resource.py
{ "start": 6179, "end": 7489 }
class ____(KubernetesResourceBaseOperator): """Delete a resource in a kubernetes.""" def delete_custom_from_yaml_object(self, body: dict): name = body["metadata"]["name"] group, version, namespace, plural = self.get_crd_fields(body) if self.namespaced: self.custom_object_cli...
KubernetesDeleteResourceOperator
python
pytorch__pytorch
torch/distributed/checkpoint/_extension.py
{ "start": 6336, "end": 7790 }
class ____: def __init__(self) -> None: # Populate default registry contents self.extensions: dict[str, type[Extension]] = { cls.registry_name(): cls for cls in (ZStandard,) } def register(self, cls: type[Extension]) -> None: self.extensions[cls.registry_name()] = cl...
ExtensionRegistry
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_indexing.py
{ "start": 23026, "end": 43284 }
class ____(TestCase): """ These tests use code to mimic the C-Code indexing for selection. NOTE: * This still lacks tests for complex item setting. * If you change behavior of indexing, you might want to modify these tests to try more combinations. * Behavior was written ...
TestMultiIndexingAutomated
python
ray-project__ray
python/ray/util/client/common.py
{ "start": 14580, "end": 18246 }
class ____(ClientStub): """Client-side stub for instantiated actor. A stub created on the Ray Client to represent a remote actor that has been started on the cluster. This class is allowed to be passed around between remote functions. Args: actor_ref: A reference to the running actor give...
ClientActorHandle
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_async_job.py
{ "start": 1758, "end": 6040 }
class ____: """ Minimal AdReportRun stand-in: - first api_get() call: RUNNING - second api_get() call: COMPLETED - get_result(): returns fake rows with the requested id field """ def __init__(self, id_field: str): self._id_field = id_field self._calls = 0 self....
DummyRun
python
scipy__scipy
scipy/interpolate/_rbfinterp.py
{ "start": 1689, "end": 19502 }
class ____: """Radial basis function interpolator in N ≥ 1 dimensions. Parameters ---------- y : (npoints, ndims) array_like 2-D array of data point coordinates. d : (npoints, ...) array_like N-D array of data values at `y`. The length of `d` along the first axis must be equ...
RBFInterpolator
python
airbytehq__airbyte
airbyte-ci/connectors/live-tests/src/live_tests/commons/json_schema_helper.py
{ "start": 2212, "end": 13124 }
class ____: """Helper class to simplify schema validation and read of records according to their schema.""" def __init__(self, schema): self._schema = schema def get_ref(self, path: str) -> Any: """Resolve reference :param path: reference (#/definitions/SomeClass, etc) :re...
JsonSchemaHelper
python
redis__redis-py
tests/test_search.py
{ "start": 113799, "end": 117104 }
class ____(SearchTestsBase): @pytest.mark.redismod @skip_if_redis_enterprise() def test_search_commands_in_pipeline(self, client): p = client.ft().pipeline() p.create_index((TextField("txt"),)) p.hset("doc1", mapping={"txt": "foo bar"}) p.hset("doc2", mapping={"txt": "foo bar...
TestPipeline
python
huggingface__transformers
src/transformers/models/dinat/configuration_dinat.py
{ "start": 919, "end": 7356 }
class ____(BackboneConfigMixin, PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DinatModel`]. It is used to instantiate a Dinat model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yiel...
DinatConfig
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/tree_clearing.py
{ "start": 77, "end": 805 }
class ____(App[None]): CSS = """ Screen { layout: horizontal; } """ @staticmethod def _populate(tree: Tree) -> Tree: for n in range(5): branch = tree.root.add(str(n)) for m in range(5): branch.add_leaf(f"{n}-{m}") return tree ...
TreeClearingSnapshotApp
python
getsentry__sentry
src/sentry/auth/providers/github/provider.py
{ "start": 861, "end": 3620 }
class ____(OAuth2Provider): access_token_url = ACCESS_TOKEN_URL authorize_url = AUTHORIZE_URL name = "GitHub" key = IntegrationProviderSlug.GITHUB.value def get_client_id(self) -> str: assert isinstance(CLIENT_ID, str) return CLIENT_ID def get_client_secret(self) -> str: ...
GitHubOAuth2Provider
python
django__django
tests/migrations/migrations_test_apps/conflicting_app_with_dependencies/migrations/0002_conflicting_second.py
{ "start": 43, "end": 354 }
class ____(migrations.Migration): dependencies = [ ("conflicting_app_with_dependencies", "0001_initial"), ] operations = [ migrations.CreateModel( "Something", [ ("id", models.AutoField(primary_key=True)), ], ) ]
Migration
python
django__django
django/core/serializers/__init__.py
{ "start": 858, "end": 8785 }
class ____: """ Stub serializer to hold exception raised during registration This allows the serializer registration to cache serializers and if there is an error raised in the process of creating a serializer it will be raised and passed along to the caller when the serializer is used. """ ...
BadSerializer
python
apache__airflow
providers/microsoft/winrm/tests/unit/microsoft/winrm/operators/test_winrm.py
{ "start": 1020, "end": 4657 }
class ____: def test_no_winrm_hook_no_ssh_conn_id(self): op = WinRMOperator(task_id="test_task_id", winrm_hook=None, ssh_conn_id=None) exception_msg = "Cannot operate without winrm_hook or ssh_conn_id." with pytest.raises(AirflowException, match=exception_msg): op.execute(None) ...
TestWinRMOperator
python
hyperopt__hyperopt
hyperopt/pyll/base.py
{ "start": 688, "end": 5161 }
class ____: """ An object whose methods generally allocate Apply nodes. _impls is a dictionary containing implementations for those nodes. >>> self.add(a, b) # -- creates a new 'add' Apply node >>> self._impl['add'](a, b) # -- this computes a + b """ def __init__(self): #...
SymbolTable
python
walkccc__LeetCode
solutions/1189. Maximum Number of Balloons/1189.py
{ "start": 0, "end": 215 }
class ____: def maxNumberOfBalloons(self, text: str) -> int: count = collections.Counter(text) return min( count['b'], count['a'], count['l'] // 2, count['o'] // 2, count['n'])
Solution
python
walkccc__LeetCode
solutions/3233. Find the Count of Numbers Which Are Not Special/3233.py
{ "start": 0, "end": 592 }
class ____: def nonSpecialCount(self, l: int, r: int) -> int: maxRoot = math.isqrt(r) isPrime = self._sieveEratosthenes(maxRoot + 1) specialCount = 0 for num in range(2, math.isqrt(r) + 1): if isPrime[num] and l <= num**2 <= r: specialCount += 1 return r - l + 1 - specialCount d...
Solution
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 758, "end": 942 }
class ____(PrefectBaseModel): """Filter by `Flow.id`.""" any_: Optional[List[UUID]] = Field( default=None, description="A list of flow ids to include" )
FlowFilterId
python
getsentry__sentry
tests/sentry/issues/test_utils.py
{ "start": 4310, "end": 8566 }
class ____(OccurrenceTestMixin): def store_search_issue( self, project_id: int, user_id: int, fingerprints: Sequence[str], environment: str | None = None, insert_time: datetime | None = None, tags: Sequence[tuple[str, Any]] | None = None, release: str ...
SearchIssueTestMixin
python
keon__algorithms
algorithms/tree/fenwick_tree/fenwick_tree.py
{ "start": 1021, "end": 2756 }
class ____(object): def __init__(self, freq): self.arr = freq self.n = len(freq) def get_sum(self, bit_tree, i): """ Returns sum of arr[0..index]. This function assumes that the array is preprocessed and partial sums of array elements are stored in bit_tree[]. ...
Fenwick_Tree
python
geekcomputers__Python
Sorting Algorithms/Sorted_Inserted_Linked_List.py
{ "start": 94, "end": 1339 }
class ____: def __init__(self): self.head = None def Sorted_Insert(self, new_node): current = self.head if current is None: new_node.next = new_node self.head = new_node elif current.data >= new_node.data: while current.next != self.head: ...
Circular_Linked_List
python
django__django
tests/queries/test_bulk_update.py
{ "start": 716, "end": 4247 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.notes = [Note.objects.create(note=str(i), misc=str(i)) for i in range(10)] def create_tags(self): self.tags = [Tag.objects.create(name=str(i)) for i in range(10)] def test_simple(self): for note in self.notes: ...
BulkUpdateNoteTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-braintree/source_braintree/schemas/cards.py
{ "start": 2648, "end": 3202 }
class ____(CreditCard): """ https://developer.paypal.com/braintree/docs/reference/response/us-bank-account """ account_holder_name: str account_type: str ach_mandate: str bank_name: str business_name: str last_name: str owner_id: str ownership_type: str plaid_verified_at...
USBankAccount
python
tornadoweb__tornado
maint/test/redbot/red_test.py
{ "start": 1132, "end": 7938 }
class ____(object): def get_handlers(self): return [ ('/hello', HelloHandler), ('/redirect(/.*)', RedirectHandler), ('/post', PostHandler), ('/chunked', ChunkedHandler), ('/cache/(.*)', CacheHandler), ] def get_app_kwargs(self): ...
TestMixin
python
prabhupant__python-ds
data_structures/linked_list/linked_list.py
{ "start": 0, "end": 94 }
class ____(): def __init__(self, val): self.val = val self.next = None
Node
python
pypa__pip
src/pip/_internal/commands/check.py
{ "start": 499, "end": 2244 }
class ____(Command): """Verify installed packages have compatible dependencies.""" ignore_require_venv = True usage = """ %prog [options]""" def run(self, options: Values, args: list[str]) -> int: package_set, parsing_probs = create_package_set_from_installed() missing, conflicti...
CheckCommand
python
pydata__xarray
asv_bench/benchmarks/dataarray_missing.py
{ "start": 396, "end": 978 }
class ____: def setup(self, shape, chunks, limit): if chunks is not None: requires_dask() self.da = make_bench_data(shape, 0.1, chunks) @parameterized( ["shape", "chunks", "limit"], ( [(365, 75, 75)], [None, {"x": 25, "y": 25}], [N...
DataArrayMissingInterpolateNA
python
pypa__warehouse
tests/unit/api/test_billing.py
{ "start": 19888, "end": 21642 }
class ____: def test_billing_webhook(self, pyramid_request, billing_service, monkeypatch): pyramid_request.body = json.dumps({"type": "mock.webhook.payload"}) pyramid_request.headers = {"Stripe-Signature": "mock-stripe-signature"} monkeypatch.setattr( billing_service, ...
TestBillingWebhook
python
getsentry__sentry
tests/snuba/rules/conditions/test_event_frequency.py
{ "start": 4784, "end": 18886 }
class ____(EventFrequencyQueryTestBase): rule_cls = EventFrequencyCondition def test_batch_query(self) -> None: batch_query = self.condition_inst.batch_query_hook( group_ids=[self.event.group_id, self.event2.group_id, self.perf_event.group_id], start=self.start, end=...
EventFrequencyQueryTest
python
joblib__joblib
joblib/test/test_parallel.py
{ "start": 43156, "end": 78095 }
class ____(list): '''MyList is interactively defined by MyList.append is a built-in''' def __hash__(self): # XXX: workaround limitation in cloudpickle return hash(self).__hash__() l = MyList() print(Parallel(backend="loky", n_jobs=2)( delayed(l.append)(i) for i in range(3) )) """.format(jo...
MyList
python
facebookresearch__faiss
faiss/gpu/test/test_gpu_index.py
{ "start": 12496, "end": 16249 }
class ____(unittest.TestCase): def test_indices_ivfflat(self): res = faiss.StandardGpuResources() d = 128 nb = 5000 nlist = 10 rs = np.random.RandomState(567) xb = rs.rand(nb, d).astype('float32') xb_indices_base = np.arange(nb, dtype=np.int64) # For...
TestIVFIndices
python
doocs__leetcode
lcof2/剑指 Offer II 048. 序列化与反序列化二叉树/Solution.py
{ "start": 172, "end": 1219 }
class ____: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return '' res = [] def preorder(root): if root is None: res.append("#,") ...
Codec
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum14.py
{ "start": 212, "end": 288 }
class ____(Enum): # This should generate two errors. x: Literal[A.x]
A
python
doocs__leetcode
solution/0200-0299/0224.Basic Calculator/Solution.py
{ "start": 0, "end": 752 }
class ____: def calculate(self, s: str) -> int: stk = [] ans, sign = 0, 1 i, n = 0, len(s) while i < n: if s[i].isdigit(): x = 0 j = i while j < n and s[j].isdigit(): x = x * 10 + int(s[j]) ...
Solution
python
openai__openai-python
src/openai/types/audio/translation_verbose.py
{ "start": 247, "end": 615 }
class ____(BaseModel): duration: float """The duration of the input audio.""" language: str """The language of the output translation (always `english`).""" text: str """The translated text.""" segments: Optional[List[TranscriptionSegment]] = None """Segments of the translated text an...
TranslationVerbose
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 7817, "end": 8346 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read", "org:write", "org:admin", "alerts:read"], # grant org:read permission, but raise permission denied if the members aren't allowed # to create alerts and the user isn't a team admin "POST": ["org:read", "org:write", ...
OrganizationDetectorPermission
python
python-markdown__markdown
tests/test_apis.py
{ "start": 7440, "end": 11890 }
class ____(unittest.TestCase): """ Test the processor registry. """ def testCreateRegistry(self): r = markdown.util.Registry() r.register(Item('a'), 'a', 20) self.assertEqual(len(r), 1) self.assertIsInstance(r, markdown.util.Registry) def testRegisterWithoutPriority(self): ...
RegistryTests
python
pypa__hatch
tests/backend/metadata/test_core.py
{ "start": 6738, "end": 7034 }
class ____: @pytest.mark.parametrize("name", ["My--App", "My__App", "My..App"]) def test_normalization(self, isolation, name): metadata = ProjectMetadata(str(isolation), None, {"project": {"name": name}}) assert metadata.core.name == metadata.core.name == "my-app"
TestName
python
getsentry__sentry
tests/sentry/db/models/manager/test_base_query_set.py
{ "start": 389, "end": 1315 }
class ____(TestCase): def test(self) -> None: group_2 = self.create_group() ids = [self.group.id, group_2.id] returned = Group.objects.filter(id__in=ids).update_with_returning( returned_fields=["id"], message="hi" ) assert {r[0] for r in returned} == set(ids) ...
TestUpdateWithReturning
python
davidhalter__jedi
jedi/inference/filters.py
{ "start": 9516, "end": 11155 }
class ____(DictFilter): """ A filter for methods that are defined in this module on the corresponding classes like Generator (for __next__, etc). """ class SpecialMethodName(AbstractNameDefinition): api_type = 'function' def __init__(self, parent_context, string_name, callable_, bui...
SpecialMethodFilter
python
facebookresearch__faiss
tests/test_standalone_codec.py
{ "start": 481, "end": 2116 }
class ____(unittest.TestCase): def do_encode_twice(self, factory_key): d = 96 nb = 1000 nq = 0 nt = 2000 xt, x, _ = get_dataset_2(d, nt, nb, nq) assert x.size > 0 codec = faiss.index_factory(d, factory_key) codec.train(xt) codes = codec.s...
TestEncodeDecode
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_animated_formats.py
{ "start": 912, "end": 3301 }
class ____(TestCase): def test_scale(self): no_frames = 20 im = create_animated_image(no_frames=no_frames) frames_count = im.n_frames self.assertEqual(frames_count, no_frames) processed = processors.scale_and_crop(im, (100, 100)) processed_frames_count = processed.n_...
AnimatedFormatProcessorsTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol19.py
{ "start": 206, "end": 271 }
class ____(Protocol): x: Final[int] = field() @dataclass
ProtoA
python
doocs__leetcode
solution/2100-2199/2184.Number of Ways to Build Sturdy Brick Wall/Solution.py
{ "start": 0, "end": 1393 }
class ____: def buildWall(self, height: int, width: int, bricks: List[int]) -> int: def dfs(v): if v > width: return if v == width: s.append(t[:]) return for x in bricks: t.append(x) dfs(v + x...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/plus/constants.py
{ "start": 24, "end": 122 }
class ____(Enum): FULL_DEPLOYMENT = "full" BRANCH_DEPLOYMENT = "branch"
DgPlusDeploymentType
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 2587, "end": 2861 }
class ____(ShowFieldTypeAndContent, PolymorphicModel): field_base = models.CharField(max_length=30) fk = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, related_name="relationbase_set" ) m2m = models.ManyToManyField("self")
RelationBase