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
scikit-image__scikit-image
tests/skimage/graph/test_flexible.py
{ "start": 164, "end": 1560 }
class ____(mcp.MCP_Flexible): """Simple MCP subclass that allows the front to travel a certain distance from the seed point, and uses a constant cost factor that is independent of the cost array. """ def _reset(self): mcp.MCP_Flexible._reset(self) self._distance = np.zeros((8, 8), d...
FlexibleMCP
python
falconry__falcon
tests/test_recipes.py
{ "start": 2106, "end": 3297 }
class ____: class QuoteResource: def on_get(self, req, resp): resp.media = { 'author': 'Grace Hopper', 'quote': ( "I've always been more interested in the future than in the past." ), } class NegotiationMiddlewa...
TestPrettyJSON
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_qt.py
{ "start": 45019, "end": 45430 }
class ____(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2QT.draw_rubberband( self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2QT.remove_rubberband( self._make_cla...
RubberbandQt
python
kamyu104__LeetCode-Solutions
Python/number-of-pairs-satisfying-inequality.py
{ "start": 1774, "end": 2930 }
class ____(object): def numberOfPairs(self, nums1, nums2, diff): """ :type nums1: List[int] :type nums2: List[int] :type diff: int :rtype: int """ def merge_sort(nums, left, right, result): if left == right: return mid =...
Solution3
python
bokeh__bokeh
src/bokeh/embed/bundle.py
{ "start": 7454, "end": 7781 }
class ____: """ Opaque type for representing URLs. """ url: str def __truediv__(self, path: str) -> URL: url = self.url if self.url.endswith("/") else f"{self.url}/" return URL(urljoin(url, path.replace(os.sep, "/"))) def __str__(self) -> str: return self.url @dataclass(froze...
URL
python
gevent__gevent
src/greentest/3.13/test_httplib.py
{ "start": 64767, "end": 67820 }
class ____(TestCase, ExtraAssertions): def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # Allowlist documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for...
OfflineTest
python
numba__numba
numba/core/types/abstract.py
{ "start": 965, "end": 2694 }
class ____(ABCMeta): """ A metaclass that will intern instances after they are created. This is done by first creating a new instance (including calling __init__, which sets up the required attributes for equality and hashing), then looking it up in the _typecache registry. """ def __init__...
_TypeMetaclass
python
realpython__materials
python-313/typing/generic_queue.py
{ "start": 32, "end": 776 }
class ____[T]: def __init__(self) -> None: self.elements: deque[T] = deque() def push(self, element: T) -> None: self.elements.append(element) def pop(self) -> T: return self.elements.popleft() # %% Python 3.13 # # class Queue[T=str]: # def __init__(self) -> None: # s...
Queue
python
walkccc__LeetCode
solutions/792. Number of Matching Subsequences/792-2.py
{ "start": 0, "end": 729 }
class ____: def numMatchingSubseq(self, s: str, words: list[str]) -> int: ans = 0 # [(i, j)] := words[i] and the letter words[i][j] is waiting for bucket = [[] for _ in range(26)] # For each word, it's waiting for word[0]. for i, word in enumerate(words): bucket[ord(word[0]) - ord('a')].app...
Solution
python
ansible__ansible
lib/ansible/module_utils/facts/system/dns.py
{ "start": 841, "end": 2664 }
class ____(BaseFactCollector): name = 'dns' _fact_ids = set() # type: t.Set[str] def collect(self, module=None, collected_facts=None): dns_facts = {} # TODO: flatten dns_facts['dns'] = {} for line in get_file_content('/etc/resolv.conf', '').splitlines(): if li...
DnsFactCollector
python
walkccc__LeetCode
solutions/700. Search in a Binary Search Tree/700.py
{ "start": 0, "end": 278 }
class ____: def searchBST(self, root: TreeNode | None, val: int) -> TreeNode | None: if not root: return None if root.val == val: return root if root.val > val: return self.searchBST(root.left, val) return self.searchBST(root.right, val)
Solution
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 2809, "end": 2877 }
class ____(InputRenderer): tag = "vf-field-file"
FileInputRenderer
python
kamyu104__LeetCode-Solutions
Python/most-common-word.py
{ "start": 111, "end": 655 }
class ____(object): def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ lookup = set(banned) counts = collections.Counter(word.strip("!?',.") for word in paragraph.l...
Solution
python
nedbat__coveragepy
tests/test_process.py
{ "start": 49568, "end": 57622 }
class ____(CoverageTest): """Test that we can measure coverage in subprocesses.""" def make_main_and_sub(self) -> None: """Create main.py and sub.py.""" # Main will run sub.py self.make_file( "main.py", """\ import os, os.path, sys ex = os...
ProcessStartupTest
python
astropy__astropy
astropy/config/configuration.py
{ "start": 1635, "end": 1861 }
class ____(ValueError): """An exception that is raised when the configuration defaults (which should be generated at build-time) are missing. """ # this is used in astropy/__init__.py
ConfigurationDefaultMissingError
python
walkccc__LeetCode
solutions/370. Range Addition/370.py
{ "start": 0, "end": 302 }
class ____: def getModifiedArray( self, length: int, updates: list[list[int]], ) -> list[int]: line = [0] * length for start, end, inc in updates: line[start] += inc if end + 1 < length: line[end + 1] -= inc return itertools.accumulate(line)
Solution
python
scrapy__scrapy
scrapy/exporters.py
{ "start": 11945, "end": 12287 }
class ____(BaseItemExporter): def __init__(self, file: BytesIO, **kwargs: Any): super().__init__(**kwargs) self.file: BytesIO = file def export_item(self, item: Any) -> None: itemdict = dict(self._get_serialized_fields(item)) self.file.write(to_bytes(pprint.pformat(itemdict) + "...
PprintItemExporter
python
PrefectHQ__prefect
src/prefect/utilities/dockerutils.py
{ "start": 13623, "end": 21608 }
class ____(Exception): """Raised when a Docker image push fails""" @silence_docker_warnings() def push_image( image_id: str, registry_url: str, name: str, tag: Optional[str] = None, stream_progress_to: Optional[TextIO] = None, ) -> str: """Pushes a local image to a Docker registry, returni...
PushError
python
automl__auto-sklearn
test/test_evaluation/test_abstract_evaluator.py
{ "start": 627, "end": 11538 }
class ____(unittest.TestCase): _multiprocess_can_split_ = True def setUp(self): """ Creates a backend mock """ self.ev_path = os.path.join(this_directory, ".tmp_evaluations") if not os.path.exists(self.ev_path): os.mkdir(self.ev_path) dummy_model_file...
AbstractEvaluatorTest
python
mlflow__mlflow
mlflow/entities/trace_info.py
{ "start": 717, "end": 9744 }
class ____(_MlflowObject): """Metadata about a trace, such as its ID, location, timestamp, etc. Args: trace_id: The primary identifier for the trace. trace_location: The location where the trace is stored, represented as a :py:class:`~mlflow.entities.TraceLocation` object. MLflow cu...
TraceInfo
python
psf__black
src/blib2to3/pgen2/parse.py
{ "start": 4141, "end": 15480 }
class ____: """Parser engine. The proper usage sequence is: p = Parser(grammar, [converter]) # create instance p.setup([start]) # prepare for parsing <for each input token>: if p.addtoken(...): # parse a token; may raise ParseError break root = p...
Parser
python
tensorflow__tensorflow
tensorflow/python/autograph/tests/basic_ifexp_test.py
{ "start": 1284, "end": 1608 }
class ____(reference_test_base.TestCase): def test_basic(self): for x in [-1, 1, 5, tf.constant(-1), tf.constant(1), tf.constant(5)]: self.assertFunctionMatchesEager(consecutive_conds, x) self.assertFunctionMatchesEager(cond_with_multiple_values, x) if __name__ == '__main__': tf.test.main()
ReferenceTest
python
getsentry__sentry
src/sentry/unmerge.py
{ "start": 4487, "end": 7376 }
class ____(abc.ABC): """ Parsed arguments of the Sentry unmerge task. Since events of the source issue are processed in batches, one can think of each batch as belonging to a state in a statemachine. That statemachine has only two states: Processing the first page (`InitialUnmergeArgs`), proces...
UnmergeArgsBase
python
huggingface__transformers
src/transformers/models/ovis2/modeling_ovis2.py
{ "start": 14751, "end": 15722 }
class ____(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Ovis2VisionEncoderLayer`]. Args: config: Ovis2VisionConfig """ def __init__(self, config: Ovis2VisionConfig): super().__init__() self.config ...
Ovis2VisionEncoder
python
encode__django-rest-framework
tests/test_serializer_lists.py
{ "start": 13850, "end": 22680 }
class ____: """ When not submitting key for list fields or multiple choice, partial serialization should result in an empty state (key not there), not an empty list. Regression test for Github issue #2761. """ def test_partial_listfield(self): class ListSerializer(serializers.Serial...
TestSerializerPartialUsage
python
networkx__networkx
networkx/algorithms/isomorphism/vf2userfunc.py
{ "start": 7268, "end": 7371 }
class ____(DiGraphMatcher): """VF2 isomorphism checker for directed multigraphs."""
MultiDiGraphMatcher
python
pydantic__pydantic
pydantic/v1/types.py
{ "start": 34622, "end": 35455 }
class ____(date, metaclass=ConstrainedNumberMeta): gt: OptionalDate = None ge: OptionalDate = None lt: OptionalDate = None le: OptionalDate = None @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: update_not_none(field_schema, exclusiveMinimum=cls.gt, exclus...
ConstrainedDate
python
kamyu104__LeetCode-Solutions
Python/sort-integers-by-the-number-of-1-bits.py
{ "start": 33, "end": 443 }
class ____(object): def sortByBits(self, arr): """ :type arr: List[int] :rtype: List[int] """ def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number result = 0 while n: n &= n - 1 result += 1 retur...
Solution
python
huggingface__transformers
src/transformers/models/parakeet/configuration_parakeet.py
{ "start": 812, "end": 6987 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ParakeetEncoder`]. It is used to instantiate a `ParakeetEncoder` model according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedConfig`] and ...
ParakeetEncoderConfig
python
getsentry__sentry
src/sentry/api/serializers/types.py
{ "start": 165, "end": 348 }
class ____(TypedDict, total=False): avatarType: str avatarUuid: str | None avatarUrl: str | None # Reponse type for OrganizationReleaseDetailsEndpoint
SerializedAvatarFields
python
getsentry__sentry
src/sentry/integrations/vercel/client.py
{ "start": 348, "end": 3943 }
class ____(ApiClient): base_url = "https://api.vercel.com" integration_name = "vercel" pagination_limit = 100 # Current User API (Read) # https://vercel.com/docs/integrations/reference#using-the-vercel-api/scopes/user GET_USER_URL = "/v2/user" # Teams API Scope (Read) # https://vercel....
VercelClient
python
keras-team__keras
keras/src/layers/pooling/global_average_pooling_test.py
{ "start": 2815, "end": 6108 }
class ____(testing.TestCase): @parameterized.parameters( ("channels_last", False), ("channels_last", True), ("channels_first", False), ("channels_first", True), ) def test_global_average_pooling1d(self, data_format, keepdims): def np_gap1d(x, data_format, keepdims, ma...
GlobalAveragePoolingCorrectnessTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes5.py
{ "start": 6536, "end": 6623 }
class ____: def __eq__(self, other: object) -> bool: return True
ParentClass5
python
lepture__authlib
authlib/oauth2/rfc7591/endpoint.py
{ "start": 527, "end": 7183 }
class ____: """The client registration endpoint is an OAuth 2.0 endpoint designed to allow a client to be registered with the authorization server. """ ENDPOINT_NAME = "client_registration" #: Rewrite this value with a list to support ``software_statement`` #: e.g. ``software_statement_alg_val...
ClientRegistrationEndpoint
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 924449, "end": 925315 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveEnterpriseAdmin""" __schema__ = github_schema __field_names__ = ("admin", "client_mutation_id", "enterprise", "message", "viewer") admin = sgqlc.types.Field("User", graphql_name="admin") """The user who was removed as an administra...
RemoveEnterpriseAdminPayload
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 12207, "end": 12538 }
class ____(LinalgTestCase): @slow def test_generalized_nonsq_cases(self): self.check_cases(require={"generalized", "nonsquare"}, exclude={"size-0"}) @slow def test_generalized_empty_nonsq_cases(self): self.check_cases(require={"generalized", "nonsquare", "size-0"})
LinalgGeneralizedNonsquareTestCase
python
django__django
tests/serializers/models/data.py
{ "start": 849, "end": 920 }
class ____(models.Model): data = models.DateField(null=True)
DateData
python
kamyu104__LeetCode-Solutions
Python/construct-the-minimum-bitwise-array-ii.py
{ "start": 48, "end": 254 }
class ____(object): def minBitwiseArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ return [x-(((x+1)&~x)>>1) if x&1 else -1 for x in nums]
Solution
python
huggingface__transformers
tests/models/switch_transformers/test_modeling_switch_transformers.py
{ "start": 40285, "end": 44847 }
class ____(unittest.TestCase): @require_torch_accelerator @require_torch_bf16 def test_small_logits(self): r""" Logits testing to check implementation consistency between `t5x` implementation and `transformers` implementation of Switch-C transformers. We only check the logits ...
SwitchTransformerModelIntegrationTests
python
huggingface__transformers
src/transformers/models/efficientnet/modeling_efficientnet.py
{ "start": 3283, "end": 3932 }
class ____(nn.Conv2d): def __init__( self, in_channels, depth_multiplier=1, kernel_size=3, stride=1, padding=0, dilation=1, bias=True, padding_mode="zeros", ): out_channels = in_channels * depth_multiplier super().__init__( ...
EfficientNetDepthwiseConv2d
python
xlwings__xlwings
xlwings/constants.py
{ "start": 49973, "end": 50164 }
class ____: xlValidAlertInformation = 3 # from enum XlDVAlertStyle xlValidAlertStop = 1 # from enum XlDVAlertStyle xlValidAlertWarning = 2 # from enum XlDVAlertStyle
DVAlertStyle
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_checks/asset_check_evaluation.py
{ "start": 449, "end": 1115 }
class ____( NamedTuple( "_AssetCheckEvaluationPlanned", [ ("asset_key", AssetKey), ("check_name", str), ], ) ): """Metadata for the event when an asset check is launched.""" def __new__(cls, asset_key: AssetKey, check_name: str): return super().__...
AssetCheckEvaluationPlanned
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 19546, "end": 23725 }
class ____(TestCase): def test_create_api_view_post(self): class MockCreateApiView(generics.CreateAPIView): def create(self, request, *args, **kwargs): self.called = True self.call_args = (request, args, kwargs) view = MockCreateApiView() data = (...
ApiViewsTests
python
ray-project__ray
python/ray/train/_internal/state/schema.py
{ "start": 3236, "end": 4615 }
class ____(BaseModel): """Metadata for a Ray Train run and information about its workers.""" name: str = Field(description="The name of the Train run.") id: str = Field(description="The unique identifier for each Train run.") job_id: str = Field(description="The Ray Job ID.") controller_actor_id: s...
TrainRunInfo
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_performance_general_settings.py
{ "start": 213, "end": 2423 }
class ____(APITestCase): endpoint = "sentry-api-0-project-performance-general-settings" def setUp(self) -> None: super().setUp() self.login_as(user=self.user, superuser=True) self.project = self.create_project() self.url = reverse( self.endpoint, kwargs=...
ProjectPerformanceGeneralSettingsTest
python
getsentry__sentry
tests/sentry/api/bases/test_organization.py
{ "start": 1732, "end": 1822 }
class ____: @property def is_active(self) -> bool: return True
MockSuperUser
python
tornadoweb__tornado
tornado/template.py
{ "start": 18871, "end": 19267 }
class ____: def each_child(self) -> Iterable["_Node"]: return () def generate(self, writer: "_CodeWriter") -> None: raise NotImplementedError() def find_named_blocks( self, loader: Optional[BaseLoader], named_blocks: Dict[str, "_NamedBlock"] ) -> None: for child in self...
_Node
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 21581, "end": 25062 }
class ____(BiffRecord): """ WARNING The font with index 4 is omitted in all BIFF versions. This means the first four fonts have zero-based indexes, and the fifth font and all following fonts are referenced with one-based indexes. Offset Size Contents 0 2 Height o...
FontRecord
python
ray-project__ray
python/ray/serve/_private/request_router/replica_wrapper.py
{ "start": 3496, "end": 6898 }
class ____: """Contains info on a running replica. Also defines the interface for a request router to talk to a replica. """ def __init__(self, replica_info: RunningReplicaInfo): self._replica_info = replica_info self._multiplexed_model_ids = set(replica_info.multiplexed_model_ids) ...
RunningReplica
python
apache__airflow
providers/vertica/src/airflow/providers/vertica/hooks/vertica.py
{ "start": 2236, "end": 7110 }
class ____(DbApiHook): """ Interact with Vertica. This hook use a customized version of default fetch_all_handler named vertica_fetch_all_handler. """ conn_name_attr = "vertica_conn_id" default_conn_name = "vertica_default" conn_type = "vertica" hook_name = "Vertica" supports_autoc...
VerticaHook
python
numba__numba
numba/tests/test_overlap.py
{ "start": 1383, "end": 3839 }
class ____(TestCase): def check_overlap(self, pyfunc, min_ndim, have_k_argument=False): N = 4 def vary_layouts(orig): yield orig.copy(order='C') yield orig.copy(order='F') a = orig[::-1].copy()[::-1] assert not a.flags.c_contiguous and not a.flags.f_...
TestArrayOverlap
python
aimacode__aima-python
planning.py
{ "start": 37238, "end": 40452 }
class ____: """ Class for formulation GraphPlan algorithm Constructs a graph of state and action space Returns solution for the planning problem """ def __init__(self, planning_problem): self.graph = Graph(planning_problem) self.no_goods = [] self.solution = [] def ...
GraphPlan
python
django__django
tests/syndication_tests/feeds.py
{ "start": 6659, "end": 7326 }
class ____(feedgenerator.Atom1Feed): """ Test of a custom feed generator class. """ def root_attributes(self): attrs = super().root_attributes() attrs["django"] = "rocks" return attrs def add_root_elements(self, handler): super().add_root_elements(handler) h...
MyCustomAtom1Feed
python
pypa__setuptools
setuptools/_vendor/zipp/__init__.py
{ "start": 1832, "end": 3690 }
class ____: """ ZipFile mix-in to ensure names are sanitized. """ def namelist(self): return list(map(self._sanitize, super().namelist())) @staticmethod def _sanitize(name): r""" Ensure a relative path with posix separators and no dot names. Modeled after ...
SanitizedNames
python
pandas-dev__pandas
pandas/tests/extension/test_common.py
{ "start": 233, "end": 285 }
class ____(dtypes.ExtensionDtype): pass
DummyDtype
python
getsentry__sentry
tests/sentry/workflow_engine/processors/test_data_sources.py
{ "start": 298, "end": 5292 }
class ____(BaseWorkflowTest): def setUp(self) -> None: # check that test_base registers the data_source_type_registry assert isinstance(data_source_type_registry.get("test"), mock.Mock) self.query = self.create_snuba_query() self.query_two = self.create_snuba_query() self.d...
TestProcessDataSources
python
pypa__warehouse
warehouse/manage/forms.py
{ "start": 8951, "end": 11218 }
class ____(wtforms.Form): __params__ = ["description", "token_scope"] def __init__( self, *args, user_id, macaroon_service, project_names, selected_project=None, **kwargs, ): super().__init__(*args, **kwargs) self.user_id = user_id ...
CreateMacaroonForm
python
gevent__gevent
src/greentest/3.10/test_asyncore.py
{ "start": 26437, "end": 26608 }
class ____(TestAPI_UseUnixSockets, unittest.TestCase): use_poll = False @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
TestAPI_UseUnixSocketsSelect
python
walkccc__LeetCode
solutions/986. Interval List Intersections/986.py
{ "start": 0, "end": 578 }
class ____: def intervalIntersection(self, firstList: list[list[int]], secondList: list[list[int]]) -> list[list[int]]: ans = [] i = 0 j = 0 while i < len(firstList) and j < len(secondList): # lo := the start of the intersection # hi := the end of the intersecti...
Solution
python
keras-team__keras
keras/src/initializers/random_initializers.py
{ "start": 21113, "end": 23631 }
class ____(RandomInitializer): """Initializer that generates an orthogonal matrix. If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix ...
Orthogonal
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_type_lookup.py
{ "start": 8928, "end": 9179 }
class ____(Sequence[str]): """Represent a sequence of text lines. It turns out that resolving a class which inherits from a parametrised generic type is... tricky. See https://github.com/HypothesisWorks/hypothesis/issues/2951 """
Lines
python
python-poetry__poetry
src/poetry/repositories/single_page_repository.py
{ "start": 329, "end": 727 }
class ____(LegacyRepository): def _get_page(self, name: NormalizedName) -> HTMLPage: """ Single page repositories only have one page irrespective of endpoint. """ response = self._get_response("") if not response: raise PackageNotFoundError(f"Package [{name}] not ...
SinglePageRepository
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverlap1.py
{ "start": 8156, "end": 9224 }
class ____(Protocol): def __call__(self, *args: Any, **kwargs: Any) -> Any: ... @overload def func30(func: CBProto30) -> None: ... @overload # This should generate an error because this overload will never be used. def func30(func: Callable[..., Any]) -> None: ... def func30(func: Any) -> None: ... @overloa...
CBProto30
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/redis.py
{ "start": 701, "end": 5547 }
class ____(ExampleDatabase): """Store Hypothesis examples as sets in the given :class:`~redis.Redis` datastore. This is particularly useful for shared databases, as per the recipe for a :class:`~hypothesis.database.MultiplexedDatabase`. .. note:: If a test has not been run for ``expire_after`...
RedisExampleDatabase
python
gevent__gevent
src/greentest/3.11/test_ssl.py
{ "start": 45751, "end": 76291 }
class ____(unittest.TestCase): def test_constructor(self): for protocol in PROTOCOLS: if has_tls_protocol(protocol): with warnings_helper.check_warnings(): ctx = ssl.SSLContext(protocol) self.assertEqual(ctx.protocol, protocol) with wa...
ContextTests
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 27023, "end": 27971 }
class ____(SpmConverter): def vocab(self, proto): vocab = [ ("<s>NOTUSED", 0.0), ("<pad>", 0.0), ("</s>NOTUSED", 0.0), ("<unk>", 0.0), ("<unk>NOTUSED", -100), ] # We down-grade the original SentencePiece by -100 to avoid using it an...
CamembertConverter
python
walkccc__LeetCode
solutions/2944. Minimum Number of Coins for Fruits/2944-3.py
{ "start": 0, "end": 519 }
class ____: def minimumCoins(self, prices: list[int]) -> int: n = len(prices) ans = math.inf # Stores (dp[i], i), where dp[i] := the minimum number of coins to acquire # fruits[i:] (0-indexed) in ascending order. minQ = collections.deque([(0, n)]) for i in range(n - 1, -1, -1): while mi...
Solution
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/llama_index/vector_stores/couchbase/base.py
{ "start": 17467, "end": 24922 }
class ____(CouchbaseVectorStoreBase): """ Couchbase Vector Store using Search Vector Indexes (FTS-based). This implementation uses Couchbase's Search Vector Indexes, which combine Full-Text Search (FTS) with vector search capabilities. Ideal for hybrid searches combining vector similarity, full-tex...
CouchbaseSearchVectorStore
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/scalarstring.py
{ "start": 2624, "end": 4286 }
class ____(ScalarString): __slots__ = () style = '' def __new__(cls, value, anchor=None): # type: (Text, Any) -> Any return ScalarString.__new__(cls, value, anchor=anchor) def preserve_literal(s): # type: (Text) -> Text return LiteralScalarString(s.replace('\r\n', '\n').replace('...
PlainScalarString
python
huggingface__transformers
src/transformers/models/sam2/modeling_sam2.py
{ "start": 15178, "end": 18858 }
class ____(nn.Module): def __init__( self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, activation: str = "relu", sigmoid_output: bool = False, ): super().__init__() self.num_layers = num_layers self.activation...
Sam2FeedForward
python
getsentry__sentry
tests/sentry/lang/javascript/test_sourcemaps.py
{ "start": 1785, "end": 3220 }
class ____(TestCase): def test_simple(self) -> None: smap_view = SourceMapView.from_json_bytes(sourcemap) result = smap_view.lookup(0, 56) assert result == SourceMapTokenMatch( dst_line=0, dst_col=50, src="foo/file2.js", src_line=0, ...
FindSourceTest
python
numpy__numpy
numpy/f2py/tests/test_assumed_shape.py
{ "start": 63, "end": 847 }
class ____(util.F2PyTest): sources = [ util.getpath("tests", "src", "assumed_shape", "foo_free.f90"), util.getpath("tests", "src", "assumed_shape", "foo_use.f90"), util.getpath("tests", "src", "assumed_shape", "precision.f90"), util.getpath("tests", "src", "assumed_shape", "foo_mod.f...
TestAssumedShapeSumExample
python
streamlit__streamlit
lib/tests/streamlit/web/server/media_file_handler_test.py
{ "start": 1126, "end": 5299 }
class ____(tornado.testing.AsyncHTTPTestCase): def setUp(self) -> None: super().setUp() # Create a new MediaFileManager and assign its storage to # MediaFileHandler. storage = MemoryMediaFileStorage(MOCK_ENDPOINT) self.media_file_manager = MediaFileManager(storage) Me...
MediaFileHandlerTest
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 42496, "end": 47263 }
class ____(DefinedFunction): r""" Catalan numbers The `n^{th}` catalan number is given by: .. math :: C_n = \frac{1}{n+1} \binom{2n}{n} * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n` Examples ======== >>> from sympy import (Symbol, binomial, gamma, hyper, ... cata...
catalan
python
kamyu104__LeetCode-Solutions
Python/integer-replacement.py
{ "start": 32, "end": 509 }
class ____(object): def integerReplacement(self, n): """ :type n: int :rtype: int """ result = 0 while n != 1: b = n & 3 if n == 3: n -= 1 elif b == 3: n += 1 elif b == 1: ...
Solution
python
pydantic__pydantic
pydantic-core/tests/serializers/test_union.py
{ "start": 1899, "end": 3363 }
class ____: def __init__(self, c, d): self.c = c self.d = d @pytest.fixture(scope='module') def model_serializer() -> SchemaSerializer: return SchemaSerializer( core_schema.union_schema( [ core_schema.model_schema( ModelA, ...
ModelB
python
python__mypy
mypy/types.py
{ "start": 46188, "end": 47901 }
class ____(ProperType): """This type has no members. This type is the bottom type. With strict Optional checking, it is the only common subtype between all other types, which allows `meet` to be well defined. Without strict Optional checking, NoneType fills this role. In general, for any type...
UninhabitedType
python
gevent__gevent
src/gevent/tests/test__pool.py
{ "start": 4194, "end": 4307 }
class ____(object): def write(self, *_args): raise RuntimeError('Writing to the file failed')
FakeFile
python
sqlalchemy__sqlalchemy
test/orm/test_instrumentation.py
{ "start": 15400, "end": 19442 }
class ____(fixtures.MappedTest): """Seems basic, but not directly covered elsewhere!""" def test_compileonattr(self): t = Table( "t", MetaData(), Column("id", Integer, primary_key=True), Column("x", Integer), ) class A: pass ...
MiscTest
python
numpy__numpy
numpy/_core/tests/test__exceptions.py
{ "start": 2209, "end": 2922 }
class ____: def test_attr(self, args): """Validate attribute types.""" exc = AxisError(*args) if len(args) == 1: assert exc.axis is None assert exc.ndim is None else: axis, ndim, *_ = args assert exc.axis == axis assert exc....
TestAxisError
python
pennersr__django-allauth
allauth/socialaccount/providers/oauth2/views.py
{ "start": 1157, "end": 3238 }
class ____: expires_in_key = "expires_in" client_class = OAuth2Client supports_state = True redirect_uri_protocol: Optional[str] = None access_token_method = "POST" # nosec login_cancelled_error = "access_denied" scope_delimiter = " " basic_auth = False headers: Optional[Dict[str, s...
OAuth2Adapter
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/utils/logging.py
{ "start": 4099, "end": 6441 }
class ____(RichHandler): KEYWORDS: ClassVar[Optional[List[str]]] = [] def __init__(self, stream: Optional[TextIO], no_color: bool) -> None: super().__init__( console=Console(file=stream, no_color=no_color, soft_wrap=True), show_time=False, show_level=False, ...
RichPipStreamHandler
python
walkccc__LeetCode
solutions/2193. Minimum Number of Moves to Make Palindrome/2193.py
{ "start": 0, "end": 413 }
class ____: def minMovesToMakePalindrome(self, s: str) -> int: ans = 0 chars = list(s) while len(chars) > 1: # Greedily match the last digit. i = chars.index(chars[-1]) if i == len(chars) - 1: # s[i] is the middle letter. ans += i // 2 else: chars.pop(i) ...
Solution
python
pandas-dev__pandas
pandas/tests/plotting/test_converter.py
{ "start": 1391, "end": 4141 }
class ____: @pytest.mark.single_cpu def test_dont_register_by_default(self): # Run in subprocess to ensure a clean state code = ( "import matplotlib.units; " "import pandas as pd; " "units = dict(matplotlib.units.registry); " "assert pd.Timestamp n...
TestRegistration
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 39007, "end": 42473 }
class ____(TestCase): def test_subconfig_wrong_type(self): # Test that an error is raised if subconfig does not receive a dict class Schema: option = c.SubConfig() for val in "not_a_dict", ("not_a_dict",), ["not_a_dict"]: with self.subTest(val): with ...
SubConfigTest
python
python-attrs__attrs
tests/test_setattr.py
{ "start": 267, "end": 341 }
class ____: x = attr.ib(on_setattr=lambda *args: None)
WithOnSetAttrHook
python
doocs__leetcode
solution/0300-0399/0319.Bulb Switcher/Solution.py
{ "start": 0, "end": 85 }
class ____: def bulbSwitch(self, n: int) -> int: return int(sqrt(n))
Solution
python
PrefectHQ__prefect
src/prefect/server/services/pause_expirations.py
{ "start": 812, "end": 3320 }
class ____(LoopService): """ Fails flow runs that have been paused and never resumed """ @classmethod def service_settings(cls) -> ServicesBaseSetting: return get_current_settings().server.services.pause_expirations def __init__(self, loop_seconds: Optional[float] = None, **kwargs: Any...
FailExpiredPauses
python
huggingface__transformers
tests/models/mt5/test_modeling_mt5.py
{ "start": 1516, "end": 20376 }
class ____: def __init__( self, parent, vocab_size=99, batch_size=13, encoder_seq_length=7, decoder_seq_length=7, # For common tests is_training=True, use_attention_mask=True, use_labels=True, hidden_size=32, num_hidden_...
MT5ModelTester
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_distribution_to_match_benfords_law.py
{ "start": 6181, "end": 11932 }
class ____(ColumnAggregateExpectation): """Expect column distribution to match Benford's Law. Tests whether data matches Benford's Law Fraud Detection Algorithm. Uses a Chi-Square Goodness of Fit test with an 80@ p-value. """ # These examples will be shown in the public gallery, and also executed as u...
ExpectColumnDistributionToMatchBenfordsLaw
python
huggingface__transformers
src/transformers/models/vit/modeling_vit.py
{ "start": 19269, "end": 24143 }
class ____(ViTPreTrainedModel): def __init__(self, config: ViTConfig): super().__init__(config) self.vit = ViTModel(config, add_pooling_layer=False, use_mask_token=True) self.decoder = nn.Sequential( nn.Conv2d( in_channels=config.hidden_size, out...
ViTForMaskedImageModeling
python
plotly__plotly.py
plotly/graph_objs/scattermapbox/legendgrouptitle/_font.py
{ "start": 233, "end": 9957 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattermapbox.legendgrouptitle" _path_str = "scattermapbox.legendgrouptitle.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", ...
Font
python
getsentry__sentry
src/sentry/seer/endpoints/organization_seer_explorer_update.py
{ "start": 688, "end": 838 }
class ____(OrganizationPermission): scope_map = { "POST": ["org:read"], } @region_silo_endpoint
OrganizationSeerExplorerUpdatePermission
python
apache__airflow
providers/mysql/src/airflow/providers/mysql/transfers/s3_to_mysql.py
{ "start": 1159, "end": 3938 }
class ____(BaseOperator): """ Loads a file from S3 into a MySQL table. :param s3_source_key: The path to the file (S3 key) that will be loaded into MySQL. :param mysql_table: The MySQL table into where the data will be sent. :param mysql_duplicate_key_handling: Specify what should happen to duplica...
S3ToMySqlOperator
python
plotly__plotly.py
plotly/graph_objs/_deprecations.py
{ "start": 14409, "end": 15227 }
class ____(dict): """ plotly.graph_objs.Stream is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.scatter.Stream - plotly.graph_objs.area.Stream """ def __init__(self, *args, **kwargs): """ plotly.graph_objs.St...
Stream
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/integration_tests/integration_test_defs/definitions/other_local_component_sample/__init__.py
{ "start": 54, "end": 129 }
class ____(BaseModel): a_string: str an_int: int
MyNewComponentSchema
python
readthedocs__readthedocs.org
readthedocs/proxito/tests/test_old_redirects.py
{ "start": 5416, "end": 33792 }
class ____(MockStorageMixin, BaseDocServing): def test_forced_redirect(self): fixture.get( Redirect, project=self.project, redirect_type=EXACT_REDIRECT, from_url="/en/latest/install.html", to_url="/en/latest/tutorial/install.html", forc...
UserRedirectTests
python
marshmallow-code__marshmallow
tests/mypy_test_cases/test_schema.py
{ "start": 163, "end": 748 }
class ____(Schema): foo = String() bar = Integer() class Meta(Schema.Meta): fields = ("foo", "bar") additional = ("baz", "qux") include = { "foo2": String(), } exclude = ("bar", "baz") many = True dateformat = "%Y-%m-%d" datetimefo...
MySchema
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 29196, "end": 29347 }
class ____(BaseDDLElement): element: Constraint def __init__(self, element: Constraint) -> None: self.element = element
CreateConstraint
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 99890, "end": 101129 }
class ____(TypedDict, total=False): """ :class:`altair.GeoJsonFeature` ``TypedDict`` wrapper. Parameters ---------- geometry The feature's geometry properties Properties associated with this feature. type Specifies the type of GeoJSON object. bbox Boundin...
GeoJsonFeatureKwds