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
walkccc__LeetCode
solutions/3339. Find the Number of K-Even Arrays/3339.py
{ "start": 0, "end": 1123 }
class ____: def countOfArrays(self, n: int, m: int, k: int) -> int: MOD = 10**9 + 7 even = m // 2 # the number of even numbers in [1, m] odd = m - even # the number of odd numbers in [1, m] # dp[i][j][0/1] := the number of arrays of length i with j consecutive even # number pairs ending in an ev...
Solution
python
openai__openai-python
src/openai/types/responses/response_output_item_done_event.py
{ "start": 257, "end": 652 }
class ____(BaseModel): item: ResponseOutputItem """The output item that was marked done.""" output_index: int """The index of the output item that was marked done.""" sequence_number: int """The sequence number of this event.""" type: Literal["response.output_item.done"] """The type o...
ResponseOutputItemDoneEvent
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 1450, "end": 6901 }
class ____(ABC): """Base class for all freshness policies. A freshness policy allows you to define expectations for the timing and frequency of asset materializations. An asset with a defined freshness policy can take on different freshness states: - ``PASS``: The asset is passing its freshness policy...
FreshnessPolicy
python
numpy__numpy
numpy/polynomial/tests/test_laguerre.py
{ "start": 16024, "end": 17616 }
class ____: def test_lagfromroots(self): res = lag.lagfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5): roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2]) pol = lag.lagfromroots(roots) res = lag.lagval(roots, pol) tg...
TestMisc
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 85961, "end": 86226 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING AutoModelForNextSentencePrediction = auto_class_update( AutoModelForNextSentencePrediction, head_doc="next sentence prediction" )
AutoModelForNextSentencePrediction
python
tensorflow__tensorflow
tensorflow/python/saved_model/registration/registration_test.py
{ "start": 1143, "end": 1250 }
class ____(RegisteredClass): pass @registration.register_serializable(package="testing")
RegisteredSubclass
python
huggingface__transformers
tests/quantization/finegrained_fp8/test_fp8.py
{ "start": 1225, "end": 2538 }
class ____(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = FineGrainedFP8Config() config_to_dict = quantization_config.to_dict() ...
FineGrainedFP8ConfigTest
python
instagram__MonkeyType
monkeytype/typing.py
{ "start": 15739, "end": 15996 }
class ____(TypeRewriter): def __init__(self, rewriters: Iterable[TypeRewriter]) -> None: self.rewriters = rewriters def rewrite(self, typ): for rw in self.rewriters: typ = rw.rewrite(typ) return typ
ChainedRewriter
python
MongoEngine__mongoengine
mongoengine/base/utils.py
{ "start": 12, "end": 619 }
class ____: """Descriptor to allow lazy compilation of regex""" def __init__(self, pattern, flags=0): self._pattern = pattern self._flags = flags self._compiled_regex = None @property def compiled_regex(self): if self._compiled_regex is None: self._compiled_...
LazyRegexCompiler
python
getsentry__sentry
src/sentry/api/fields/user.py
{ "start": 251, "end": 833 }
class ____(serializers.Field): def to_representation(self, value: RpcUser) -> str: return value.username def to_internal_value(self, data: Any) -> RpcUser | User | None: if not data: return None if isinstance(data, int) or data.isdigit(): user = user_service.get...
UserField
python
PyCQA__pylint
doc/data/messages/n/non-iterator-returned/good.py
{ "start": 16, "end": 796 }
class ____: def __init__(self, signs, predictions): self.signs = signs self.predictions = predictions def __iter__(self): self.index = 0 self.number_of_prediction = len(self.predictions) return self def __next__(self): if self.index == len(self.signs): ...
GenericAstrology
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 126808, "end": 129878 }
class ____(BasePostProgressGroupMixin): """Unit tests for is_issue_eligible_for_seer_automation.""" @patch("sentry.quotas.backend.has_available_reserved_budget", return_value=True) @patch("sentry.seer.seer_setup.get_seer_org_acknowledgement_for_scanner", return_value=True) @patch("sentry.features.has",...
SeerAutomationHelperFunctionsTestMixin
python
rapidsai__cudf
python/cudf/cudf/core/udf/strings_typing.py
{ "start": 1893, "end": 2363 }
class ____(models.StructModel): # from udf_string.hpp: # private: # char* m_data{}; # cudf::size_type m_bytes{}; # cudf::size_type m_size{}; _members = ( ("m_data", types.CPointer(types.char)), ("m_bytes", size_type), ("m_size", size_type), ) def __init__(...
udf_string_model
python
huggingface__transformers
src/transformers/models/moshi/modeling_moshi.py
{ "start": 2145, "end": 5895 }
class ____(ModelOutput): r""" audio_sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, 1, sequence_length)`, *optional*): The generated audio waveforms. sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`): The generated text seq...
MoshiConditionalGenerationGenerateOutput
python
doocs__leetcode
solution/0400-0499/0421.Maximum XOR of Two Numbers in an Array/Solution.py
{ "start": 683, "end": 874 }
class ____: def findMaximumXOR(self, nums: List[int]) -> int: trie = Trie() for x in nums: trie.insert(x) return max(trie.search(x) for x in nums)
Solution
python
python__mypy
mypy/stubtest.py
{ "start": 33565, "end": 88553 }
class ____(Generic[T]): def __init__(self) -> None: self.pos: list[T] = [] self.kwonly: dict[str, T] = {} self.varpos: T | None = None self.varkw: T | None = None def __str__(self) -> str: def get_name(arg: Any) -> str: if isinstance(arg, inspect.Parameter): ...
Signature
python
allegroai__clearml
clearml/binding/environ_bind.py
{ "start": 322, "end": 2468 }
class ____(object): _current_task = None _environment_section = "Environment" __patched = False @classmethod def update_current_task(cls, task: Any) -> None: cls._current_task = task # noinspection PyBroadException try: if not cls.__patched: cls._...
EnvironmentBind
python
django__django
django/db/backends/oracle/functions.py
{ "start": 65, "end": 509 }
class ____(Func): function = "" template = """ EXTRACT(day from %(expressions)s) * 86400 + EXTRACT(hour from %(expressions)s) * 3600 + EXTRACT(minute from %(expressions)s) * 60 + EXTRACT(second from %(expressions)s) """ def __init__(self, expression, *, output_field=None, **extra): ...
IntervalToSeconds
python
huggingface__transformers
src/transformers/models/bert_generation/modeling_bert_generation.py
{ "start": 17547, "end": 19118 }
class ____(nn.Module): """Construct the embeddings from word and position embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(con...
BertGenerationEmbeddings
python
scipy__scipy
scipy/ndimage/tests/test_interpolation.py
{ "start": 14923, "end": 17819 }
class ____: def test_geometric_transform_grid_constant_order1(self, xp): # verify interpolation outside the original bounds x = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=xp.float64) def mapping(x): return (x[0] - 0.5), (x[1] - 0.5) expected_resu...
TestGeometricTransformExtra
python
lepture__authlib
authlib/oauth2/rfc6749/requests.py
{ "start": 4614, "end": 4705 }
class ____: @property def data(self): raise NotImplementedError()
JsonPayload
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/distributions.py
{ "start": 6092, "end": 8225 }
class ____(nn.Module): def __init__(self, hidden_size: int, act_sizes: List[int]): super().__init__() self.act_sizes = act_sizes self.branches = self._create_policy_branches(hidden_size) def _create_policy_branches(self, hidden_size: int) -> nn.ModuleList: branches = [] ...
MultiCategoricalDistribution
python
kubernetes-client__python
kubernetes/client/models/v1_glusterfs_persistent_volume_source.py
{ "start": 383, "end": 7759 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1GlusterfsPersistentVolumeSource
python
wandb__wandb
wandb/vendor/pygments/lexers/python.py
{ "start": 18697, "end": 21892 }
class ____(Lexer): """ For Python console output or doctests, such as: .. sourcecode:: pycon >>> a = 'foo' >>> print a foo >>> 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modul...
PythonConsoleLexer
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/urlfetch/snippets/main.py
{ "start": 2036, "end": 2878 }
class ____(webapp2.RequestHandler): """Demonstrates an HTTP POST form query using urlfetch.""" form_fields = { "first_name": "Albert", "last_name": "Johnson", } def get(self): # [START gae_urlfetch_snippets_urlfetch_post] try: form_data = urllib.urlencode(Ur...
UrlPostHandler
python
ray-project__ray
release/ray_release/exception.py
{ "start": 947, "end": 1024 }
class ____(RuntimeError): exit_code = ExitCode.UNSPECIFIED
ReleaseTestError
python
pypa__pip
src/pip/_vendor/rich/syntax.py
{ "start": 7621, "end": 7967 }
class ____: """Descriptor to get and set padding.""" def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]: """Space around the Syntax.""" return obj._padding def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None: obj._padding = Padding.unp...
PaddingProperty
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/job_base.py
{ "start": 3098, "end": 4293 }
class ____(IJob): def __init__( self, job_name: str, repository_def: "RepositoryDefinition", ): self._job_name = job_name self._repository_def = repository_def def get_definition(self) -> "JobDefinition": return self._repository_def.get_job(self._job_name) ...
RepoBackedJob
python
sympy__sympy
sympy/printing/mathml.py
{ "start": 2577, "end": 18949 }
class ____(MathMLPrinterBase): """Prints an expression to the Content MathML markup language. References: https://www.w3.org/TR/MathML2/chapter4.html """ printmethod = "_mathml_content" def mathml_tag(self, e): """Returns the MathML tag for an expression.""" translate = { ...
MathMLContentPrinter
python
doocs__leetcode
solution/1600-1699/1659.Maximize Grid Happiness/Solution.py
{ "start": 0, "end": 1408 }
class ____: def getMaxGridHappiness( self, m: int, n: int, introvertsCount: int, extrovertsCount: int ) -> int: @cache def dfs(i: int, pre: int, ic: int, ec: int) -> int: if i == m or (ic == 0 and ec == 0): return 0 ans = 0 for cur in r...
Solution
python
django__django
tests/bulk_create/models.py
{ "start": 998, "end": 1034 }
class ____(Place): pass
Restaurant
python
kamyu104__LeetCode-Solutions
Python/uncommon-words-from-two-sentences.py
{ "start": 62, "end": 377 }
class ____(object): def uncommonFromSentences(self, A, B): """ :type A: str :type B: str :rtype: List[str] """ count = collections.Counter(A.split()) count += collections.Counter(B.split()) return [word for word in count if count[word] == 1]
Solution
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 11017, "end": 11893 }
class ____(PipenvException): def __init__(self, message, no_version_found=False): extra = ( "Your dependencies could not be resolved. You likely have a " "mismatch in your sub-dependencies.\n" "You can use [yellow]$ pipenv run pip install <requirement_name>[/yellow] to by...
ResolutionFailure
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams5.py
{ "start": 1154, "end": 1266 }
class ____[R: t2]: ... # This should generate an error because constraints must be legal # type expressions.
ClassL
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 76738, "end": 78205 }
class ____(PrefectOperatorFilterBaseModel): """Filter artifacts. Only artifacts matching all criteria will be returned""" id: Optional[ArtifactFilterId] = Field( default=None, description="Filter criteria for `Artifact.id`" ) key: Optional[ArtifactFilterKey] = Field( default=None, descr...
ArtifactFilter
python
pandas-dev__pandas
pandas/tests/indexing/test_datetime.py
{ "start": 169, "end": 5714 }
class ____: def test_get_loc_naive_dti_aware_str_deprecated(self): # GH#46903 ts = Timestamp("20130101")._value dti = pd.DatetimeIndex([ts + 50 + i for i in range(100)]) ser = Series(range(100), index=dti) key = "2013-01-01 00:00:00.000000050+0000" msg = re.escape(re...
TestDatetimeIndex
python
ray-project__ray
python/ray/dag/tests/test_class_dag.py
{ "start": 159, "end": 336 }
class ____: def __init__(self, init_value=0): self.i = init_value def inc(self): self.i += 1 def get(self): return self.i @ray.remote
Counter
python
coleifer__peewee
tests/db_url.py
{ "start": 127, "end": 3532 }
class ____(BaseTestCase): def test_db_url_parse(self): cfg = parse('mysql://usr:pwd@hst:123/db') self.assertEqual(cfg['user'], 'usr') self.assertEqual(cfg['passwd'], 'pwd') self.assertEqual(cfg['host'], 'hst') self.assertEqual(cfg['database'], 'db') self.assertEqual(c...
TestDBUrl
python
pennersr__django-allauth
tests/apps/socialaccount/providers/mediawiki/tests.py
{ "start": 246, "end": 1203 }
class ____(OAuth2TestsMixin, TestCase): provider_id = MediaWikiProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "iss": "https://meta.wikimedia.org", "sub": 12345, "a...
MediaWikiTests
python
spack__spack
lib/spack/spack/spec.py
{ "start": 219681, "end": 220038 }
class ____(spack.error.SpecError): """Raised when an invalid conditional variant is specified.""" def __init__(self, variant, when, spec): msg = f"Invalid variant {variant} for spec {spec}.\n" msg += f"{variant} is only available for {spec.name} when satisfying one of {when}." super()._...
InvalidVariantForSpecError
python
keras-team__keras
keras/src/layers/preprocessing/hashing.py
{ "start": 338, "end": 11188 }
class ____(Layer): """A preprocessing layer which hashes and bins categorical features. This layer transforms categorical inputs to hashed output. It element-wise converts a ints or strings to ints in a fixed range. The stable hash function uses `tensorflow::ops::Fingerprint` to produce the same output...
Hashing
python
weaviate__weaviate-python-client
weaviate/collections/queries/hybrid/generate/executor.py
{ "start": 1053, "end": 23519 }
class ____( Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType] ): @overload def hybrid( self, query: Optional[str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, group...
_HybridGenerateExecutor
python
kamyu104__LeetCode-Solutions
Python/amount-of-new-area-painted-each-day.py
{ "start": 86, "end": 1068 }
class ____(object): def amountPainted(self, paint): """ :type paint: List[List[int]] :rtype: List[int] """ points = collections.defaultdict(list) for i, (s, e) in enumerate(paint): points[s].append((True, i)) points[e].append((False, i)) ...
Solution
python
pytorch__pytorch
test/package/test_trace_dep/__init__.py
{ "start": 28, "end": 117 }
class ____(torch.nn.Module): def forward(self, inp): return torch.sum(inp)
SumMod
python
tensorflow__tensorflow
tensorflow/python/data/ops/structured_function.py
{ "start": 2551, "end": 12798 }
class ____(): """A function wrapper that supports structured arguments and return values.""" def __init__(self, func, transformation_name, dataset=None, input_classes=None, input_shapes=None, input_types=None, ...
StructuredFunctionWrapper
python
kamyu104__LeetCode-Solutions
Python/equal-tree-partition.py
{ "start": 50, "end": 675 }
class ____(object): def checkEqualTree(self, root): """ :type root: TreeNode :rtype: bool """ def getSumHelper(node, lookup): if not node: return 0 total = node.val + \ getSumHelper(node.left, lookup) + \ ...
Solution
python
dask__dask
dask/typing.py
{ "start": 14628, "end": 15168 }
class ____(DaskCollection, Protocol): """Protocol defining a Dask collection that uses HighLevelGraphs. This protocol is nearly identical to :py:class:`~dask.typing.DaskCollection`, with the addition of the ``__dask_layers__`` method (required for collections backed by high level graphs). """ ...
HLGDaskCollection
python
bokeh__bokeh
src/bokeh/core/property/dataspec.py
{ "start": 13345, "end": 13945 }
class ____(DataSpec): """ A |DataSpec| property that accepts hatch pattern types as fixed values. The ``HatchPatternSpec`` property attempts to first interpret string values as hatch pattern types. Otherwise, string values are interpreted as field names. For example: .. code-block:: python ...
HatchPatternSpec
python
pytorch__pytorch
torch/_functorch/_aot_autograd/schemas.py
{ "start": 4506, "end": 4675 }
class ____(Enum): NOT_MUTATED = 1 MUTATED_IN_GRAPH = 2 MUTATED_OUT_GRAPH = 3 # This class tells us info about user inputs. @dataclass(frozen=True)
MutationType
python
ray-project__ray
python/ray/_common/tests/test_signature.py
{ "start": 11724, "end": 14128 }
class ____: """Tests for the recover_args utility function.""" def test_only_positional_args(self): """Test recovering only positional arguments.""" flattened = [DUMMY_TYPE, 1, DUMMY_TYPE, 2, DUMMY_TYPE, 3] args, kwargs = recover_args(flattened) assert args == [1, 2, 3] ...
TestRecoverArgs
python
getsentry__sentry
src/sentry/api/endpoints/api_application_rotate_secret.py
{ "start": 584, "end": 1090 }
class ____(ApiApplicationEndpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ENTERPRISE authentication_classes = (SessionAuthentication,) permission_classes = (SentryIsAuthenticated,) def post(self, request: Request, application: ApiApplication) -> Respons...
ApiApplicationRotateSecretEndpoint
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_datacatalog.py
{ "start": 19735, "end": 21085 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook") def test_assert_valid_hook_call(self, mock_hook) -> None: with pytest.warns(AirflowProviderDeprecationWarning): task = CloudDataCatalogDeleteTagOperator( task_id="task_id", ...
TestCloudDataCatalogDeleteTagOperator
python
pytorch__pytorch
test/inductor/test_cooperative_reductions.py
{ "start": 8804, "end": 8958 }
class ____(CooperativeReductionTests): pass @config.patch("triton.multi_kernel", int(not config.triton.multi_kernel))
NoPersistCooperativeReductionTests
python
pennersr__django-allauth
allauth/socialaccount/providers/facebook/views.py
{ "start": 1728, "end": 3231 }
class ____(View): @method_decorator(login_not_required) def dispatch(self, request): self.adapter = get_adapter() self.provider = self.adapter.get_provider(request, PROVIDER_ID) try: return super().dispatch(request) except ( requests.RequestException, ...
LoginByTokenView
python
nedbat__coveragepy
coverage/templite.py
{ "start": 760, "end": 2305 }
class ____: """Build source code conveniently.""" def __init__(self, indent: int = 0) -> None: self.code: list[str | CodeBuilder] = [] self.indent_level = indent def __str__(self) -> str: return "".join(str(c) for c in self.code) def add_line(self, line: str) -> None: ...
CodeBuilder
python
google__flatbuffers
tests/py_test.py
{ "start": 68981, "end": 81183 }
class ____(unittest.TestCase): def setUp(self, *args, **kwargs): super(TestAllCodePathsOfExampleSchema, self).setUp(*args, **kwargs) b = flatbuffers.Builder(0) _MONSTER.MonsterStart(b) gen_mon = _MONSTER.MonsterEnd(b) b.Finish(gen_mon) self.mon = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()...
TestAllCodePathsOfExampleSchema
python
cython__cython
Cython/Shadow.py
{ "start": 12273, "end": 12496 }
class ____(typedef): def __init__(self, type, name=None): name = f"const {name or repr(type)}" super().__init__(type, name) def __class_getitem__(cls, base_type): return const(base_type)
const
python
run-llama__llama_index
llama-index-finetuning/llama_index/finetuning/mistralai/base.py
{ "start": 785, "end": 5506 }
class ____(BaseLLMFinetuneEngine): """MistralAI Finetuning Engine.""" def __init__( self, base_model: str, training_path: str, validation_path: Optional[str] = None, verbose: bool = False, start_job_id: Optional[str] = None, validate_json: bool = True, ...
MistralAIFinetuneEngine
python
django__django
tests/decorators/test_cache.py
{ "start": 298, "end": 525 }
class ____: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr)
HttpRequestProxy
python
google__pytype
pytype/tools/xref/indexer.py
{ "start": 5710, "end": 7192 }
class ____: """A symbol definition. Attributes: name: The symbol name typ: The definition type (e.g. ClassDef) data: Pytype data from the opcode traces scope: The namespace id (e.g. module:class A:function f:x) target: The LHS of an attribute (e.g. for x.foo, target = typeof(x)) doc: The do...
Definition
python
aimacode__aima-python
notebook4e.py
{ "start": 30778, "end": 44488 }
class ____(Canvas): """fol_bc_ask() on HTML canvas""" def __init__(self, varname, kb, query, width=800, height=600, cid=None): super().__init__(varname, width, height, cid) self.kb = kb self.query = query self.l = 1 / 20 self.b = 3 * self.l bc_out = list(self.fol...
Canvas_fol_bc_ask
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol40.py
{ "start": 583, "end": 630 }
class ____(P2Parent[T], Protocol[T]): ...
P2Child
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image23.py
{ "start": 315, "end": 1060 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image23.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(...
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/k-inverse-pairs-array.py
{ "start": 2439, "end": 2991 }
class ____(object): def kInversePairs(self, n, k): """ :type n: int :type k: int :rtype: int """ MOD = 10**9+7 dp = [[] for _ in xrange(k+1)] dp[0].append([]) for i in xrange(n): dp = [[[x+int(x >= i-k) for x in p]+[i-k] for k in xr...
Solution_ConstructPermutation
python
huggingface__transformers
src/transformers/models/mixtral/modular_mixtral.py
{ "start": 18666, "end": 18943 }
class ____(MistralForQuestionAnswering): pass __all__ = [ "MixtralForCausalLM", "MixtralForQuestionAnswering", "MixtralModel", "MixtralPreTrainedModel", "MixtralForSequenceClassification", "MixtralForTokenClassification", ]
MixtralForQuestionAnswering
python
kubernetes-client__python
kubernetes/e2e_test/port_server.py
{ "start": 76, "end": 1166 }
class ____: def __init__(self, port): self.port = port self.server = socketserver.ThreadingTCPServer(('0.0.0.0', port), self.handler) self.server.daemon_threads = True self.thread = threading.Thread(target=self.server.serve_forever, name='Port %...
PortServer
python
redis__redis-py
tests/test_asyncio/test_command_parser.py
{ "start": 244, "end": 5576 }
class ____: @pytest.mark.asyncio async def test_get_command_policies(self, r): commands_parser = AsyncCommandsParser() await commands_parser.initialize(node=r.get_default_node()) expected_command_policies = { "core": { "keys": [ "keys", ...
TestAsyncCommandParser
python
RaRe-Technologies__gensim
gensim/test/basetmtests.py
{ "start": 312, "end": 1837 }
class ____: def test_print_topic(self): topics = self.model.show_topics(formatted=True) for topic_no, topic in topics: self.assertTrue(isinstance(topic_no, int)) self.assertTrue(isinstance(topic, str)) def test_print_topics(self): topics = self.model.print_topics...
TestBaseTopicModel
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 43559, "end": 44423 }
class ____(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `JavascriptLexer`. """ name = 'JavaScript+Django/Jinja' aliases = ['js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'] alias_filenames = ['*.js'] mimetypes =...
JavascriptDjangoLexer
python
pytorch__pytorch
test/distributed/test_nvshmem.py
{ "start": 27072, "end": 28295 }
class ____(MultiProcContinuousTest): def _init_device(self) -> None: # TODO: relieve this (seems to hang if without) device_module.set_device(self.device) # Set NVSHMEM as SymmMem backend symm_mem.set_backend("NVSHMEM") @property def device(self) -> torch.device: ret...
DispatchCombineInSubgroups
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 79654, "end": 87716 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) autoscale: Optional[AutoScale] = Field( None, description=( "If autoscale, the required parameters to automatically scale clusters up" ...
NewCluster
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 32312, "end": 33696 }
class ____(AssetSelection): left: AssetSelection right: AssetSelection def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: return self.left.resolve_inner( asset_graph, allow_missing=allow_missing ) - self.right.resolv...
SubtractAssetSelection
python
pytorch__pytorch
torch/profiler/_pattern_matcher.py
{ "start": 17685, "end": 19294 }
class ____(Pattern): """ This pattern identifies if we are enabling bias in Conv2d which is followed by BatchNorm2d. Bias doesn't do anything when followed by batchnorm. Pattern: nn.Module: Conv2d | nn.Module: BatchNorm2d ... aten::conv2d AND dtype of third argument is...
Conv2dBiasFollowedByBatchNorm2dPattern
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/base.py
{ "start": 71332, "end": 72036 }
class ____(compiler.IdentifierPreparer): reserved_words = {x.lower() for x in RESERVED_WORDS} illegal_initial_characters = {str(dig) for dig in range(0, 10)}.union( ["_", "$"] ) def _bindparam_requires_quotes(self, value): """Return True if the given identifier requires quoting.""" ...
OracleIdentifierPreparer
python
getsentry__sentry
src/sentry/models/groupopenperiod.py
{ "start": 1033, "end": 1419 }
class ____(models.Func): function = "TSTZRANGE" output_field = DateTimeRangeField() def should_create_open_periods(type_id: int) -> bool: grouptypes_without_open_periods = options.get( "workflow_engine.group.type_id.open_periods_type_denylist" ) if type_id in grouptypes_without_open_period...
TsTzRange
python
numba__llvmlite
llvmlite/tests/customize.py
{ "start": 11689, "end": 13268 }
class ____(runner.TextTestRunner): """ A test runner which delegates the actual running to a pool of child processes. """ resultclass = ParallelTestResult def __init__(self, runner_cls, **kwargs): runner.TextTestRunner.__init__(self, **kwargs) self.runner_cls = runner_cls ...
ParallelTestRunner
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 21942, "end": 22487 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.predictions = MobileBertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output: torch.Tensor, pooled_output: torch.Tensor) -> tuple[torch.Tensor]: ...
MobileBertPreTrainingHeads
python
pypa__pip
src/pip/_vendor/rich/progress.py
{ "start": 8721, "end": 17245 }
class ____(ContextManager[_I], Generic[_I]): """A utility class to handle a context for both a reader and a progress.""" def __init__(self, progress: "Progress", reader: _I) -> None: self.progress = progress self.reader: _I = reader def __enter__(self) -> _I: self.progress.start() ...
_ReadContext
python
kamyu104__LeetCode-Solutions
Python/check-if-string-is-transformable-with-substring-sort-operations.py
{ "start": 29, "end": 646 }
class ____(object): def isTransformable(self, s, t): """ :type s: str :type t: str :rtype: bool """ idxs = [[] for _ in xrange(10)] for i in reversed(xrange(len(s))): idxs[int(s[i])].append(i) for c in t: d = int(c) ...
Solution
python
walkccc__LeetCode
solutions/1578. Minimum Time to Make Rope Colorful/1578.py
{ "start": 0, "end": 737 }
class ____: def minCost(self, colors: str, neededTime: list[int]) -> int: ans = 0 maxNeededTime = neededTime[0] for i in range(1, len(colors)): if colors[i] == colors[i - 1]: ans += min(maxNeededTime, neededTime[i]) # For each continuous group, Bob needs to remove every balloon exce...
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/cli/argparsing/parsers.py
{ "start": 864, "end": 972 }
class ____(Exception): """Base class for argument completion results.""" @dataclasses.dataclass
Completion
python
huggingface__transformers
src/transformers/models/janus/modular_janus.py
{ "start": 23839, "end": 24722 }
class ____(ChameleonVQVAEVectorQuantizer): def __init__(self, config: JanusVQVAEConfig): super().__init__(config) self.quant_state_dims = [config.num_patches] * 2 def get_codebook_entry(self, image_tokens: torch.LongTensor) -> torch.FloatTensor: batch_size = image_tokens.shape[0] ...
JanusVQVAEVectorQuantizer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1586517, "end": 1586797 }
class ____(sgqlc.types.Union): """Represents either a pull request the viewer can access or a restricted contribution. """ __schema__ = github_schema __types__ = (CreatedPullRequestContribution, RestrictedContribution)
CreatedPullRequestOrRestrictedContribution
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_index_tricks.py
{ "start": 17271, "end": 19572 }
class ____(TestCase): def test_basic(self): a = np.zeros((3, 3), dtype=int) fill_diagonal(a, 5) assert_array_equal(a, np.array([[5, 0, 0], [0, 5, 0], [0, 0, 5]])) def test_tall_matrix(self): a = np.zeros((10, 3), dtype=int) fill_diagonal(a, 5) assert_array_equal(...
TestFillDiagonal
python
tensorflow__tensorflow
tensorflow/python/debug/lib/source_remote_test.py
{ "start": 1591, "end": 8243 }
class ____(test_util.TensorFlowTestCase): @classmethod def setUpClass(cls): test_util.TensorFlowTestCase.setUpClass() (cls._server_port, cls._debug_server_url, cls._server_dump_dir, cls._server_thread, cls._server) = grpc_debug_test_server.start_server_on_separate_thread( poll_server=Tru...
SendTracebacksTest
python
apache__airflow
providers/snowflake/tests/unit/snowflake/operators/test_snowflake_sql.py
{ "start": 1337, "end": 10479 }
class ____: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __eq__(self, other): return isinstance(other, MockRow) and self.__dict__ == other.__dict__ def __hash__(self): return hash(self.__dict__) def __repr__(self): return f"MockRow({self.__dict__})" ...
MockRow
python
simonw__datasette
datasette/views/special.py
{ "start": 40025, "end": 41613 }
class ____(SchemaBaseView): """ Displays schema for a specific table. Supports HTML, JSON, and Markdown formats. """ name = "table_schema" async def get(self, request): database_name = request.url_vars["database"] table_name = request.url_vars["table"] format_ = request...
TableSchemaView
python
streamlit__streamlit
lib/streamlit/elements/lib/js_number.py
{ "start": 737, "end": 3532 }
class ____: """Utility class for exposing JavaScript Number constants.""" # The largest int that can be represented with perfect precision # in JavaScript. MAX_SAFE_INTEGER = (1 << 53) - 1 # The smallest int that can be represented with perfect precision # in JavaScript. MIN_SAFE_INTEGER =...
JSNumber
python
pennersr__django-allauth
allauth/headless/apps.py
{ "start": 91, "end": 261 }
class ____(AppConfig): name = "allauth.headless" verbose_name = _("Headless") def ready(self): from allauth.headless import checks # noqa
HeadlessConfig
python
python-openxml__python-docx
src/docx/enum/style.py
{ "start": 81, "end": 9427 }
class ____(BaseEnum): """Alias: **WD_STYLE** Specifies a built-in Microsoft Word style. Example:: from docx import Document from docx.enum.style import WD_STYLE document = Document() styles = document.styles style = styles[WD_STYLE.BODY_TEXT] MS API name: `W...
WD_BUILTIN_STYLE
python
pytorch__pytorch
torch/_inductor/codecache.py
{ "start": 26416, "end": 36942 }
class ____: """ Object to capture all the details for a compiled FX graph relevant to computing a safe and stable cache key. """ # Excluded kwargs param that are not stable between runs EXCLUDED_KWARGS = ["graph_id"] def __init__( self, gm: torch.fx.GraphModule, exa...
FxGraphHashDetails
python
huggingface__transformers
tests/models/mistral3/test_modeling_mistral3.py
{ "start": 1447, "end": 5411 }
class ____: def __init__( self, parent, batch_size=3, seq_length=7, image_seq_length=4, vision_feature_layer=-1, ignore_index=-100, image_token_index=1, num_channels=3, image_size=30, model_type="mistral3", is_training=T...
Mistral3VisionText2TextModelTester
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_datetime.py
{ "start": 287, "end": 5378 }
class ____: def test_is_(self): dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME") assert dti.is_(dti) assert dti.is_(dti.view()) assert not dti.is_(dti.copy()) def test_time_overflow_for_32bit_machines(self): # GH8943. On some machines NumPy defaults to np....
TestDatetimeIndex
python
chardet__chardet
chardet/sbcharsetprober.py
{ "start": 1329, "end": 1578 }
class ____(NamedTuple): charset_name: str language: str char_to_order_map: Dict[int, int] language_model: Dict[int, Dict[int, int]] typical_positive_ratio: float keep_ascii_letters: bool alphabet: str
SingleByteCharSetModel
python
kamyu104__LeetCode-Solutions
Python/better-compression-of-string.py
{ "start": 63, "end": 670 }
class ____(object): def betterCompression(self, compressed): """ :type compressed: str :rtype: str """ cnt = [0]*26 x, curr = -1, 0 for i in xrange(len(compressed)): if not compressed[i].isdigit(): x = ord(compressed[i])-ord('a') ...
Solution
python
kubernetes-client__python
kubernetes/client/models/v1_node_runtime_handler.py
{ "start": 383, "end": 4262 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1NodeRuntimeHandler
python
pytorch__pytorch
torch/distributed/elastic/rendezvous/etcd_server.py
{ "start": 2132, "end": 8415 }
class ____: """ .. note:: tested on etcd server v3.4.3. Starts and stops a local standalone etcd server on a random free port. Useful for single node, multi-worker launches or testing, where a sidecar etcd server is more convenient than having to separately setup an etcd server. This class...
EtcdServer
python
pypa__pip
src/pip/_internal/resolution/resolvelib/requirements.py
{ "start": 5214, "end": 7260 }
class ____(Requirement): """A requirement representing Requires-Python metadata.""" def __init__(self, specifier: SpecifierSet, match: Candidate) -> None: self.specifier = specifier self._specifier_string = str(specifier) # for faster __eq__ self._hash: int | None = None self._...
RequiresPythonRequirement
python
apache__airflow
providers/apache/cassandra/tests/unit/apache/cassandra/sensors/test_record.py
{ "start": 1051, "end": 3262 }
class ____: @patch("airflow.providers.apache.cassandra.sensors.record.CassandraHook") def test_poke(self, mock_hook): sensor = CassandraRecordSensor( task_id="test_task", cassandra_conn_id=TEST_CASSANDRA_CONN_ID, table=TEST_CASSANDRA_TABLE, keys=TEST_CASSA...
TestCassandraRecordSensor
python
huggingface__transformers
src/transformers/models/deepseek_v2/modular_deepseek_v2.py
{ "start": 14696, "end": 15548 }
class ____(LlamaRotaryEmbedding): @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = p...
DeepseekV2RotaryEmbedding