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
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/cursor_shapes.py
{ "start": 2935, "end": 3721 }
class ____(CursorShapeConfig): def __init__( self, get_cursor_shape_config: Callable[[], AnyCursorShapeConfig] ) -> None: self.get_cursor_shape_config = get_cursor_shape_config def get_cursor_shape(self, application: Application[Any]) -> CursorShape: return to_cursor_shape_config(se...
DynamicCursorShapeConfig
python
sqlalchemy__sqlalchemy
test/orm/test_utils.py
{ "start": 1332, "end": 5124 }
class ____(fixtures.TestBase): """ Test for #7305 """ @testing.fixture def plain_fixture(cls, decl_base): class Foo(decl_base): __tablename__ = "foo" id = Column(Integer, primary_key=True) decl_base.metadata.create_all(testing.db) return Foo @t...
ContextualWarningsTest
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 19506, "end": 20172 }
class ____(TestCase): @staticmethod def application(env, start_response): assert "test.submit" in env["CONTENT_TYPE"] start_response('200 OK', [('Content-Type', 'text/plain')]) return [b"ok"] def test_multiline_116(self): """issue #116""" request = '\r\n'.join(( ...
TestMultiLineHeader
python
ipython__ipython
IPython/core/ultratb.py
{ "start": 42457, "end": 44622 }
class ____(FormattedTB): """A traceback printer which can be called on the fly. It will find out about exceptions by itself. A brief example:: AutoTB = AutoFormattedTB(mode = 'Verbose', theme_name='linux') try: ... except: AutoTB() # or AutoTB(out=logfile) whe...
AutoFormattedTB
python
pytorch__pytorch
torch/_functorch/_aot_autograd/schemas.py
{ "start": 45313, "end": 48295 }
class ____: """ AOTAutograd needs to do many transformations to the calling convention of the user function it is tracing, e.g., deduplicating inputs, unpacking subclasses, etc. CompilerWrapper lets us factor these into compositional stages so we can handle each transformation incrementally instead...
CompilerWrapper
python
getsentry__sentry
src/sentry/hybridcloud/rpc/service.py
{ "start": 15902, "end": 17724 }
class ____(RpcException): """Indicate that the response from a remote RPC service violated expectations.""" def _look_up_service_method( service_name: str, method_name: str ) -> tuple[DelegatingRpcService, Callable[..., Any]]: try: service = _global_service_registry[service_name] except KeyErr...
RpcResponseException
python
wandb__wandb
wandb/sdk/data_types/saved_model.py
{ "start": 13616, "end": 14401 }
class ____(_PicklingSavedModel["torch.nn.Module"]): _log_type = "pytorch-model-file" _path_extension = "pt" @staticmethod def _deserialize(dir_or_file_path: str) -> torch.nn.Module: return _get_torch().load(dir_or_file_path, weights_only=False) @staticmethod def _validate_obj(obj: Any)...
_PytorchSavedModel
python
pandas-dev__pandas
pandas/core/internals/ops.py
{ "start": 423, "end": 5145 }
class ____(NamedTuple): lvals: ArrayLike rvals: ArrayLike locs: BlockPlacement left_ea: bool right_ea: bool rblk: Block def _iter_block_pairs( left: BlockManager, right: BlockManager ) -> Iterator[BlockPairInfo]: # At this point we have already checked the parent DataFrames for # ...
BlockPairInfo
python
doocs__leetcode
solution/0300-0399/0324.Wiggle Sort II/Solution.py
{ "start": 0, "end": 420 }
class ____: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ arr = sorted(nums) n = len(arr) i, j = (n - 1) >> 1, n - 1 for k in range(n): if k % 2 == 0: nums[k] = arr[i] ...
Solution
python
walkccc__LeetCode
solutions/744. Find Smallest Letter Greater Than Target/744.py
{ "start": 0, "end": 236 }
class ____: def nextGreatestLetter(self, letters: list[str], target: str) -> str: l = bisect.bisect_right(range(len(letters)), target, key=lambda m: letters[m]) return letters[l % len(letters)]
Solution
python
django__django
django/utils/feedgenerator.py
{ "start": 11007, "end": 11341 }
class ____(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"])
RssUserland091Feed
python
run-llama__llama_index
llama-index-core/tests/agent/utils/test_agent_utils.py
{ "start": 574, "end": 634 }
class ____(BaseModel): hello: str world: int
Structure
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 44076, "end": 44145 }
class ____(_ImportStmt): __slots__ = ("level", "module")
ImportFrom
python
google__jax
tests/mosaic/gpu_test_multidevice.py
{ "start": 1943, "end": 2594 }
class ____(TestCase): def test_multigpu(self): if len(jax.devices()) < 2: self.skipTest("Need at least 2 devices") def kernel(ctx, src, dst, _): mgpu.FragmentedArray.load_strided(src).store_untiled(dst) x = np.arange(64 * 64, dtype=jnp.float32).reshape(64, 64) f = jax.jit(mgpu.as_gpu_kern...
ProfilerTest
python
getsentry__sentry
src/sentry/api/bases/incident.py
{ "start": 896, "end": 1932 }
class ____(OrganizationEndpoint): def convert_args( self, request: Request, incident_identifier: str, *args: Any, **kwargs: Any, ) -> tuple[tuple[Any, ...], dict[str, Any]]: args, kwargs = super().convert_args(request, *args, **kwargs) organization = kwarg...
IncidentEndpoint
python
dagster-io__dagster
python_modules/dagster/dagster/_config/pythonic_config/config.py
{ "start": 6712, "end": 16624 }
class ____(MakeConfigCacheable, metaclass=BaseConfigMeta): """Base class for Dagster configuration models, used to specify config schema for ops and assets. Subclasses :py:class:`pydantic.BaseModel`. Example definition: .. code-block:: python from pydantic import Field class MyAssetC...
Config
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0004_add_project_container_image.py
{ "start": 100, "end": 580 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0003_project_cdn_enabled"), ] operations = [ migrations.AddField( model_name="project", name="container_image", field=models.CharField( max_len...
Migration
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 732841, "end": 733442 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "milestone_title", "subject") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(...
DemilestonedEvent
python
bokeh__bokeh
src/bokeh/models/plots.py
{ "start": 34383, "end": 35491 }
class ____(list): def __setattr__(self, attr, value): for x in self: setattr(x, attr, value) def __getattribute__(self, attr): if attr in dir(list): return list.__getattribute__(self, attr) if len(self) == 0: raise AttributeError(f"Trying to access {at...
_list_attr_splat
python
gevent__gevent
src/gevent/tests/test__core.py
{ "start": 4195, "end": 4359 }
class ____(LibevTestMixin, unittest.TestCase): kind = available_loops['libev-cffi'] @unittest.skipIf(not_available('libuv-cffi'), "Needs libuv-cffi")
TestLibevCffi
python
facebook__pyre-check
client/timer.py
{ "start": 345, "end": 3277 }
class ____: """ A simple utility class to facilitate clock duration computation. A ``Timer`` object tracks one single state: the timestamp at which the timer starts. It provides various ``stop`` methods which returns the duration from the moment of the stop method is invoked to the moment when the ...
Timer
python
Netflix__metaflow
test/test_config/config_simple.py
{ "start": 1738, "end": 2606 }
class ____(FlowSpec): trigger_param = Parameter( "trigger_param", default="", external_trigger=True, external_artifact=trigger_name_func, ) cfg = Config("cfg", default="config_simple.json") cfg_default_value = Config( "cfg_default_value", default_value=de...
ConfigSimple
python
ray-project__ray
rllib/utils/actor_manager.py
{ "start": 4674, "end": 6188 }
class ____: @DeveloperAPI def ping(self) -> str: """Ping the actor. Can be used as a health check. Returns: "pong" if actor is up and well. """ return "pong" @DeveloperAPI def apply( self, func: Callable[[Any, Optional[Any], Optional[Any]], T...
FaultAwareApply
python
readthedocs__readthedocs.org
readthedocs/core/migrations/0015_remove_email_options.py
{ "start": 121, "end": 880 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("core", "0014_optout_email_build_image_deprecation"), ] operations = [ migrations.RemoveField( model_name="historicaluserprofile", name="optout_email_build_image_deprecation", ...
Migration
python
django__django
tests/model_forms/tests.py
{ "start": 2847, "end": 2960 }
class ____(forms.ModelForm): class Meta: model = DerivedPost fields = "__all__"
DerivedPostForm
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 263959, "end": 264211 }
class ____(VegaLiteSchema): """ConditionalValueDefnumber schema wrapper.""" _schema = {"$ref": "#/definitions/ConditionalValueDef<number>"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ConditionalValueDefnumber
python
huggingface__transformers
src/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py
{ "start": 1326, "end": 2368 }
class ____(ModelOutput): """ Output type of [`Wav2Vec2DecoderWithLM`], with transcription. Args: text (list of `str` or `str`): Decoded logits in text from. Usually the speech transcription. logit_score (list of `float` or `float`): Total logit score of the beams ass...
Wav2Vec2DecoderWithLMOutput
python
huggingface__transformers
tests/models/seamless_m4t/test_modeling_seamless_m4t.py
{ "start": 1536, "end": 12920 }
class ____: def __init__( self, parent, input_modality="speech", batch_size=2, seq_length=4, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, hidden_act="gelu", hidden_dropout_prob=0.1, at...
SeamlessM4TModelTester
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 882546, "end": 891718 }
class ____(PolarDef): """ PositionDatumDefBase schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and a...
PositionDatumDefBase
python
spack__spack
lib/spack/spack/test/installer_build_graph.py
{ "start": 3725, "end": 22354 }
class ____: """Tests for the BuildGraph class.""" def test_basic_graph_construction(self, mock_specs: Dict[str, Spec], temporary_store: Store): """Test basic graph construction with all specs to be installed.""" graph = BuildGraph( specs=[mock_specs["root"]], root_policy...
TestBuildGraph
python
lazyprogrammer__machine_learning_examples
tf2.0/keras_trader.py
{ "start": 6632, "end": 11244 }
class ____(object): def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = ReplayBuffer(state_size, action_size, size=500) self.gamma = 0.95 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.01 self....
DQNAgent
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 187559, "end": 187650 }
class ____(_DateTimeRangeTests, _RangeTypeCompilation): pass
DateTimeRangeCompilationTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/subset_automation_condition.py
{ "start": 460, "end": 1420 }
class ____(BuiltinAutomationCondition[T_EntityKey]): """Base class for simple conditions which compute a simple subset of the asset graph.""" @property def requires_cursor(self) -> bool: return False @abstractmethod def compute_subset( self, context: AutomationContext[T_EntityKey] ...
SubsetAutomationCondition
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-mistralai/llama_index/embeddings/mistralai/base.py
{ "start": 402, "end": 3492 }
class ____(BaseEmbedding): """ Class for MistralAI embeddings. Args: model_name (str): Model for embedding. Defaults to "mistral-embed". api_key (Optional[str]): API key to access the model. Defaults to None. """ # Instance variables initialized via Pydantic's mechani...
MistralAIEmbedding
python
spyder-ide__spyder
spyder/plugins/plots/widgets/figurebrowser.py
{ "start": 45795, "end": 49995 }
class ____(QFrame, SpyderConfigurationAccessor): """ A basic widget on which can be painted a custom png, jpg, or svg image. """ sig_context_menu_requested = Signal(QPoint) """ This signal is emitted to request a context menu. Parameters ---------- point: QPoint The QPoint ...
FigureCanvas
python
PrefectHQ__prefect
src/integrations/prefect-dask/tests/test_utils.py
{ "start": 282, "end": 1807 }
class ____: def test_from_task(self): @task def test_task(): delayed_num = dask.delayed(42) with get_dask_client() as client: assert isinstance(client, Client) result = client.compute(delayed_num).result() return result @fl...
TestDaskSyncClient
python
ray-project__ray
rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py
{ "start": 258, "end": 3553 }
class ____(RLlibCallback): def __init__(self, win_rate_threshold): super().__init__() # 0=RandomPolicy, 1=1st main policy snapshot, # 2=2nd main policy snapshot, etc.. self.current_opponent = 0 self.win_rate_threshold = win_rate_threshold def on_train_result(self, *, al...
SelfPlayCallbackOldAPIStack
python
facelessuser__pymdown-extensions
pymdownx/blocks/block.py
{ "start": 5866, "end": 11814 }
class ____(metaclass=ABCMeta): """Block.""" # Set to something if argument should be split. # Arguments will be split and white space stripped. NAME = '' # Instance arguments and options ARGUMENT: bool | None = False OPTIONS: dict[str, tuple[Any, Callable[[Any], Any]]] = {} def __init...
Block
python
huggingface__transformers
tests/pipelines/test_pipelines_text_generation.py
{ "start": 1024, "end": 22536 }
class ____(unittest.TestCase): model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def test_small_model_pt(self): text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-random-LlamaForCausalLM", max_new_tokens=10, ) ...
TextGenerationPipelineTests
python
huggingface__transformers
examples/pytorch/language-modeling/run_plm.py
{ "start": 4218, "end": 23631 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. """ dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( ...
DataTrainingArguments
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/vector.py
{ "start": 6537, "end": 10963 }
class ____(types.TypeEngine): """Oracle VECTOR datatype. For complete background on using this type, see :ref:`oracle_vector_datatype`. .. versionadded:: 2.0.41 """ cache_ok = True operator_classes = OperatorClass.BASE | OperatorClass.MATH __visit_name__ = "VECTOR" _typecode_m...
VECTOR
python
huggingface__transformers
src/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py
{ "start": 8675, "end": 9328 }
class ____(nn.Module): def __init__(self, config: ASTConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.interme...
ASTIntermediate
python
google__pytype
pytype/abstract/_function_base.py
{ "start": 19299, "end": 29901 }
class ____(Function): """An abstract base class for functions represented by function.Signature. Subclasses should define call(self, node, f, args) and set self.bound_class. """ def __init__( self, signature: function.Signature, ctx: "context.Context" ) -> None: # We should only instantiate subcla...
SignedFunction
python
Textualize__textual
src/textual/binding.py
{ "start": 1188, "end": 1294 }
class ____(Exception): """Binding key is in an invalid format.""" @dataclass(frozen=True)
InvalidBinding
python
sympy__sympy
sympy/physics/quantum/gate.py
{ "start": 23926, "end": 24591 }
class ____(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Y' gate_name_latex = 'Y' def get_target_matrix(self, format='sympy'): retur...
YGate
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 4226, "end": 5158 }
class ____(nn.Module): def __init__(self, config: MllamaVisionConfig, is_gated: bool = True): super().__init__() self.max_num_tiles = config.max_num_tiles self.hidden_size = config.hidden_size self.max_aspect_ratio_id = config.max_aspect_ratio_id self.is_gated = is_gated ...
MllamaPrecomputedAspectRatioEmbedding
python
jazzband__django-model-utils
tests/models.py
{ "start": 4068, "end": 4292 }
class ____(models.Model): name = models.CharField(max_length=25) name_changed = MonitorField(monitor="name") name2 = models.CharField(max_length=25) name_changed2 = MonitorField(monitor="name2")
DoubleMonitored
python
sanic-org__sanic
sanic/exceptions.py
{ "start": 26373, "end": 26471 }
class ____(SanicException): """Exception raised when an invalid signal is sent."""
InvalidSignal
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 13372, "end": 16486 }
class ____: timeout: int node_id: Optional[str] = None node_ip: Optional[str] = None # One of {file, stream}. File means it will return the whole log. # stream means it will keep the connection and streaming the log. media_type: str = "file" # The filename to match when finding the log to do...
GetLogOptions
python
fluentpython__example-code-2e
14-inheritance/diamond2.py
{ "start": 1476, "end": 1614 }
class ____(U, A): # <4> def ping(self): print(f'{self}.ping() in LeafUA') super().ping() # end::DIAMOND_CLASSES[]
LeafUA
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 19661, "end": 20571 }
class ____(PrefectOperatorFilterBaseModel): """Filter for subflows of a given flow run""" any_: Optional[list[UUID]] = Field( default=None, description="A list of parent flow run ids to include" ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressio...
FlowRunFilterParentFlowRunId
python
chroma-core__chroma
chromadb/api/__init__.py
{ "start": 16717, "end": 18544 }
class ____(ABC): @abstractmethod def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: """Create a new database. Raises an error if the database already exists. Args: database: The name of the database to create. """ pass @abstractmethod ...
AdminAPI
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_ecs_executor.py
{ "start": 5676, "end": 10801 }
class ____: """Tests EcsTaskCollection Class.""" # You can't use a fixture in _setup_method unless you declare _setup_method to be a fixture itself. @pytest.fixture(autouse=True) def _setup_method(self, mock_airflow_key): # Create a new Collection and verify it is empty. self.collection...
TestEcsTaskCollection
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1134982, "end": 1136012 }
class ____(sgqlc.types.Type, Node): """Represents a 'disconnected' event on a given issue or pull request. """ __schema__ = github_schema __field_names__ = ("actor", "created_at", "is_cross_repository", "source", "subject") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifie...
DisconnectedEvent
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_grad_acc.py
{ "start": 1044, "end": 1838 }
class ____: """ This configures how gradients are accumulated in :meth:`_test_grad_acc`. Each instance of this class represents ``num_iters``-many consecutive iterations, where the ``no_sync()`` context manager is used or not as given by ``use_no_sync``. Attributes: use_no_sync (bool): ...
_GradAccConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/unit_tests/common.py
{ "start": 553, "end": 710 }
class ____: customer_id = "12345" query = None page_size = 100 page_token = None next_page_token = None # Mocking Classes
MockSearchRequest
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 54607, "end": 59699 }
class ____(QuantizationTestCase): """ Base QuantizationTestCase for PT2 with some helper methods. """ _MAP_TO_FX_TRACED_OPS = { torch.ops.quantized_decomposed.quantize_per_tensor: torch.ops.quantized_decomposed.quantize_per_tensor.default, torch.ops.quantized_decomposed.dequantize_per_t...
PT2EQuantizationTestCase
python
justquick__django-activity-stream
runtests/testapp/drf.py
{ "start": 222, "end": 346 }
class ____(serializers.ModelSerializer): class Meta: model = Group fields = ['id', 'name']
GroupSerializer
python
numpy__numpy
numpy/distutils/ccompiler_opt.py
{ "start": 81857, "end": 100395 }
class ____(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse): """ A helper class for `CCompiler` aims to provide extra build options to effectively control of compiler optimizations that are directly related to CPU features. """ def __init__(self, ccompiler, cpu_baseline="min", cpu_disp...
CCompilerOpt
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/dependency.py
{ "start": 3998, "end": 8774 }
class ____(ABC): """Node invocation within a graph. Identified by its name inside the graph.""" name: str definition: "NodeDefinition" graph_definition: "GraphDefinition" _additional_tags: Mapping[str, str] _hook_defs: AbstractSet[HookDefinition] _retry_policy: Optional[RetryPolicy] _in...
Node
python
ray-project__ray
python/ray/tests/test_basic_2.py
{ "start": 17044, "end": 21229 }
class ____: @ray.remote class B: def get(self): return "OK" if __name__ == "__main__": current_path = os.path.dirname(__file__) job_config = ray.job_config.JobConfig(code_search_path=[current_path]) ray.init({}, job_config=job_config) b = A.B.remote() print(ray.get(b.get...
A
python
PrefectHQ__prefect
src/integrations/prefect-dbt/tests/core/test_tracker.py
{ "start": 7705, "end": 8347 }
class ____: """Test task run ID management functionality.""" def test_task_run_id_set_and_get(self, sample_node_id, sample_task_run_id): """Test that set_task_run_id stores and get_task_run_id retrieves the task run ID.""" tracker = NodeTaskTracker() # Set task run ID tracker.s...
TestNodeTaskTrackerTaskRunIds
python
huggingface__transformers
src/transformers/models/univnet/configuration_univnet.py
{ "start": 769, "end": 6758 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`UnivNetModel`]. It is used to instantiate a UnivNet vocoder model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simil...
UnivNetConfig
python
django__django
tests/many_to_one_null/models.py
{ "start": 272, "end": 525 }
class ____(models.Model): headline = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, models.SET_NULL, null=True) class Meta: ordering = ("headline",) def __str__(self): return self.headline
Article
python
kamyu104__LeetCode-Solutions
Python/append-k-integers-with-minimal-sum.py
{ "start": 42, "end": 429 }
class ____(object): def minimalKSum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ result = k*(k+1)//2 curr = k+1 for x in sorted(set(nums)): if x < curr: result += curr-x curr += 1 ...
Solution
python
getsentry__sentry
tests/sentry/integrations/jira/test_integration.py
{ "start": 51885, "end": 57441 }
class ____(APITestCase): @cached_property def integration(self): integration = self.create_provider_integration( provider="jira", name="Jira Cloud", metadata={ "oauth_client_id": "oauth-client-id", "shared_secret": "a-super-secret-key-f...
JiraMigrationIntegrationTest
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/mapreduce.py
{ "start": 1408, "end": 4066 }
class ____(Chain): """Map-reduce chain.""" combine_documents_chain: BaseCombineDocumentsChain """Chain to use to combine documents.""" text_splitter: TextSplitter """Text splitter to use.""" input_key: str = "input_text" output_key: str = "output_text" @classmethod def from_params(...
MapReduceChain
python
falconry__falcon
falcon/_typing.py
{ "start": 5938, "end": 6123 }
class ____(Protocol[_ReqT, _RespT]): """WSGI Middleware with request handler.""" def process_request(self, req: _ReqT, resp: _RespT) -> None: ...
WsgiMiddlewareWithProcessRequest
python
google__pytype
pytype/tests/test_attr1.py
{ "start": 19885, "end": 21636 }
class ____(test_base.BaseTest): """Tests for attr.s.""" def test_basic(self): ty = self.Infer(""" import attr @attr.s() class Foo: x = attr.ib() y = attr.ib(type=int) z = attr.ib(type=str) """) self.assertTypesMatchPytd( ty, """ import att...
TestAttrs
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py
{ "start": 213604, "end": 230232 }
class ____(quantize_model_test_base.QuantizedModelTest): """Test cases regarding the use of CalibrationOptions proto. Run all tests cases in both the graph mode (default in TF1) and the eager mode (default in TF2) to ensure support for when TF2 is disabled. """ @parameterized.parameters( testing.param...
CalibrationOptionsTest
python
huggingface__transformers
src/transformers/models/ibert/modeling_ibert.py
{ "start": 28759, "end": 31627 }
class ____(IBertPreTrainedModel): _tied_weights_keys = { "lm_head.decoder.weight": "ibert.embeddings.word_embeddings.weight$", "lm_head.decoder.bias": "lm_head.bias", } def __init__(self, config): super().__init__(config) self.ibert = IBertModel(config, add_pooling_layer=Fa...
IBertForMaskedLM
python
doocs__leetcode
solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/Solution.py
{ "start": 0, "end": 441 }
class ____: def numSteps(self, s: str) -> int: carry = False ans = 0 for c in s[:0:-1]: if carry: if c == '0': c = '1' carry = False else: c = '0' if c == '1': ...
Solution
python
lxml__lxml
src/lxml/tests/common_imports.py
{ "start": 4067, "end": 5114 }
class ____: def __init__(self, charlen=100, depth=4, children=5): self.data = BytesIO() self.chars = b'a' * charlen self.children = range(children) self.more = self.iterelements(depth) def iterelements(self, depth): yield b'<root>' depth -= 1 if depth > ...
LargeFileLike
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 225314, "end": 226090 }
class ____(sgqlc.types.Input): """Autogenerated input type of DismissRepositoryVulnerabilityAlert""" __schema__ = github_schema __field_names__ = ("repository_vulnerability_alert_id", "dismiss_reason", "client_mutation_id") repository_vulnerability_alert_id = sgqlc.types.Field(sgqlc.types.non_null(ID),...
DismissRepositoryVulnerabilityAlertInput
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 285491, "end": 286151 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("DiscussionPollOptionEdge"), graphql_name="edges" ) nodes ...
DiscussionPollOptionConnection
python
django__django
tests/migrations/migrations_test_apps/lookuperror_a/migrations/0003_a3.py
{ "start": 43, "end": 802 }
class ____(migrations.Migration): dependencies = [ ("lookuperror_c", "0002_c2"), ("lookuperror_b", "0002_b2"), ("lookuperror_a", "0002_a2"), ] operations = [ migrations.CreateModel( name="A3", fields=[ ( "id", ...
Migration
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/79_metaclass.py
{ "start": 0, "end": 42 }
class ____(Base, metaclass=Meta): pass
Foo
python
apache__avro
lang/py/avro/test/test_tether_word_count.py
{ "start": 2913, "end": 6415 }
class ____(unittest.TestCase): """unittest for a python tethered map-reduce job.""" _base_dir = None _script_path = None _input_path = None _output_path = None _output_schema_path = None def setUp(self): """Create temporary files for testing.""" prefix, _ = os.path.splitext...
TestTetherWordCount
python
getsentry__sentry
src/sentry/api/endpoints/oauth_userinfo.py
{ "start": 551, "end": 764 }
class ____(SentryAPIException): status_code = status.HTTP_403_FORBIDDEN code = "insufficient-scope" message = "openid scope is required for userinfo access" @control_silo_endpoint
InsufficientScopesError
python
great-expectations__great_expectations
tests/data_context/test_project_manager.py
{ "start": 307, "end": 2066 }
class ____: @pytest.mark.unit def test_get_expectations_store_success(self): context = Mock(spec=AbstractDataContext) project_manager = ProjectManager() project_manager.set_project(project=context) store = project_manager.get_expectations_store() assert store == context...
TestProjectManagerStores
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 515694, "end": 515886 }
class ____(VegaLiteSchema): """LayoutAlign schema wrapper.""" _schema = {"$ref": "#/definitions/LayoutAlign"} def __init__(self, *args): super().__init__(*args)
LayoutAlign
python
scrapy__scrapy
tests/test_request_attribute_binding.py
{ "start": 905, "end": 1160 }
class ____: def process_exception(self, request, exception): return Response( url="http://localhost/", body=b"Caught " + exception.__class__.__name__.encode("utf-8"), )
CatchExceptionDoNotOverrideRequestMiddleware
python
joke2k__faker
faker/providers/address/de_CH/__init__.py
{ "start": 73, "end": 5338 }
class ____(AddressProvider): city_formats = ("{{city_name}}",) building_number_formats = ("%", "%#", "%#", "%#", "%##") street_suffixes = ["strasse"] street_name_formats = ("{{last_name}}{{street_suffix}}",) street_address_formats = ("{{street_name}} {{building_number}}",) address_formats = ("{{...
Provider
python
pikepdf__pikepdf
src/pikepdf/_methods.py
{ "start": 23923, "end": 24751 }
class ____(MutableMapping): def __getitem__(self, k: str) -> AttachedFileSpec: filespec = self._get_filespec(k) if filespec is None: raise KeyError(k) return filespec def __setitem__(self, k: str, v: AttachedFileSpec | bytes) -> None: if isinstance(v, bytes): ...
Extend_Attachments
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/policy.py
{ "start": 824, "end": 3811 }
class ____( NamedTuple( "_RetryPolicy", [ ("max_retries", PublicAttr[int]), ("delay", PublicAttr[Optional[check.Numeric]]), # declarative time modulation to allow calc witout running user function ("backoff", PublicAttr[Optional[Backoff]]), ...
RetryPolicy
python
django__django
tests/m2o_recursive/models.py
{ "start": 366, "end": 609 }
class ____(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey( "self", models.SET_NULL, blank=True, null=True, related_name="child_set" ) def __str__(self): return self.name
Category
python
huggingface__transformers
tests/models/umt5/test_modeling_umt5.py
{ "start": 14487, "end": 18937 }
class ____: def __init__( self, parent, vocab_size=99, batch_size=13, encoder_seq_length=7, # For common tests use_attention_mask=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, d_ff=37, relative_attent...
UMT5EncoderOnlyModelTester
python
apache__airflow
scripts/ci/prek/new_session_in_provide_session.py
{ "start": 927, "end": 1562 }
class ____(typing.NamedTuple): argument: ast.arg default: ast.expr | None def _get_session_arg_and_default(args: ast.arguments) -> _SessionArgument | None: arguments = reversed([*args.args, *args.kwonlyargs]) defaults = reversed([*args.defaults, *args.kw_defaults]) for argument, default in itertoo...
_SessionArgument
python
patrick-kidger__equinox
equinox/internal/_loop/common.py
{ "start": 7617, "end": 10696 }
class ____(Module): start: Any stop: Any step: Any def _is_hashable_slice(x): return isinstance(x, _HashableSlice) def _to_hashable_slice_impl(x): if isinstance(x, slice): return _HashableSlice(x.start, x.stop, x.step) else: return x def _to_raw_slice_impl(x): if _is_ha...
_HashableSlice
python
ray-project__ray
rllib/examples/envs/classes/repeat_after_me_env.py
{ "start": 88, "end": 1591 }
class ____(gym.Env): """Env in which the observation at timestep minus n must be repeated.""" def __init__(self, config=None): config = config or {} if config.get("continuous"): self.observation_space = Box(-1.0, 1.0, (2,)) else: self.observation_space = Discrete...
RepeatAfterMeEnv
python
kamyu104__LeetCode-Solutions
Python/minimum-score-triangulation-of-polygon.py
{ "start": 33, "end": 527 }
class ____(object): def minScoreTriangulation(self, A): """ :type A: List[int] :rtype: int """ dp = [[0 for _ in xrange(len(A))] for _ in xrange(len(A))] for p in xrange(3, len(A)+1): for i in xrange(len(A)-p+1): j = i+p-1 d...
Solution
python
huggingface__transformers
tests/models/nystromformer/test_modeling_nystromformer.py
{ "start": 1359, "end": 8958 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_head...
NystromformerModelTester
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 30005, "end": 30514 }
class ____(Structure): _fields_ = ( ("module_name", p_uint32), ("iextdefsym", p_uint32), ("nextdefsym", p_uint32), ("irefsym", p_uint32), ("nrefsym", p_uint32), ("ilocalsym", p_uint32), ("nlocalsym", p_uint32), ("iextrel", p_uint32), ("nextrel"...
dylib_module
python
pytorch__pytorch
test/test_testing.py
{ "start": 12878, "end": 14366 }
class ____(TestCase): @slowTest def test_throw_unrecoverable_cuda_exception(self, device): x = torch.rand(10, device=device) # cause unrecoverable CUDA exception, recoverable on CPU y = x[torch.tensor([25])].cpu() @slowTest def test_trivial_passing_test_case_on_cpu_cuda(self, d...
TestThatContainsCUDAAssertFailure
python
django__django
tests/contenttypes_tests/models.py
{ "start": 940, "end": 1012 }
class ____(ConcreteModel): class Meta: proxy = True
ProxyModel
python
kamyu104__LeetCode-Solutions
Python/minimum-weighted-subgraph-with-the-required-paths-ii.py
{ "start": 2703, "end": 3898 }
class ____(object): def minimumWeight(self, edges, queries): """ :type edges: List[List[int]] :type queries: List[List[int]] :rtype: List[int] """ def dfs(u): for i in lookup2[u]: result[i] += dist[u] for x in queries[i]: ...
Solution2
python
python-markdown__markdown
tests/test_syntax/blocks/test_blockquotes.py
{ "start": 797, "end": 1809 }
class ____(TestCase): # TODO: Move legacy tests here def test_nesting_limit(self): # Test that the nesting limit is within 100 levels of recursion limit. Future code changes could cause the # recursion limit to need adjusted here. We need to account for all of Markdown's internal calls. Finall...
TestBlockquoteBlocks
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 2586, "end": 2754 }
class ____[*Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]: pass
TestTypeParams
python
wntrblm__nox
nox/sessions.py
{ "start": 33687, "end": 43225 }
class ____: def __init__( self, name: str, signatures: Sequence[str], func: Func, global_config: argparse.Namespace, manifest: Manifest, *, multi: bool = False, ) -> None: self.name = name self.signatures = signatures self.f...
SessionRunner
python
getsentry__sentry
src/sentry/explore/endpoints/explore_saved_query_starred_order.py
{ "start": 1158, "end": 2703 }
class ____(OrganizationEndpoint): publish_status = {"PUT": ApiPublishStatus.EXPERIMENTAL} owner = ApiOwner.EXPLORE permission_classes = (MemberPermission,) def has_feature(self, organization, request): return features.has( "organizations:visibility-explore-view", organization, actor...
ExploreSavedQueryStarredOrderEndpoint