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
doocs__leetcode
solution/1000-1099/1017.Convert to Base -2/Solution.py
{ "start": 0, "end": 311 }
class ____: def baseNeg2(self, n: int) -> str: k = 1 ans = [] while n: if n % 2: ans.append('1') n -= k else: ans.append('0') n //= 2 k *= -1 return ''.join(ans[::-1]) or '0'
Solution
python
encode__django-rest-framework
rest_framework/authentication.py
{ "start": 4896, "end": 6917 }
class ____(BaseAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ keyword =...
TokenAuthentication
python
walkccc__LeetCode
solutions/1509. Minimum Difference Between Largest and Smallest Value in Three Moves/1509.py
{ "start": 0, "end": 333 }
class ____: def minDifference(self, nums: list[int]) -> int: n = len(nums) if n < 5: return 0 ans = math.inf nums.sort() # 1. Change nums[0..i) to nums[i]. # 2. Change nums[n - 3 + i..n) to nums[n - 4 + i]. for i in range(4): ans = min(ans, nums[n - 4 + i] - nums[i]) re...
Solution
python
pyinstaller__pyinstaller
PyInstaller/utils/win32/versioninfo.py
{ "start": 15602, "end": 17182 }
class ____: """ WORD wLength; // length of the version resource WORD wValueLength; // length of the Value member in the current // VS_VERSION_INFO structure WORD wType; // 1 means text, 0 means binary WCHAR szKey[]; // Contains the Unicode string...
VarFileInfo
python
allegroai__clearml
clearml/backend_api/services/v2_20/projects.py
{ "start": 18549, "end": 31810 }
class ____(NonStrictDataModel): """ :param id: Project id :type id: str :param name: Project name :type name: str :param basename: Project base name :type basename: str :param description: Project description :type description: str :param user: Associated user id :type user: ...
ProjectsGetAllResponseSingle
python
django__django
tests/check_framework/test_templates.py
{ "start": 530, "end": 945 }
class ____(SimpleTestCase): @override_settings( TEMPLATES=[ {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_1"}, {"BACKEND": f"{__name__}.{ErrorEngine.__qualname__}", "NAME": "backend_2"}, ] ) def test_errors_aggregated(self): errors = c...
CheckTemplatesTests
python
huggingface__transformers
tests/models/poolformer/test_modeling_poolformer.py
{ "start": 1341, "end": 1632 }
class ____(ConfigTester): def create_and_test_config_common_properties(self): config = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(config, "hidden_sizes")) self.parent.assertTrue(hasattr(config, "num_encoder_blocks"))
PoolFormerConfigTester
python
openai__openai-python
src/openai/types/chat/chat_completion_chunk.py
{ "start": 3503, "end": 6006 }
class ____(BaseModel): id: str """A unique identifier for the chat completion. Each chunk has the same ID.""" choices: List[Choice] """A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the last chunk if you set `stream_options...
ChatCompletionChunk
python
pytorch__pytorch
torch/_export/db/examples/cond_branch_class_method.py
{ "start": 95, "end": 231 }
class ____(torch.nn.Module): def foo(self, x): return x.cos() def forward(self, x): return self.foo(x)
MySubModule
python
patrick-kidger__equinox
equinox/_make_jaxpr.py
{ "start": 506, "end": 2599 }
class ____(Module): fn: Callable @property def __wrapped__(self): return self.fn def __call__(self, *args, **kwargs): dynamic, static = partition((args, kwargs), _is_struct) dynamic_flat, dynamic_treedef = jtu.tree_flatten(dynamic) def _fn(*_dynamic_flat): ...
_MakeJaxpr
python
mlflow__mlflow
mlflow/store/model_registry/file_store.py
{ "start": 3596, "end": 45173 }
class ____(AbstractStore): MODELS_FOLDER_NAME = "models" META_DATA_FILE_NAME = "meta.yaml" TAGS_FOLDER_NAME = "tags" MODEL_VERSION_TAGS_FOLDER_NAME = "tags" CREATE_MODEL_VERSION_RETRIES = 3 REGISTERED_MODELS_ALIASES_FOLDER_NAME = "aliases" def __init__(self, root_directory=None): ""...
FileStore
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_variables.py
{ "start": 8114, "end": 12105 }
class ____(TestVariableEndpoint): @pytest.mark.enable_redact @pytest.mark.parametrize( ("query_params", "expected_total_entries", "expected_keys"), [ # Filters ( {}, 5, [ TEST_VARIABLE_KEY, ...
TestGetVariables
python
kamyu104__LeetCode-Solutions
Python/smallest-subarray-to-sort-in-every-sliding-window.py
{ "start": 56, "end": 1200 }
class ____(object): def minSubarraySort(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ def count(nums): nxt, stk = [n]*n, [] for i in reversed(xrange(n)): while not (not stk or nums[stk[-1]] >= nums...
Solution
python
readthedocs__readthedocs.org
readthedocs/oauth/models.py
{ "start": 2208, "end": 2337 }
class ____(models.TextChoices): USER = "User", _("User") ORGANIZATION = "Organization", _("Organization")
GitHubAccountType
python
pytorch__pytorch
torch/_inductor/codegen/cpp_wrapper_cpu.py
{ "start": 1467, "end": 1585 }
class ____(Protocol): def writeline(self, line: Union[LineContext, DeferredLineBase, str]) -> None: ...
HasWriteLine
python
pytorch__pytorch
torch/_dynamo/pgo.py
{ "start": 8172, "end": 25771 }
class ____: scalar: Union[int, AutoDynamic, AutoUnset] = dataclasses.field(default=auto_unset) # NB: We don't have cases where we have a known dimensionality but # we know NOTHING about the individual sizes size: Union[AutoDynamic, AutoUnset, tuple[Union[int, AutoDynamic], ...]] = ( dataclasses....
FrameStateSizeEntry
python
pytorch__pytorch
torch/_inductor/codegen/rocm/ck_template.py
{ "start": 269, "end": 3695 }
class ____(ROCmTemplate): """ Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic """ _TORCH_DTYPE_TO_CK = { torch.float32: "F32", torch.float64: "F64", torch.float16: "F16", torch.bfloat16: "BF16", torch.int32: "I32"...
CKTemplate
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/asset/decorators.py
{ "start": 5389, "end": 6756 }
class ____(BaseAsset): """ Representation from decorating a function with ``@asset.multi``. This is implemented as an "asset-like" object that can be used in all places that accept asset-ish things (e.g. normal assets, aliases, AssetAll, AssetAny). :meta private: """ name: str _fu...
MultiAssetDefinition
python
getsentry__sentry
tests/sentry/issues/endpoints/test_project_performance_issue_settings.py
{ "start": 509, "end": 18775 }
class ____(APITestCase): endpoint = "sentry-api-0-project-performance-issue-settings" def setUp(self) -> None: super().setUp() self.login_as(user=self.user, superuser=True) self.project = self.create_project() @patch("sentry.models.ProjectOption.objects.get_value") @with_featur...
ProjectPerformanceIssueSettingsTest
python
walkccc__LeetCode
solutions/2647. Color the Triangle Red/2647.py
{ "start": 0, "end": 760 }
class ____: def colorRed(self, n: int) -> list[list[int]]: ans = [] tipSize = n % 4 # The tip of the triangle is always painted red. if tipSize >= 1: ans.append([1, 1]) # Pamost right and most left elements at the following rows. for i in range(2, tipSize + 1): ans.append([i, 1])...
Solution
python
kamyu104__LeetCode-Solutions
Python/insert-delete-getrandom-o1-duplicates-allowed.py
{ "start": 93, "end": 1454 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.__list = [] self.__used = defaultdict(list) def insert(self, val): """ Inserts a value to the collection. Returns true if the collection did not already contain th...
RandomizedCollection
python
bokeh__bokeh
tests/unit/bokeh/embed/test_bundle.py
{ "start": 7093, "end": 8048 }
class ____: def test_without_gl(self) -> None: assert beb._use_gl(beb._all_objs([plot()])) is False assert beb._use_gl(beb._all_objs([plot(), table()])) is False assert beb._use_gl(beb._all_objs([plot(), widget()])) is False d = Document() d.add_root(plot()) d.add_roo...
Test__use_gl
python
falconry__falcon
tests/_inspect_fixture.py
{ "start": 846, "end": 957 }
class ____: async def on_post_id(self, *args): pass def sinkFn(*args): pass
OtherResponderAsync
python
ray-project__ray
python/ray/serve/tests/test_model_composition.py
{ "start": 322, "end": 442 }
class ____: def __init__(self): pass def hello(self): return "hello" @serve.deployment
ClassHello
python
huggingface__transformers
tests/models/gpt_bigcode/test_modeling_gpt_bigcode.py
{ "start": 20366, "end": 23010 }
class ____(unittest.TestCase): def test_generate_simple(self): model = GPTBigCodeForCausalLM.from_pretrained("bigcode/gpt_bigcode-santacoder").to(torch_device) tokenizer = GPT2TokenizerFast.from_pretrained("bigcode/gpt_bigcode-santacoder") input_ids = tokenizer("def print_hello_world():", r...
GPTBigCodeModelLanguageGenerationTest
python
pytorch__pytorch
test/jit/test_dataclasses.py
{ "start": 1501, "end": 4644 }
class ____(JitTestCase): @classmethod def tearDownClass(cls): torch._C._jit_clear_class_registry() def test_init_vars(self): @torch.jit.script @dataclass(order=True) class Point2: x: float y: float norm_p: InitVar[int] = 2 norm...
TestDataclasses
python
tensorflow__tensorflow
tensorflow/python/distribute/multi_process_runner.py
{ "start": 31577, "end": 36450 }
class ____(object): """Represents a callable to run in a subprocess.""" @contextlib.contextmanager def _runtime_mode(self, executing_eagerly): if executing_eagerly: with context.eager_mode(): yield else: with context.graph_mode(): yield def _message_checking_func(self, task...
_ProcFunc
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_int.py
{ "start": 3494, "end": 26701 }
class ____(__TestCase): def test_basic(self): self.assertEqual(int(314), 314) self.assertEqual(int(3.14), 3) # Check that conversion from float truncates towards zero self.assertEqual(int(-3.14), -3) self.assertEqual(int(3.9), 3) self.assertEqual(int(-3.9), -3) ...
IntTestCases
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/comments.py
{ "start": 36296, "end": 36373 }
class ____(CommentedMap): __slots__ = (Comment.attrib,)
CommentedOrderedMap
python
tiangolo__fastapi
fastapi/_compat/v1.py
{ "start": 5280, "end": 10325 }
class ____(Exception): pass RequestErrorModel: Type[BaseModel] = create_model("Request") def with_info_plain_validator_function( function: Callable[..., Any], *, ref: Union[str, None] = None, metadata: Any = None, serialization: Any = None, ) -> Any: return {} def get_model_definitions...
PydanticSchemaGenerationError
python
huggingface__transformers
src/transformers/models/mobilevit/image_processing_mobilevit.py
{ "start": 2256, "end": 23941 }
class ____(BaseImageProcessor): r""" Constructs a MobileViT image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `pre...
MobileViTImageProcessor
python
huggingface__transformers
src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
{ "start": 23429, "end": 26484 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = UniSpeechSatPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_d...
UniSpeechSatEncoderStableLayerNorm
python
kamyu104__LeetCode-Solutions
Python/min-stack.py
{ "start": 792, "end": 1659 }
class ____(object): def __init__(self): self.stack, self.minStack = [], [] # @param x, an integer # @return an integer def push(self, x): self.stack.append(x) if len(self.minStack): if x < self.minStack[-1][0]: self.minStack.append([x, 1]) ...
MinStack2
python
coleifer__peewee
tests/libs/mock.py
{ "start": 60628, "end": 61447 }
class ____(MagicMixin, Mock): """ MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself. If you use the `spec` or `spec_set` arguments then *only* magic methods that exist in the sp...
MagicMock
python
weaviate__weaviate-python-client
weaviate/collections/collection/base.py
{ "start": 203, "end": 1031 }
class ____(Generic[ConnectionType]): def __init__( self, connection: ConnectionType, name: str, validate_arguments: bool, consistency_level: Optional[ConsistencyLevel] = None, tenant: Optional[str] = None, ) -> None: self._connection = connection s...
_CollectionBase
python
sympy__sympy
sympy/matrices/matrices.py
{ "start": 20180, "end": 23536 }
class ____(MatrixCommon): """A class to house deprecated matrix methods.""" def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): return self.charpoly(x=x) def berkowitz_det(self): """Computes determinant using Berkowitz method. See Also ======== det...
MatrixDeprecated
python
getsentry__sentry
src/sentry/integrations/web/vercel_extension_configuration.py
{ "start": 164, "end": 304 }
class ____(IntegrationExtensionConfigurationView): provider = "vercel" external_provider_key = "vercel"
VercelExtensionConfigurationView
python
pytorch__pytorch
torch/_inductor/analysis/profile_analysis.py
{ "start": 24523, "end": 27570 }
class ____(RuntimeError): pass def main() -> None: """ Main function for the profile analysis script. """ import argparse parser = argparse.ArgumentParser() parser.add_argument( "--diff", nargs=5, metavar=( "input_file1", "name1", ...
ParseException
python
django__django
django/forms/fields.py
{ "start": 18038, "end": 18219 }
class ____: def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS")
DateTimeFormatsIterator
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 157169, "end": 158397 }
class ____(Operation): def __init__(self, nan=0.0, posinf=None, neginf=None, *, name=None): super().__init__(name=name) self.nan = nan self.posinf = posinf self.neginf = neginf def call(self, x): return backend.numpy.nan_to_num( x, nan=self.nan, posinf=self.p...
NanToNum
python
getsentry__sentry
src/sentry/api/endpoints/organization_onboarding_tasks.py
{ "start": 604, "end": 744 }
class ____(OrganizationPermission): scope_map = {"POST": ["org:read"], "GET": ["org:read"]} @region_silo_endpoint
OnboardingTaskPermission
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/slots2.py
{ "start": 423, "end": 490 }
class ____(Slots1): __slots__ = () aaa = 4 @dataclass
Slots2
python
pytorch__pytorch
torch/ao/quantization/backend_config/backend_config.py
{ "start": 2146, "end": 3838 }
class ____: """ Config for specifying additional constraints for a given dtype, such as quantization value ranges, scale value ranges, and fixed quantization params, to be used in :class:`~torch.ao.quantization.backend_config.DTypeConfig`. The constraints currently supported are: * `quant_min_...
DTypeWithConstraints
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/errors.py
{ "start": 5377, "end": 5478 }
class ____(InvalidRequestFatalError): description = 'Missing redirect URI.'
MissingRedirectURIError
python
apache__airflow
helm-tests/tests/helm_tests/other/test_hpa.py
{ "start": 914, "end": 4510 }
class ____: """Tests HPA.""" def test_hpa_disabled_by_default(self): """Disabled by default.""" docs = render_chart( values={}, show_only=["templates/workers/worker-hpa.yaml"], ) assert docs == [] @pytest.mark.parametrize( ("executor", "is_cr...
TestHPA
python
kamyu104__LeetCode-Solutions
Python/number-of-unique-xor-triplets-i.py
{ "start": 57, "end": 268 }
class ____(object): def uniqueXorTriplets(self, nums): """ :type nums: List[int] :rtype: int """ return 1<<len(nums).bit_length() if len(nums) >= 3 else len(nums)
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/config.py
{ "start": 567, "end": 809 }
class ____(enum.Enum): """When to terminate instances.""" ALWAYS = enum.auto() NEVER = enum.auto() SUCCESS = enum.auto() def __str__(self): return self.name.lower() @dataclasses.dataclass(frozen=True)
TerminateMode
python
huggingface__transformers
src/transformers/models/bros/processing_bros.py
{ "start": 1129, "end": 1844 }
class ____(ProcessorMixin): r""" Constructs a Bros processor which wraps a BERT tokenizer. [`BrosProcessor`] offers all the functionalities of [`BertTokenizerFast`]. See the docstring of [`~BrosProcessor.__call__`] and [`~BrosProcessor.decode`] for more information. Args: tokenizer (`BertT...
BrosProcessor
python
vyperlang__vyper
vyper/venom/check_venom.py
{ "start": 284, "end": 547 }
class ____(VenomError): message: str = "basic block does not terminate" def __init__(self, basicblock): self.basicblock = basicblock def __str__(self): return f"basic block is not terminated:\n{self.basicblock}"
BasicBlockNotTerminated
python
doocs__leetcode
solution/0200-0299/0294.Flip Game II/Solution2.py
{ "start": 0, "end": 695 }
class ____: def canWin(self, currentState: str) -> bool: def win(i): if sg[i] != -1: return sg[i] vis = [False] * n for j in range(i - 1): vis[win(j) ^ win(i - j - 2)] = True for j in range(n): if not vis[j]: ...
Solution
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_washington_dc_zip.py
{ "start": 717, "end": 1713 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_dc_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls...
ColumnValuesToBeValidWashingtonDCZip
python
sphinx-doc__sphinx
sphinx/builders/html/_assets.py
{ "start": 1767, "end": 4141 }
class ____: filename: str | os.PathLike[str] priority: int attributes: dict[str, str] def __init__( self, filename: str | os.PathLike[str], /, *, priority: int = 500, **attributes: str, ) -> None: object.__setattr__(self, 'filename', filename)...
_JavaScript
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 42224, "end": 42327 }
class ____(GroupByCumulative): chunk = M.cumprod aggregate = M.mul initial = 1
GroupByCumprod
python
google__jax
jax/experimental/mosaic/gpu/launch_context.py
{ "start": 15376, "end": 15490 }
class ____(enum.Enum): TMA = enum.auto() CP_ASYNC = enum.auto() @dataclasses.dataclass()
AsyncCopyImplementation
python
getsentry__sentry
tests/sentry/integrations/slack/test_message_builder.py
{ "start": 9316, "end": 43380 }
class ____(TestCase, PerformanceIssueTestCase, OccurrenceTestMixin): def test_build_group_block(self) -> None: release = self.create_release(project=self.project) event = self.store_event( data={ "event_id": "a" * 32, "tags": {"escape": "`room`", "foo": "b...
BuildGroupAttachmentTest
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_alertrule_workflow.py
{ "start": 1383, "end": 3595 }
class ____(OrganizationAlertRuleWorkflowAPITestCase): def test_get_with_workflow_id_filter(self) -> None: response = self.get_success_response( self.organization.slug, workflow_id=str(self.workflow_1.id) ) assert response.data == serialize(self.alert_rule_workflow_1, self.user) ...
OrganizationAlertRuleWorkflowIndexGetTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 13372, "end": 13579 }
class ____(graphene.InputObjectType): output_name = graphene.NonNull(graphene.String) key = graphene.NonNull(graphene.String) class Meta: name = "MarshalledOutput"
GrapheneMarshalledOutput
python
dagster-io__dagster
python_modules/libraries/dagster-tableau/dagster_tableau/resources.py
{ "start": 36131, "end": 36799 }
class ____(BaseTableauWorkspace): """Represents a workspace in Tableau Cloud and provides utilities to interact with Tableau APIs. """ pod_name: str = Field(..., description="The pod name of the Tableau Cloud workspace.") def build_client(self) -> None: self._client = TableauCloudClient( ...
TableauCloudWorkspace
python
PyCQA__pylint
tests/functional/i/invalid/invalid_bool_returned.py
{ "start": 843, "end": 1011 }
class ____: """ __bool__ returns node which does not have 'value' in AST """ def __bool__(self): # [invalid-bool-returned] return lambda: 3
ThirdBadBool
python
pandas-dev__pandas
pandas/core/computation/pytables.py
{ "start": 8975, "end": 10881 }
class ____(BinOp): filter: tuple[Any, Any, Index] | None = None def __repr__(self) -> str: if self.filter is None: return "Filter: Not Initialized" return pprint_thing(f"[Filter : [{self.filter[0]}] -> [{self.filter[1]}]") def invert(self) -> Self: """invert the filter"...
FilterBinOp
python
fastapi__sqlmodel
sqlmodel/_compat.py
{ "start": 946, "end": 1094 }
class ____: max_length: Optional[int] = None max_digits: Optional[int] = None decimal_places: Optional[int] = None @dataclass
FakeMetadata
python
sympy__sympy
sympy/printing/pytorch.py
{ "start": 382, "end": 10628 }
class ____(ArrayPrinter, AbstractPythonCodePrinter): printmethod = "_torchcode" mapping = { sympy.Abs: "torch.abs", sympy.sign: "torch.sign", # XXX May raise error for ints. sympy.ceiling: "torch.ceil", sympy.floor: "torch.floor", sympy.log: "torch.log", ...
TorchPrinter
python
sqlalchemy__sqlalchemy
test/orm/test_unitofwork.py
{ "start": 84098, "end": 86420 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "items", metadata, Column( "item_id", Integer, primary_key=True, test_needs_autoincrement=True, ), ...
SaveTest3
python
ray-project__ray
python/ray/train/_internal/state/state_manager.py
{ "start": 440, "end": 4323 }
class ____: """A class that aggregates and reports train run info to TrainStateActor. This manager class is created on the train controller layer for each run. """ def __init__(self, state_actor) -> None: self.state_actor = state_actor self.train_run_info_dict = defaultdict(dict) ...
TrainRunStateManager
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 420118, "end": 422228 }
class ____(Response): """ Response of tasks.validate endpoint. """ _service = "tasks" _action = "validate" _version = "2.13" _schema = {"additionalProperties": False, "definitions": {}, "type": "object"} response_mapping = { GetByIdRequest: GetByIdResponse, GetAllRequest: GetAllR...
ValidateResponse
python
huggingface__transformers
src/transformers/models/zamba2/modular_zamba2.py
{ "start": 44522, "end": 45724 }
class ____(PreTrainedModel): config: Zamba2Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Zamba2AttentionDecoderLayer", "Zamba2MambaDecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_flex_attn ...
Zamba2PreTrainedModel
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 31791, "end": 32677 }
class ____(SetitemCastingEquivalents): # timedelta64 should not be treated as integers when setting into # numeric Series @pytest.fixture def val(self): td = np.timedelta64(4, "ns") return td # TODO: could also try np.full((1,), td) @pytest.fixture(params=[complex, int, fl...
TestSetitemTimedelta64IntoNumeric
python
kamyu104__LeetCode-Solutions
Python/number-of-subsequences-with-odd-sum.py
{ "start": 377, "end": 675 }
class ____(object): def subsequenceCount(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 dp = [0]*2 for x in nums: dp = [(dp[i]+dp[i^(x%2)]+int(x%2 == i))%MOD for i in xrange(2)] return dp[1]
Solution2
python
astropy__astropy
astropy/time/core.py
{ "start": 4619, "end": 6008 }
class ____(enum.Enum): NOT_STARTED = 0 # No thread has reached the check RUNNING = 1 # A thread is running update_leap_seconds (_LEAP_SECONDS_LOCK is held) DONE = 2 # update_leap_seconds has completed _LEAP_SECONDS_CHECK = _LeapSecondsCheck.NOT_STARTED _LEAP_SECONDS_LOCK = threading.RLock() def _comp...
_LeapSecondsCheck
python
tensorflow__tensorflow
tensorflow/python/ops/sort_ops_test.py
{ "start": 1214, "end": 7192 }
class ____(test.TestCase): def random_array(self, shape, dtype): if np.issubdtype(dtype, np.integer): imin = np.iinfo(dtype).min imax = np.iinfo(dtype).max return np.random.randint(imin, imax, shape, dtype) else: return np.random.random(shape).astype(dtype) def _test_sort(self, val...
SortTest
python
pennersr__django-allauth
allauth/socialaccount/providers/eventbrite/provider.py
{ "start": 709, "end": 2154 }
class ____(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = "eventbrite" name = "Eventbrite" account_class = EventbriteAccount oauth2_adapter_class = EventbriteOAuth2Adapter def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return s...
EventbriteProvider
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azureaisearch/llama_index/vector_stores/azureaisearch/base.py
{ "start": 57828, "end": 63547 }
class ____: def __init__( self, query: VectorStoreQuery, field_mapping: Dict[str, str], odata_filter: Optional[str], search_client: SearchClient, async_search_client: AsyncSearchClient, semantic_configuration_name: Optional[str] = None, **search_kwargs...
AzureQueryResultSearchBase
python
huggingface__transformers
src/transformers/models/sam/modeling_sam.py
{ "start": 23339, "end": 24395 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.scale = config.hidden_size // 2 self.register_buffer("positional_embedding", self.scale * torch.randn((2, config.num_pos_feats))) def forward(self, input_coords, input_shape=None): """Positionally encode ...
SamPositionalEmbedding
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 90748, "end": 91555 }
class ____(Affine2DBase): """ A transformation that translates by *xt* and *yt*, after *xt* and *yt* have been transformed by *scale_trans*. """ def __init__(self, xt, yt, scale_trans, **kwargs): super().__init__(**kwargs) self._t = (xt, yt) self._scale_trans = scale_trans ...
ScaledTranslation
python
readthedocs__readthedocs.org
readthedocs/projects/models.py
{ "start": 57351, "end": 57997 }
class ____(TimeStampedModel): """WebHook / Email notification attached to a Project.""" # TODO: Overridden from TimeStampedModel just to allow null values, # remove after deploy. created = CreationDateTimeField( _("created"), null=True, blank=True, ) modified = Modificat...
Notification
python
apache__airflow
helm-tests/tests/helm_tests/other/test_git_sync_worker.py
{ "start": 900, "end": 10062 }
class ____: """Test git sync worker.""" def test_should_add_dags_volume_to_the_worker_if_git_sync_and_persistence_is_enabled(self): docs = render_chart( values={ "executor": "CeleryExecutor", "dags": {"persistence": {"enabled": True}, "gitSync": {"enabled": T...
TestGitSyncWorker
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/dynamic_tests/test_dynamic_output.py
{ "start": 6346, "end": 8123 }
class ____(NamedTuple): x: int @dg.op(out={"items": dg.DynamicOut(), "refs": dg.Out()}) def spawn(): for i in range(10): yield dg.DynamicOutput(DangerNoodle(i), output_name="items", mapping_key=f"num_{i}") gc.collect() yield dg.Output(len(objgraph.by_type("DangerNoodle")), output_name="refs")...
DangerNoodle
python
PyCQA__pylint
tests/functional/a/alternative/alternative_union_syntax_error.py
{ "start": 3758, "end": 3814 }
class ____(ForwardMetaclass): pass
SecondLevelMetaclass
python
dask__distributed
distributed/tests/test_collections.py
{ "start": 8414, "end": 9214 }
class ____(Mapping): def __init__(self, d: Mapping): self.d = d def __getitem__(self, item): return self.d[item] def __iter__(self): return iter(self.d) def __len__(self): return len(self.d) def test_sum_mappings(): a = {"x": 1, "y": 1.2, "z": [3, 4]} b = Rea...
ReadOnlyMapping
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_multi_hierarchy_base.py
{ "start": 2898, "end": 3876 }
class ____(BaseB, BaseY): """ Combines both hierarchies with parameter, config, and step override. Overrides the process step from BaseY. """ param_c = Parameter("param_c", help="Parameter C", default=5) config_c = Config("config_c", default_value={"merge": True, "offset": 200}) @step ...
BaseC
python
django__django
tests/template_tests/syntax_tests/test_cache.py
{ "start": 5649, "end": 7492 }
class ____(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(libraries={"cache": "django.templatetags.cache"}) super().setUpClass() def test_cache_regression_20130(self): t = self.engine.from_string( "{% load cache %}{% cache 1 regression_20130 %}foo...
CacheTests
python
PrefectHQ__prefect
tests/utilities/schema_tools/test_validation.py
{ "start": 65090, "end": 71442 }
class ____: # We should always be conforming to PydanticV2 and there should # be no unintended changes here. def test_pydantic_v2_single_type_tuple(self): """ single_type_tuple: tuple[str] """ schema = { "title": "Parameters", "type": "object", ...
TestPreprocessSchemaPydanticV2Tuples
python
huggingface__transformers
src/transformers/models/gpt_neo/modeling_gpt_neo.py
{ "start": 37958, "end": 41507 }
class ____(GPTNeoPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = GPTNeoModel(config) self.dropout = nn.Dropout(config.classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_...
GPTNeoForTokenClassification
python
doocs__leetcode
solution/2200-2299/2268.Minimum Number of Keypresses/Solution.py
{ "start": 0, "end": 275 }
class ____: def minimumKeypresses(self, s: str) -> int: cnt = Counter(s) ans, k = 0, 1 for i, x in enumerate(sorted(cnt.values(), reverse=True), 1): ans += k * x if i % 9 == 0: k += 1 return ans
Solution
python
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 13513, "end": 13678 }
class ____(SnubaError): """ Exception raised when the Snuba API server returns an unexpected response type (e.g. not JSON.) """
UnexpectedResponseError
python
getsentry__sentry
tests/sentry/uptime/subscriptions/test_subscriptions.py
{ "start": 7033, "end": 7734 }
class ____(UptimeTestCase): def test_with_task(self) -> None: with self.tasks(): uptime_sub = create_uptime_subscription("https://sentry.io", 3600, 1000) with self.tasks(): delete_uptime_subscription(uptime_sub) with pytest.raises(UptimeSubscription.DoesNotExist): ...
DeleteUptimeSubscriptionTest
python
ipython__ipython
IPython/lib/pretty.py
{ "start": 15057, "end": 15389 }
class ____(Printable): def __init__(self): self.objs = [] self.width = 0 def output(self, stream, output_width): for obj in self.objs: stream.write(obj) return output_width + self.width def add(self, obj, width): self.objs.append(obj) self.width...
Text
python
dagster-io__dagster
python_modules/libraries/dagster-databricks/dagster_databricks/resources.py
{ "start": 1145, "end": 4671 }
class ____(ConfigurableResource, IAttachDifferentObjectToOpContext): """Resource which provides a Python client for interacting with Databricks within an op or asset. """ host: Optional[str] = Field( description="Databricks host, e.g. https://uksouth.azuredatabricks.com", default=None ) ...
DatabricksClientResource
python
PyCQA__pylint
doc/data/messages/n/non-parent-init-called/bad.py
{ "start": 77, "end": 190 }
class ____(Animal): def __init__(self): super().__init__() self.has_vertebrae = True
Vertebrate
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/prefect_kubernetes/exceptions.py
{ "start": 281, "end": 389 }
class ____(OpenApiException): """An exception for when a Kubernetes job fails."""
KubernetesJobFailedError
python
modin-project__modin
modin/core/dataframe/pandas/interchange/dataframe_protocol/column.py
{ "start": 2261, "end": 18246 }
class ____(ProtocolColumn): """ A column object, with only the methods and properties required by the interchange protocol defined. A column can contain one or more chunks. Each chunk can contain up to three buffers - a data buffer, a mask buffer (depending on null representation), and an offsets b...
PandasProtocolColumn
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_visual.py
{ "start": 4309, "end": 5955 }
class ____: def test_valid(self) -> None: prop = bcpv.FontSize() for unit in css_units.split("|"): v = f"10{unit}" assert prop.is_valid(v) v = f"10.2{unit}" assert prop.is_valid(v) for unit in css_units.upper().split("|"): v = f"...
Test_FontSize
python
ray-project__ray
python/ray/tests/test_ray_init.py
{ "start": 5258, "end": 11958 }
class ____(Exception): def __init__(self, credentials): self.credentials = credentials def test_ray_init_credentials_with_client(monkeypatch): def mock_init( self, conn_str="", secure=False, metadata=None, connection_retries=3, _credentials=None, ): ...
Stop
python
getsentry__sentry
src/sentry/integrations/jira/integration.py
{ "start": 47020, "end": 49073 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.JIRA.value name = "Jira" metadata = metadata integration_cls = JiraIntegration # Jira is region-restricted because the JiraSentryIssueDetailsView view does not currently # contain organization-identifying information aside from the ...
JiraIntegrationProvider
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 9529, "end": 9712 }
class ____(AlertBase): def __init__(self, proto: AlertProto, root: ElementTree) -> None: super().__init__(proto, root) self.type = "info" @dataclass(repr=False)
Info
python
ray-project__ray
rllib/evaluation/env_runner_v2.py
{ "start": 7313, "end": 51737 }
class ____: """Collect experiences from user environment using Connectors.""" def __init__( self, worker: "RolloutWorker", base_env: BaseEnv, multiple_episodes_in_batch: bool, callbacks: "RLlibCallback", perf_stats: _PerfStats, rollout_fragment_length: in...
EnvRunnerV2
python
cherrypy__cherrypy
cherrypy/lib/reprconf.py
{ "start": 860, "end": 3935 }
class ____(dict): """A dict of config namespace names and handlers. Each config entry should begin with a namespace name; the corresponding namespace handler will be called once for each config entry in that namespace, and will be passed two arguments: the config key (with the namespace removed) an...
NamespaceSet
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 7544, "end": 8057 }
class ____(sgqlc.types.Enum): """The status of a git comparison between two refs. Enumeration Choices: * `AHEAD`: The head ref is ahead of the base ref. * `BEHIND`: The head ref is behind the base ref. * `DIVERGED`: The head ref is both ahead and behind of the base ref, indicating git histor...
ComparisonStatus
python
run-llama__llama_index
llama-index-core/tests/memory/blocks/test_fact.py
{ "start": 368, "end": 5626 }
class ____(MockLLM): """Test-specific subclass of MockLLM with mocked achat method.""" def __init__(self, *args, responses: List[ChatResponse], **kwargs): super().__init__(*args, **kwargs) self._responses = responses self._index = 0 async def achat(self, messages: List[ChatMessage]...
MyMockLLM
python
pytorch__pytorch
torch/_numpy/testing/utils.py
{ "start": 59571, "end": 77296 }
class ____: """ Context manager and decorator doing much the same as ``warnings.catch_warnings``. However, it also provides a filter mechanism to work around https://bugs.python.org/issue4180. This bug causes Python before 3.4 to not reliably show warnings again after they have been ignore...
suppress_warnings