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
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 8798, "end": 10665 }
class ____(OutbrainAmplifyStream, HttpSubStream): primary_key = None def __init__(self, authenticator, config, parent: CampaignsByMarketers, **kwargs): super().__init__(parent=parent, **kwargs) self.config = config self._authenticator = authenticator self._session = requests.ses...
PromotedLinksForCampaigns
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict13.py
{ "start": 468, "end": 504 }
class ____(ParentB): x: int
ChildB
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B018.py
{ "start": 28, "end": 390 }
class ____: """abc""" a = 2 "str" # Str (no raise) f"{int}" # JoinedStr (no raise) 1j # Number (complex) 1 # Number (int) 1.0 # Number (float) b"foo" # Binary True # NameConstant (True) False # NameConstant (False) None # NameConstant (None) [1, 2] # list {...
Foo2
python
spyder-ide__spyder
spyder/plugins/remoteclient/tests/test_plugin.py
{ "start": 1571, "end": 2793 }
class ____: def test_wrong_version( self, remote_client: RemoteClient, remote_client_id: str, monkeypatch, qtbot, ): monkeypatch.setattr( "spyder.plugins.remoteclient.api.manager.ssh.SPYDER_REMOTE_MAX_VERSION", "0.0.1", ) mo...
TestVersionCheck
python
pikepdf__pikepdf
src/pikepdf/objects.py
{ "start": 6359, "end": 7111 }
class ____(Object, metaclass=_ObjectMeta): """Construct a PDF Array object.""" object_type = ObjectType.array def __new__(cls, a: Iterable | Rectangle | Matrix | None = None) -> Array: """Construct a PDF Array. Args: a: An iterable of objects. All objects must be either ...
Array
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 6295, "end": 7759 }
class ____(graphene.ObjectType): name = graphene.NonNull(graphene.String) job_name = graphene.NonNull(graphene.String) runConfigOrError = graphene.NonNull(GraphenePartitionRunConfigOrError) tagsOrError = graphene.NonNull(GraphenePartitionTagsOrError) class Meta: name = "PartitionTagsAndConf...
GrapheneJobSelectionPartition
python
getsentry__sentry
tests/sentry/attachments/test_base.py
{ "start": 148, "end": 4169 }
class ____: """ In-memory mock cache that roughly works like Django cache. Extended with internal assertions to ensure correct use of `raw`. """ def __init__(self): self.data = {} #: Used to check for consistent usage of `raw` param self.raw_map = {} def get(self, key, ...
InMemoryCache
python
pypa__setuptools
setuptools/tests/config/test_apply_pyprojecttoml.py
{ "start": 19933, "end": 25710 }
class ____: def pyproject(self, tmp_path, dynamic, extra_content=""): content = f"[project]\nname = 'proj'\ndynamic = {dynamic!r}\n" if "version" not in dynamic: content += "version = '42'\n" file = tmp_path / "pyproject.toml" file.write_text(content + extra_content, enco...
TestPresetField
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 3033, "end": 3725 }
class ____(BaseSimpleType): @classmethod def convert_from_xml(cls, str_value: str) -> bool: if str_value not in ("1", "0", "true", "false"): raise InvalidXmlError( "value must be one of '1', '0', 'true' or 'false', got '%s'" % str_value ) return str_value ...
XsdBoolean
python
huggingface__transformers
src/transformers/models/granitemoe/modeling_granitemoe.py
{ "start": 5904, "end": 7577 }
class ____(nn.Module): def __init__(self, num_experts: int, input_size: int, output_size: int) -> None: """ Initialize the GraniteMoeParallelExperts module. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with many MoE librar...
GraniteMoeParallelExperts
python
joke2k__faker
faker/providers/company/de_AT/__init__.py
{ "start": 45, "end": 556 }
class ____(CompanyProvider): # Source: https://www.wko.at/wirtschaftsrecht/gesellschaftsformen-oesterreich formats = ( "{{last_name}} {{company_suffix}}", "{{last_name}} {{last_name}} {{company_suffix}}", "{{last_name}} & {{last_name}} {{company_suffix}}", ) company_suffixes = ...
Provider
python
mlflow__mlflow
tests/pyfunc/sample_code/code_with_dependencies.py
{ "start": 192, "end": 582 }
class ____(PythonModel): def _call_retriever(self, id): return f"Retriever called with ID: {id}. Output: 42." def predict(self, context, model_input): return f"Input: {model_input}. {self._call_retriever(model_input)}" def predict_stream(self, context, model_input, params=None): yi...
MyModel
python
scikit-learn__scikit-learn
sklearn/neural_network/_multilayer_perceptron.py
{ "start": 1615, "end": 31498 }
class ____(BaseEstimator, ABC): """Base class for MLP classification and regression. Warning: This class should not be used directly. Use derived classes instead. .. versionadded:: 0.18 """ _parameter_constraints: dict = { "hidden_layer_sizes": [ "array-like", ...
BaseMultilayerPerceptron
python
scikit-learn__scikit-learn
sklearn/model_selection/_split.py
{ "start": 92578, "end": 96765 }
class ____(BaseCrossValidator): """Predefined split cross-validator. Provides train/test indices to split data into train/test sets using a predefined scheme specified by the user with the ``test_fold`` parameter. Read more in the :ref:`User Guide <predefined_split>`. .. versionadded:: 0.16 ...
PredefinedSplit
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/components/shell-script-component/with-scaffolder.py
{ "start": 269, "end": 1001 }
class ____(dg.Scaffolder): """Scaffolds a template shell script alongside a filled-out defs.yaml file.""" def scaffold(self, request: ScaffoldRequest) -> None: dg.scaffold_component( request, { "script_path": "script.sh", "asset_specs": [ ...
ShellCommandScaffolder
python
gevent__gevent
src/greentest/3.13/test_queue.py
{ "start": 22601, "end": 22744 }
class ____(BaseQueueTestMixin): def setUp(self): self.type2test = self.queue.PriorityQueue super().setUp()
PriorityQueueTest
python
lepture__mistune
tests/test_commonmark.py
{ "start": 1860, "end": 2194 }
class ____(BaseTestCase): @classmethod def ignore_case(cls, n): return n in IGNORE_CASES or n in DIFF_CASES def assert_case(self, n, text, html): result = mistune.html(text) self.assertEqual(normalize_html(result), normalize_html(html)) TestCommonMark.load_fixtures("commonmark.jso...
TestCommonMark
python
redis__redis-py
redis/cluster.py
{ "start": 5405, "end": 13160 }
class ____: RedisClusterRequestTTL = 16 PRIMARIES = "primaries" REPLICAS = "replicas" ALL_NODES = "all" RANDOM = "random" DEFAULT_NODE = "default-node" NODE_FLAGS = {PRIMARIES, REPLICAS, ALL_NODES, RANDOM, DEFAULT_NODE} COMMAND_FLAGS = dict_merge( list_keys_to_dict( ...
AbstractRedisCluster
python
numpy__numpy
tools/swig/test/testTensor.py
{ "start": 14375, "end": 14687 }
class ____(TensorTestCase): def __init__(self, methodName="runTest"): TensorTestCase.__init__(self, methodName) self.typeStr = "ulongLong" self.typeCode = "Q" self.result = int(self.result) ######################################################################
ulongLongTestCase
python
numpy__numpy
numpy/distutils/tests/test_ccompiler_opt_conf.py
{ "start": 977, "end": 5862 }
class ____(FakeCCompilerOpt): """A hook to check the sanity of configured features - before it called by the abstract class '_Feature' """ def conf_features_partial(self): conf_all = self.conf_features for feature_name, feature in conf_all.items(): self.test_feature( ...
_TestConfFeatures
python
rapidsai__cudf
python/cudf/cudf/core/udf/strings_typing.py
{ "start": 801, "end": 1032 }
class ____(types.Type): np_dtype: np.dtype[np.object_] = np.dtype("object") def __init__(self): super().__init__(name="managed_udf_string") @property def return_as(self): return self
ManagedUDFString
python
kamyu104__LeetCode-Solutions
Python/smallest-sufficient-team.py
{ "start": 111, "end": 925 }
class ____(object): def smallestSufficientTeam(self, req_skills, people): """ :type req_skills: List[str] :type people: List[List[str]] :rtype: List[int] """ lookup = {v: i for i, v in enumerate(req_skills)} dp = {0: []} for i, p in enumerate(people): ...
Solution
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 39755, "end": 42007 }
class ____: def test_properties(self): value = binascii.unhexlify(b"092384932230498bc980aa8098456f6ff7ff3ac9") ski = x509.SubjectKeyIdentifier(value) assert ski.digest == value assert ski.key_identifier == value def test_repr(self): ski = x509.SubjectKeyIdentifier( ...
TestSubjectKeyIdentifier
python
lepture__authlib
authlib/integrations/httpx_client/oauth1_client.py
{ "start": 979, "end": 3264 }
class ____(_OAuth1Client, httpx.AsyncClient): auth_class = OAuth1Auth def __init__( self, client_id, client_secret=None, token=None, token_secret=None, redirect_uri=None, rsa_key=None, verifier=None, signature_method=SIGNATURE_HMAC_SHA1, ...
AsyncOAuth1Client
python
getsentry__sentry
tests/sentry/notifications/notifications/test_assigned.py
{ "start": 908, "end": 21557 }
class ____(APITestCase): def validate_email(self, outbox, index, email, txt_msg, html_msg): msg = outbox[index] assert msg.to == [email] assert isinstance(msg, EmailMultiAlternatives) # check the txt version assert txt_msg in msg.body # check the html version ...
AssignedNotificationAPITest
python
PyCQA__pyflakes
pyflakes/messages.py
{ "start": 1131, "end": 1370 }
class ____(Message): message = "'from %s import *' only allowed at module level" def __init__(self, filename, loc, modname): Message.__init__(self, filename, loc) self.message_args = (modname,)
ImportStarNotPermitted
python
ethereum__web3.py
tests/core/method-class/test_result_formatters.py
{ "start": 496, "end": 907 }
class ____(Module): method = Method("method_for_test", result_formatters=result_formatter) @pytest.fixture def dummy_w3(): w3 = Web3( DummyProvider(), modules={"module": ModuleForTest}, ) return w3 def test_result_formatter(dummy_w3, request_mocker): with request_mocker(dummy_w3,...
ModuleForTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarTuple24.py
{ "start": 241, "end": 696 }
class ____(Generic[*Ts]): def __init__(self) -> None: self.x: list[Union[*Ts]] = [] reveal_type(self.x, expected_text="list[Union[*Ts@ClassA]]") def method(self) -> Union[*Ts]: ... a1 = ClassA[int, bool, str]() reveal_type(a1.method(), expected_text="int | bool | str") reveal_type(a1.x, exp...
ClassA
python
kamyu104__LeetCode-Solutions
Python/longest-increasing-subsequence-ii.py
{ "start": 71, "end": 1383 }
class ____(object): def __init__(self, N, build_fn=lambda _: 0, query_fn=lambda x, y: y if x is None else x if y is None else max(x, y), update_fn=lambda x: x): self.tree = [None]*(2*2**((N-1).bit_length())) self.base = len(self.tree)//2 sel...
SegmentTree
python
jd__tenacity
tenacity/retry.py
{ "start": 7507, "end": 8440 }
class ____(retry_if_exception_message): """Retries until an exception message equals or matches.""" def __init__( self, message: typing.Optional[str] = None, match: typing.Union[None, str, typing.Pattern[str]] = None, ) -> None: super().__init__(message, match) # inv...
retry_if_not_exception_message
python
huggingface__transformers
src/transformers/models/wav2vec2/modeling_wav2vec2.py
{ "start": 87632, "end": 93906 }
class ____(Wav2Vec2PreTrainedModel): def __init__(self, config): super().__init__(config) self.wav2vec2 = Wav2Vec2Model(config) num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings if config.use_weighted_layer_sum: self.layer_weights = nn.Pa...
Wav2Vec2ForXVector
python
huggingface__transformers
tests/models/rag/test_modeling_rag.py
{ "start": 24434, "end": 25685 }
class ____(RagTestMixin, unittest.TestCase): @cached_property def config_and_inputs(self): question_encoder_tester = DPRModelTester(self) dpr_config_and_inputs = question_encoder_tester.prepare_config_and_inputs() generator_tester = T5ModelTester(self, vocab_size=1101) t5_config_...
RagDPRT5Test
python
encode__django-rest-framework
tests/test_views.py
{ "start": 472, "end": 1109 }
class ____(APIView): def get(self, request, *args, **kwargs): return Response({'method': 'GET'}) def post(self, request, *args, **kwargs): return Response({'method': 'POST', 'data': request.data}) @api_view(['GET', 'POST', 'PUT', 'PATCH']) def basic_view(request): if request.method == 'GE...
BasicView
python
qdrant__qdrant-client
qdrant_client/embed/model_embedder.py
{ "start": 871, "end": 1579 }
class ____(Worker): def __init__(self, batch_size: int, **kwargs: Any): self.model_embedder = ModelEmbedder(**kwargs) self.batch_size = batch_size @classmethod def start(cls, batch_size: int, **kwargs: Any) -> "ModelEmbedderWorker": return cls(threads=1, batch_size=batch_size, **kwa...
ModelEmbedderWorker
python
pandas-dev__pandas
doc/source/conf.py
{ "start": 16804, "end": 17251 }
class ____(MethodDocumenter): """ Specialized Documenter subclass for accessors. """ objtype = "accessor" directivetype = "method" # lower than MethodDocumenter so this is not chosen for normal methods priority = 0.6 def format_signature(self) -> str: # this method gives an er...
AccessorDocumenter
python
tensorflow__tensorflow
tensorflow/python/training/monitored_session.py
{ "start": 47937, "end": 52440 }
class ____(_WrappedSession): """A wrapped session that recreates a session upon certain kinds of errors. The constructor is passed a SessionCreator object, not a session. Calls to `run()` are delegated to the wrapped session. If a call raises the exception `tf.errors.AbortedError` or `tf.errors.UnavailableEr...
_RecoverableSession
python
django__django
tests/generic_relations/models.py
{ "start": 2706, "end": 2832 }
class ____(models.Manager): def get_queryset(self): return super().get_queryset().filter(has_tail=True)
GeckoManager
python
PyCQA__pylint
tests/functional/i/init_not_called.py
{ "start": 430, "end": 566 }
class ____(AAAA, BBBB, CCCC): """derived class""" def __init__(self): # [super-init-not-called] AAAA.__init__(self)
ZZZZ
python
apache__airflow
helm-tests/tests/helm_tests/airflow_aux/test_basic_helm_chart.py
{ "start": 3786, "end": 36460 }
class ____: """Tests basic helm chart tests.""" def _get_values_with_version(self, values, version): if version != "default": values["airflowVersion"] = version return values def _get_object_count(self, version): if self._is_airflow_3_or_above(version): retu...
TestBaseChartTest
python
getsentry__sentry
tests/sentry/codecov/endpoints/test_test_results.py
{ "start": 3603, "end": 13559 }
class ____(APITestCase): endpoint_name = "sentry-api-0-test-results" def setUp(self) -> None: super().setUp() self.organization = self.create_organization(owner=self.user) self.integration = self.create_integration( organization=self.organization, external_id="12...
TestResultsEndpointTest
python
TheAlgorithms__Python
graphs/minimum_spanning_tree_prims2.py
{ "start": 6255, "end": 8950 }
class ____[T]: """ Graph Undirected Weighted Class Functions: add_node: function to add a node in the graph add_edge: function to add an edge between 2 nodes in the graph """ def __init__(self) -> None: self.connections: dict[T, dict[T, int]] = {} self.nodes: int = 0 d...
GraphUndirectedWeighted
python
pytorch__pytorch
torch/nn/modules/batchnorm.py
{ "start": 512, "end": 4759 }
class ____(Module): """Common base of _InstanceNorm and _BatchNorm.""" _version = 2 __constants__ = ["track_running_stats", "momentum", "eps", "num_features", "affine"] num_features: int eps: float momentum: Optional[float] affine: bool track_running_stats: bool # WARNING: weight an...
_NormBase
python
Textualize__textual
docs/examples/widgets/label.py
{ "start": 79, "end": 241 }
class ____(App): def compose(self) -> ComposeResult: yield Label("Hello, world!") if __name__ == "__main__": app = LabelApp() app.run()
LabelApp
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/pipeline.py
{ "start": 1710, "end": 4183 }
class ____(Step): """ Pipeline step to check if the connector is a candidate for migration to manifest-only. """ context: ConnectorContext title: str = "Validate Manifest Migration Candidate" airbyte_repo: git.Repo = git.Repo(search_parent_directories=True) async def _run(self) -> StepResu...
CheckIsManifestMigrationCandidate
python
jpadilla__pyjwt
jwt/types.py
{ "start": 348, "end": 2524 }
class ____(TypedDict, total=False): """Options for :py:func:`jwt.decode()` and :py:func:`jwt.api_jwt.decode_complete()` (TypedDict). .. warning:: Some claims, such as ``exp``, ``iat``, ``jti``, ``nbf``, and ``sub``, will only be verified if present. Please refer to the documentation below ...
Options
python
walkccc__LeetCode
solutions/2592. Maximize Greatness of an Array/2592.py
{ "start": 0, "end": 181 }
class ____: def maximizeGreatness(self, nums: list[int]) -> int: ans = 0 nums.sort() for num in nums: if num > nums[ans]: ans += 1 return ans
Solution
python
django__django
tests/generic_views/views.py
{ "start": 919, "end": 1339 }
class ____(generic.DetailView): template_name = "generic_views/author_detail.html" queryset = Author.objects.all() def get(self, request, *args, **kwargs): # Ensures get_context_object_name() doesn't reference self.object. author = self.get_object() context = {"custom_" + self.get_c...
AuthorCustomDetail
python
paramiko__paramiko
demos/demo_server.py
{ "start": 1201, "end": 5860 }
class ____(paramiko.ServerInterface): # 'data' is the output of base64.b64encode(key) # (using the "user_rsa_key" files) data = ( b"AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp" b"fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC" b"KDqIexkgHAfID/6mqvmn...
Server
python
great-expectations__great_expectations
tests/expectations/test_conditions.py
{ "start": 2844, "end": 5301 }
class ____: def test_column_hash_equal(self): assert hash(Column("age")) == hash(Column("age")) def test_column_hash_not_equal(self): assert hash(Column("age")) != hash(Column("city")) def test_less_than_operator(self): col = Column("age") result = col < 18 assert ...
TestColumn
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 948925, "end": 949323 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("RequestedReviewer", graph...
RequestedReviewerEdge
python
walkccc__LeetCode
solutions/1198. Find Smallest Common Element in All Rows/1198.py
{ "start": 0, "end": 254 }
class ____: def smallestCommonElement(self, mat: list[list[int]]) -> int: MAX = 10000 count = [0] * (MAX + 1) for row in mat: for a in row: count[a] += 1 if count[a] == len(mat): return a return -1
Solution
python
pytorch__pytorch
test/distributed/tensor/test_dtensor_testbase.py
{ "start": 353, "end": 1446 }
class ____(DTensorTestBase): """ This class tests if the basic functionalities of DTensorTestBase are working as expected on CPU, regardless of the presence of CUDA devices. """ @property def backend(self): return "gloo" @property def device_type(self) -> str: return "c...
DTensorTestBaseUtilCPUTest
python
celery__celery
t/unit/backends/test_asynchronous.py
{ "start": 550, "end": 4741 }
class ____: """ Base test class for the Default / Gevent / Eventlet drainers. """ interval = 0.1 # Check every tenth of a second MAX_TIMEOUT = 10 # Specify a max timeout so it doesn't run forever def get_drainer(self, environment): with patch('celery.backends.asynchronous.detect_envi...
DrainerTests
python
huggingface__transformers
src/transformers/models/ijepa/modeling_ijepa.py
{ "start": 13295, "end": 14554 }
class ____(PreTrainedModel): config: IJepaConfig base_model_prefix = "ijepa" main_input_name = "pixel_values" input_modalities = ("image",) supports_gradient_checkpointing = True _no_split_modules = ["IJepaEmbeddings", "IJepaLayer"] _supports_sdpa = True _supports_flash_attn = True _...
IJepaPreTrainedModel
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 54963, "end": 55288 }
class ____(base_classes.Note): def __init__(self, xl): self.xl = xl @property def api(self): return self.xl @property def text(self): return self.xl.Text() @text.setter def text(self, value): self.xl.Text(value) def delete(self): self.xl.Delete...
Note
python
getsentry__sentry
src/sentry/releases/endpoints/release_deploys.py
{ "start": 1927, "end": 5119 }
class ____(serializers.Serializer): name = serializers.CharField( max_length=64, required=False, allow_blank=True, allow_null=True, help_text="The optional name of the deploy", ) environment = serializers.CharField( max_length=64, help_text="The environment yo...
DeploySerializer
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_prediction_writer.py
{ "start": 935, "end": 5393 }
class ____(BasePredictionWriter): def write_on_batch_end(self, *_, **__): pass def write_on_epoch_end(self, *_, **__): pass def test_prediction_writer_invalid_write_interval(): """Test that configuring an unknown interval name raises an error.""" with pytest.raises(MisconfigurationExc...
DummyPredictionWriter
python
tensorflow__tensorflow
tensorflow/python/data/ops/dataset_ops.py
{ "start": 185740, "end": 186050 }
class ____(DatasetV2): """Abstract class representing a dataset with one input.""" def __init__(self, input_dataset: DatasetV2, variant_tensor): self._input_dataset = input_dataset super(UnaryDataset, self).__init__(variant_tensor) def _inputs(self): return [self._input_dataset]
UnaryDataset
python
tensorflow__tensorflow
tensorflow/python/framework/ops.py
{ "start": 5183, "end": 7032 }
class ____(object): """Store user-specified device and provide computation of merged device.""" def __init__(self, device_name_or_function) -> None: self._device_name_or_function = device_name_or_function self.display_name = str(self._device_name_or_function) self.function = device_name_or_function ...
_UserDeviceSpec
python
automl__auto-sklearn
autosklearn/pipeline/components/regression/__init__.py
{ "start": 802, "end": 5353 }
class ____(AutoSklearnChoice): @classmethod def get_components(cls): components = OrderedDict() components.update(_regressors) components.update(additional_components.components) return components @classmethod def get_available_components( cls, dataset_properties...
RegressorChoice
python
encode__django-rest-framework
tests/test_relations_hyperlink.py
{ "start": 1383, "end": 1565 }
class ____(serializers.HyperlinkedModelSerializer): class Meta: model = ManyToManySource fields = ('url', 'name', 'targets') # ForeignKey
ManyToManySourceSerializer
python
pytorch__pytorch
benchmarks/dynamo/huggingface.py
{ "start": 10835, "end": 22042 }
class ____(BenchmarkRunner): def __init__(self): super().__init__() self.suite_name = "huggingface" @property def _config(self): return load_yaml_file("huggingface.yaml") @property def _skip(self): return self._config["skip"] @property def _accuracy(self): ...
HuggingfaceRunner
python
encode__django-rest-framework
rest_framework/serializers.py
{ "start": 3396, "end": 10611 }
class ____(Field): """ The BaseSerializer class provides a minimal class which may be used for writing custom serializer implementations. Note that we strongly restrict the ordering of operations/properties that may be used on the serializer in order to enforce correct usage. In particular, if...
BaseSerializer
python
html5lib__html5lib-python
html5lib/tests/support.py
{ "start": 2499, "end": 4712 }
class ____(object): def __init__(self, filename, newTestHeading="data", encoding="utf8"): if encoding is None: self.f = open(filename, mode="rb") else: self.f = codecs.open(filename, encoding=encoding) self.encoding = encoding self.newTestHeading = newTestHead...
TestData
python
getlogbook__logbook
src/logbook/ticketing.py
{ "start": 10725, "end": 15881 }
class ____(BackendBase): """Implements a backend that writes into a MongoDB database.""" class _FixedTicketClass(Ticket): @property def ticket_id(self): return self._id class _FixedOccurrenceClass(Occurrence): def __init__(self, db, row): self.update_from_di...
MongoDBBackend
python
pypa__hatch
src/hatch/project/constants.py
{ "start": 144, "end": 524 }
class ____: REQUESTED_TARGETS = "HATCH_BUILD_REQUESTED_TARGETS" LOCATION = "HATCH_BUILD_LOCATION" HOOKS_ONLY = "HATCH_BUILD_HOOKS_ONLY" NO_HOOKS = "HATCH_BUILD_NO_HOOKS" HOOKS_ENABLE = "HATCH_BUILD_HOOKS_ENABLE" HOOK_ENABLE_PREFIX = "HATCH_BUILD_HOOK_ENABLE_" CLEAN = "HATCH_BUILD_CLEAN" ...
BuildEnvVars
python
airbytehq__airbyte
airbyte-integrations/connectors/source-gcs/source_gcs/source.py
{ "start": 1009, "end": 4350 }
class ____(FileBasedSource): @classmethod def read_config(cls, config_path: str) -> Mapping[str, Any]: """ Override the default read_config to transform the legacy config format into the new one before validating it against the new spec. """ config = FileBasedSource.read_...
SourceGCS
python
huggingface__transformers
tests/generation/test_utils.py
{ "start": 3059, "end": 122124 }
class ____: input_name = "input_ids" model_tester = None max_new_tokens = 3 def prepare_config_and_inputs_for_generate(self, batch_size=2): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # We don't want a few model inputs in our model input dictionary fo...
GenerationTesterMixin
python
django__django
tests/admin_inlines/models.py
{ "start": 7424, "end": 7727 }
class ____(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE) def get_absolute_url(self): return "/child_model2/" # Models for #19425
ChildModel2
python
kamyu104__LeetCode-Solutions
Python/number-of-subarrays-with-lcm-equal-to-k.py
{ "start": 770, "end": 1348 }
class ____(object): def subarrayLCM(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def gcd(a, b): while b: a, b = b, a%b return a def lcm(a, b): return a//gcd(a, b)*b result ...
Solution2
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0005_sync_project_model.py
{ "start": 100, "end": 1898 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0004_add_project_container_image"), ] operations = [ migrations.AlterField( model_name="project", name="documentation_type", field=models.CharField( ...
Migration
python
spyder-ide__spyder
external-deps/python-lsp-server/test/fixtures.py
{ "start": 1138, "end": 1217 }
class ____(FakeEditorMethodsMixin, PythonLSPServer): pass
FakePythonLSPServer
python
vyperlang__vyper
vyper/semantics/environment.py
{ "start": 414, "end": 771 }
class ____(_EnvType): _id = "block" _type_members = { "coinbase": AddressT(), "difficulty": UINT256_T, "prevrandao": BYTES32_T, "number": UINT256_T, "gaslimit": UINT256_T, "basefee": UINT256_T, "blobbasefee": UINT256_T, "prevhash": BYTES32_T, ...
_Block
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 935238, "end": 935810 }
class ____( sgqlc.types.Type, Node, AuditEntry, RepositoryAuditEntryData, OrganizationAuditEntryData, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("fork_parent_name", "fork_source_name", "visibility") fork_parent_name = sgqlc.types...
RepoCreateAuditEntry
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
{ "start": 3017, "end": 4235 }
class ____: """Test IP address detection.""" def test_detect_valid_ipv4(self): content = "Server IP: 192.168.1.1" matches = detect_ip(content) assert len(matches) == 1 assert matches[0]["type"] == "ip" assert matches[0]["value"] == "192.168.1.1" def test_detect_mul...
TestIPDetection
python
bokeh__bokeh
tests/unit/bokeh/client/test_util__client.py
{ "start": 2002, "end": 2956 }
class ____: def test_with_http(self) -> None: assert bcu.websocket_url_for_server_url("http://foo.com") == "ws://foo.com/ws" assert bcu.websocket_url_for_server_url("http://foo.com/") == "ws://foo.com/ws" def test_with_https(self) -> None: assert bcu.websocket_url_for_server_url("https:...
Test_websocket_url_for_server_url
python
jschneier__django-storages
tests/test_utils.py
{ "start": 276, "end": 436 }
class ____(TestCase): def test_get_setting(self): value = utils.setting("SECRET_KEY") self.assertEqual(settings.SECRET_KEY, value)
SettingTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_styles02.py
{ "start": 380, "end": 4449 }
class ____(unittest.TestCase): """ Test assembling a complete Styles file. """ def test_assemble_xml_file(self): """Test for simple font styles.""" self.maxDiff = None fh = StringIO() style = Styles() style._set_filehandle(fh) workbook = Workbook() ...
TestAssembleStyles
python
spack__spack
lib/spack/spack/util/crypto.py
{ "start": 893, "end": 3541 }
class ____: def __init__(self, hash_alg, alert_fn, disable_security_check): self.hash_alg = hash_alg self.alert_fn = alert_fn self.disable_security_check = disable_security_check def __call__(self, disable_alert=False): if not disable_alert: self.alert_fn( ...
DeprecatedHash
python
getsentry__sentry
tests/sentry/uptime/autodetect/test_ranking.py
{ "start": 8386, "end": 9147 }
class ____(UptimeTestCase): def test(self) -> None: assert should_autodetect_for_organization(self.organization) self.organization.update_option("sentry:uptime_autodetection", False) assert not should_autodetect_for_organization(self.organization) self.organization.update_option("sen...
ShouldDetectForOrgTest
python
bokeh__bokeh
src/bokeh/core/property/dataspec.py
{ "start": 17849, "end": 18652 }
class ____(UnitsSpec): """ A |DataSpec| property that accepts numeric fixed values or strings that refer to columns in a :class:`~bokeh.models.sources.ColumnDataSource`, and also provides an associated units property to store units information. Acceptable values for units are ``"screen"`` and ``"data"``...
DistanceSpec
python
walkccc__LeetCode
solutions/2497. Maximum Star Sum of a Graph/2497.py
{ "start": 0, "end": 560 }
class ____: def maxStarSum(self, vals: list[int], edges: list[list[int]], k: int) -> int: n = len(vals) ans = -math.inf graph = [[] for _ in range(n)] for u, v in edges: graph[u].append((v, vals[v])) graph[v].append((u, vals[u])) for i, starSum in enumerate(vals): maxHeap = [] ...
Solution
python
getsentry__sentry
src/sentry/integrations/cursor/integration.py
{ "start": 1991, "end": 2297 }
class ____(forms.Form): api_key = forms.CharField( label=_("Cursor API Key"), help_text=_("Enter your Cursor API key to call Cursor Agents with."), widget=forms.PasswordInput(attrs={"placeholder": _("***********************")}), max_length=255, )
CursorAgentConfigForm
python
huggingface__transformers
src/transformers/models/dac/feature_extraction_dac.py
{ "start": 961, "end": 7992 }
class ____(SequenceFeatureExtractor): r""" Constructs an Dac feature extractor. This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains most of the main methods. Users should refer to this superclass for more information regarding those method...
DacFeatureExtractor
python
PyCQA__pylint
tests/functional/c/consider/consider_using_enumerate.py
{ "start": 1807, "end": 2131 }
class ____: def __iter__(self): # Should not suggest enumerate on self for i in range(len(self)): yield self[i] def does_not_crash_on_range_without_args(): for elem in range(): print(elem) # False negative described in #3657 # https://github.com/pylint-dev/pylint/issues/3...
Good
python
pytorch__pytorch
benchmarks/gpt_fast/quantize.py
{ "start": 2008, "end": 2775 }
class ____: def __init__(self, mod): self.mod = mod @torch.no_grad() def create_quantized_state_dict(self): cur_state_dict = self.mod.state_dict() for fqn, mod in self.mod.named_modules(): if isinstance(mod, torch.nn.Linear): int8_weight, scales, _ = dyna...
WeightOnlyInt8QuantHandler
python
pytorch__pytorch
torch/_inductor/cpp_builder.py
{ "start": 34077, "end": 53322 }
class ____(BuildOptionsBase): """ This class is inherited from BuildOptionsBase, and as cxx build options. This option need contains basic cxx build option, which contains: 1. OS related args. 2. Toolchains related args. 3. Cxx standard related args. Note: 1. This Options is good for ass...
CppOptions
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_ltc_address.py
{ "start": 890, "end": 1891 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_ltc_address" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _panda...
ColumnValuesToBeValidLtcAddress
python
sympy__sympy
sympy/physics/secondquant.py
{ "start": 19298, "end": 23188 }
class ____(FermionicOperator, Creator): """ Fermionic creation operator. """ op_symbol = 'f+' def _dagger_(self): return AnnihilateFermion(self.state) def apply_operator(self, state): """ Apply state to self if self is not symbolic and state is a FockStateKet, else ...
CreateFermion
python
pytorch__pytorch
torch/_inductor/loop_body.py
{ "start": 2115, "end": 2293 }
class ____(NamedTuple): index_name: str # LoopBody.indexing_exprs[index_name] buffer_name: Optional[str] mode: Optional[str] # V.ops.store(..., mode=mode)
MemoryEntry
python
huggingface__transformers
src/transformers/models/perception_lm/modular_perception_lm.py
{ "start": 3129, "end": 4259 }
class ____(LlavaModelOutputWithPast): r""" past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). ...
PerceptionLMModelOutputWithPast
python
python-openxml__python-docx
src/docx/oxml/numbering.py
{ "start": 2659, "end": 3965 }
class ____(BaseOxmlElement): """``<w:numbering>`` element, the root element of a numbering part, i.e. numbering.xml.""" num = ZeroOrMore("w:num", successors=("w:numIdMacAtCleanup",)) def add_num(self, abstractNum_id): """Return a newly added CT_Num (<w:num>) element referencing the abstract ...
CT_Numbering
python
huggingface__transformers
src/transformers/models/gemma/modular_gemma.py
{ "start": 10592, "end": 13491 }
class ____(LlamaModel): def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor]...
GemmaModel
python
openai__openai-python
src/openai/types/chat/chat_completion_audio.py
{ "start": 157, "end": 655 }
class ____(BaseModel): id: str """Unique identifier for this audio response.""" data: str """ Base64 encoded audio bytes generated by the model, in the format specified in the request. """ expires_at: int """ The Unix timestamp (in seconds) for when this audio response will no ...
ChatCompletionAudio
python
kamyu104__LeetCode-Solutions
Python/minimum-fuel-cost-to-report-to-the-capital.py
{ "start": 45, "end": 1310 }
class ____(object): def minimumFuelCost(self, roads, seats): """ :type roads: List[List[int]] :type seats: int :rtype: int """ def ceil_divide(a, b): return (a+b-1)//b def iter_dfs(): result = 0 stk = [(1, (0, -1, 0, [1...
Solution
python
keon__algorithms
tests/test_array.py
{ "start": 13144, "end": 13495 }
class ____(unittest.TestCase): def test_limit(self): self.assertListEqual(limit([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]) self.assertListEqual(limit([1, 2, 3, 4, 5], 2, 4), [2, 3, 4]) self.assertListEqual(limit([1, 2, 3, 4, 5], 2), [2, 3, 4, 5]) self.assertListEqual(limit([1, 2, 3, 4, 5], ...
TestLimit
python
walkccc__LeetCode
solutions/3353. Minimum Total Operations/3353.py
{ "start": 0, "end": 127 }
class ____: def minOperations(self, nums: list[int]) -> int: return sum(a != b for a, b in itertools.pairwise(nums))
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 27581, "end": 28311 }
class ____(AssetSelection): selected_asset_keys: Sequence[AssetKey] def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: return set() def resolve_checks_inner( # pyright: ignore[reportIncompatibleMethodOverride] self, asset_grap...
AssetChecksForAssetKeysSelection
python
ray-project__ray
python/ray/dag/dag_operation_future.py
{ "start": 641, "end": 1174 }
class ____(DAGOperationFuture): """ A future that is already resolved. Calling `wait()` on this will immediately return the result without blocking. """ def __init__(self, result): """ Initialize a resolved future. Args: result: The result of the future. ...
ResolvedFuture
python
scipy__scipy
benchmarks/benchmarks/stats.py
{ "start": 1177, "end": 1530 }
class ____(Benchmark): def setup(self): rng = np.random.default_rng(12345678) self.a = rng.random((6,3)) * 10 self.b = rng.random((6,3)) * 10 self.c = rng.random((6,3)) * 10 def time_f_oneway(self): stats.f_oneway(self.a, self.b, self.c) stats.f_oneway(self.a, se...
ANOVAFunction