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
pytorch__pytorch
test/mkldnn_verbose.py
{ "start": 32, "end": 637 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(1, 10, 5, 1) def forward(self, x): y = self.conv(x) return y def run_model(level): m = Module().eval() d = torch.rand(1, 1, 112, 112) with torch.backends.mkldnn....
Module
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table30.py
{ "start": 315, "end": 920 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table30.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/divide-intervals-into-minimum-number-of-groups.py
{ "start": 73, "end": 505 }
class ____(object): def minGroups(self, intervals): """ :type intervals: List[List[int]] :rtype: int """ events = collections.Counter() for l, r in intervals: events[l] += 1 events[r+1] -= 1 result = curr = 0 for t in sorted(eve...
Solution
python
plotly__plotly.py
plotly/graph_objs/barpolar/marker/colorbar/_tickformatstop.py
{ "start": 233, "end": 8554 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "barpolar.marker.colorbar" _path_str = "barpolar.marker.colorbar.tickformatstop" _valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"} @property def dtickrange(self): """ range [*min*, *max*], where ...
Tickformatstop
python
dagster-io__dagster
python_modules/dagster/dagster_tests/definitions_tests/test_default_io_manager.py
{ "start": 663, "end": 3405 }
class ____(PickledObjectFilesystemIOManager): def __init__(self, ctx): super().__init__(base_dir="/tmp/dagster/foo-io-manager") assert ctx.instance foo_io_manager_def = dg.IOManagerDefinition( resource_fn=FooIoManager, config_schema={}, ) @dg.op def foo_io_manager_op(context): assert...
FooIoManager
python
huggingface__transformers
tests/models/falcon_h1/test_modeling_falcon_h1.py
{ "start": 15821, "end": 23736 }
class ____(unittest.TestCase): @slow def test_falcon_h1_hard(self): """ An integration test for Falcon-H1. """ EXPECTED_TEXT_DEFAULT = """ user Tell me about the french revolution. assistant The French Revolution (1789–1799) was a p...
FalconH1ModelIntegrationTest
python
pypa__pip
src/pip/_vendor/pygments/formatter.py
{ "start": 465, "end": 4390 }
class ____: """ Converts a token stream to text. Formatters should have attributes to help selecting them. These are similar to the corresponding :class:`~pygments.lexer.Lexer` attributes. .. autoattribute:: name :no-value: .. autoattribute:: aliases :no-value: .. autoa...
Formatter
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 36526, "end": 36927 }
class ____(VOTableSpecWarning): """ The column fields as defined using ``FIELD`` elements do not match those in the headers of the embedded PARQUET file. If ``verify`` is not ``'exception'``, the embedded PARQUET file will take precedence. """ message_template = ( "The fields defined i...
W56
python
aio-libs__aiohttp
aiohttp/_websocket/models.py
{ "start": 265, "end": 626 }
class ____(IntEnum): OK = 1000 GOING_AWAY = 1001 PROTOCOL_ERROR = 1002 UNSUPPORTED_DATA = 1003 ABNORMAL_CLOSURE = 1006 INVALID_TEXT = 1007 POLICY_VIOLATION = 1008 MESSAGE_TOO_BIG = 1009 MANDATORY_EXTENSION = 1010 INTERNAL_ERROR = 1011 SERVICE_RESTART = 1012 TRY_AGAIN_LATE...
WSCloseCode
python
oauthlib__oauthlib
tests/openid/connect/core/grant_types/test_implicit.py
{ "start": 6762, "end": 7637 }
class ____(OpenIDImplicitTest): def setUp(self): super().setUp() self.request.response_type = 'id_token' token = 'MOCKED_TOKEN' self.url_query = 'https://a.b/cb?state=abc&id_token=%s' % token self.url_fragment = 'https://a.b/cb#state=abc&id_token=%s' % token @mock.patch(...
OpenIDImplicitNoAccessTokenTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 491442, "end": 492003 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("organization", "permission", "source") organization = sgqlc.types.Field( sgqlc.types.non_null("Organization"), graphql_name="organization" ) permission = sgqlc.ty...
PermissionSource
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 133374, "end": 143054 }
class ____(Token): r""" Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - ``quote_char`` - string of one or more characters defining the quote delimiting string - ``esc_char`` - character to re_escape quotes, typically backslash ...
QuotedString
python
kamyu104__LeetCode-Solutions
Python/zero-array-transformation-ii.py
{ "start": 70, "end": 1030 }
class ____(object): def minZeroArray(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: int """ def binary_search(left, right, check): while left <= right: mid = left+(right-left)//2 if ch...
Solution
python
django-haystack__django-haystack
test_haystack/elasticsearch7_tests/test_backend.py
{ "start": 59888, "end": 62602 }
class ____(TestCase): def setUp(self): super().setUp() # Wipe it clean. self.raw_es = elasticsearch.Elasticsearch( settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"] ) clear_elasticsearch_index() # Stow. self.old_ui = connections["elasticsearc...
Elasticsearch7BoostBackendTestCase
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/get_task_states_test.py
{ "start": 6157, "end": 6438 }
class ____(GetTaskStatesTest, test.TestCase): """This covers the cases where multiple workers and PS are used.""" def setUp(self): super().setUp(2, 2) if __name__ == "__main__": v2_compat.enable_v2_behavior() multi_process_runner.test_main()
MultiWorkerGetTaskStatesTest
python
jazzband__django-polymorphic
src/polymorphic/models.py
{ "start": 538, "end": 594 }
class ____(LookupError): pass
PolymorphicTypeUndefined
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_quicksight.py
{ "start": 1385, "end": 3862 }
class ____: def setup_method(self): self.default_op_kwargs = { "task_id": "quicksight_sensor", "aws_conn_id": None, "data_set_id": DATA_SET_ID, "ingestion_id": INGESTION_ID, } def test_init(self): self.default_op_kwargs.pop("aws_conn_id", ...
TestQuickSightSensor
python
allegroai__clearml
clearml/utilities/gpu/pynvml.py
{ "start": 57123, "end": 58122 }
class ____(_PrintableStructure): _fields_ = [ ('sessionId', c_uint), ('pid', c_uint), ('vgpuInstance', _nvmlVgpuInstance_t), ('displayOrdinal', c_uint), ('sessionType', c_uint), ('sessionFlags', c_uint), ('hMaxResolution', c_uint), ('vMaxResolution', c...
c_nvmlFBCSession_t
python
sqlalchemy__sqlalchemy
examples/association/dict_of_sets_with_default.py
{ "start": 1433, "end": 1879 }
class ____(Base): __tablename__ = "a" associations: Mapped[Mapping[str, B]] = relationship( "B", collection_class=lambda: GenDefaultCollection( operator.attrgetter("key") ), ) collections: AssociationProxy[dict[str, set[int]]] = association_proxy( "associatio...
A
python
PrefectHQ__prefect
src/prefect/context.py
{ "start": 13633, "end": 16653 }
class ____(RunContext): """ The context for a flow run. Data in this context is only available from within a flow run function. Attributes: flow: The flow instance associated with the run flow_run: The API metadata for the flow run task_runner: The task runner instance being use...
EngineContext
python
encode__django-rest-framework
tests/test_request.py
{ "start": 10113, "end": 10422 }
class ____(TestCase): def test_default_secure_false(self): request = Request(factory.get('/', secure=False)) assert request.scheme == 'http' def test_default_secure_true(self): request = Request(factory.get('/', secure=True)) assert request.scheme == 'https'
TestSecure
python
huggingface__transformers
tests/models/sam/test_image_processing_sam.py
{ "start": 4049, "end": 13134 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = SamImageProcessor if is_vision_available() else None fast_image_processing_class = SamImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = S...
SamImageProcessingTest
python
ansible__ansible
lib/ansible/module_utils/common/arg_spec.py
{ "start": 2787, "end": 11219 }
class ____: """Argument spec validation class Creates a validator based on the ``argument_spec`` that can be used to validate a number of parameters using the :meth:`validate` method. """ def __init__(self, argument_spec, mutually_exclusive=None, required_together...
ArgumentSpecValidator
python
ray-project__ray
release/llm_tests/serve/test_llm_serve_correctness.py
{ "start": 2396, "end": 7811 }
class ____: def __init__( self, tensor_parallel_size: int = 1, pipeline_parallel_size: int = 1, model_id: str = MODEL_ID, ): self.tensor_parallel_size = tensor_parallel_size self.pipeline_parallel_size = pipeline_parallel_size self.model_id = model_id ...
VllmServer
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_annotated.py
{ "start": 276, "end": 336 }
class ____(Enum): RED = 1 GREEN = 2 BLUE = 3
Color
python
django__django
tests/foreign_object/tests.py
{ "start": 23742, "end": 25491 }
class ____(SimpleTestCase): @isolate_apps("foreign_object") def test_check_composite_foreign_object(self): class Parent(models.Model): a = models.PositiveIntegerField() b = models.PositiveIntegerField() class Meta: unique_together = (("a", "b"),) ...
TestModelCheckTests
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-lilac/llama_index/readers/lilac/base.py
{ "start": 314, "end": 3894 }
class ____(BaseReader): """ Lilac dataset reader. """ def load_data( self, dataset: str, text_path: "Path" = "text", doc_id_path: Optional["Path"] = "doc_id", columns: Optional[List["ColumnId"]] = None, filters: Optional[List["FilterLike"]] = None, ...
LilacReader
python
getsentry__sentry
fixtures/safe_migrations_apps/bad_flow_delete_field_double_pending_app/migrations/0002_delete_pending.py
{ "start": 190, "end": 507 }
class ____(CheckedMigration): dependencies = [ ("bad_flow_delete_field_double_pending_app", "0001_initial"), ] operations = [ SafeRemoveField( model_name="testtable", name="field", deletion_action=DeletionAction.MOVE_TO_PENDING, ), ]
Migration
python
ray-project__ray
python/ray/serve/tests/test_https_proxy.py
{ "start": 1743, "end": 11053 }
class ____: def test_https_basic_deployment(self, https_serve_instance): """Test basic HTTPS deployment functionality.""" @serve.deployment def hello(): return "Hello HTTPS!" serve.run(hello.bind()) # Test HTTPS request with certificate verification disabled fo...
TestHTTPSProxy
python
getsentry__sentry
src/sentry/api/fields/actor.py
{ "start": 287, "end": 611 }
class ____(serializers.Field): def __init__(self, *args, **kwds): super().__init__(*args, **kwds) def to_representation(self, value): return value.identifier def to_internal_value(self, data) -> Actor | None: return parse_and_validate_actor(data, self.context["organization"].id)
ActorField
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/cloud/digitalocean.py
{ "start": 739, "end": 1498 }
class ____(CloudEnvironment): """Updates integration test environment after delegation. Will setup the config file as parameter.""" def get_environment_config(self) -> CloudEnvironmentConfig: """Return environment configuration for use in the test environment after delegation.""" parser = confi...
DigitalOceanCloudEnvironment
python
huggingface__transformers
src/transformers/models/pix2struct/image_processing_pix2struct.py
{ "start": 8185, "end": 20061 }
class ____(BaseImageProcessor): r""" Constructs a Pix2Struct image processor. Args: do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. Ca...
Pix2StructImageProcessor
python
catalyst-team__catalyst
catalyst/contrib/data/reader.py
{ "start": 4442, "end": 5229 }
class ____(object): """Abstraction to compose several readers into one open function.""" def __init__(self, transforms: List[IReader]): """ Args: transforms: list of reader to compose """ self.transforms = transforms def __call__(self, element): """ ...
ReaderCompose
python
huggingface__transformers
src/transformers/models/gemma2/configuration_gemma2.py
{ "start": 1321, "end": 10374 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Gemma2Model`]. It is used to instantiate an Gemma2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar config...
Gemma2Config
python
bokeh__bokeh
src/bokeh/core/property/dataspec.py
{ "start": 12291, "end": 12468 }
class ____(DataSpec): def __init__(self, default, *, help: str | None = None) -> None: super().__init__(Enum(enums.FontStyle), default=default, help=help)
FontStyleSpec
python
ray-project__ray
python/ray/data/_internal/planner/exchange/push_based_shuffle_task_scheduler.py
{ "start": 12596, "end": 15357 }
class ____: def __init__( self, stage: _PushBasedShuffleStage, shuffle_reduce, all_merge_results: List[List[List[ObjectRef]]], ray_remote_args, reduce_args: List[Any], _debug_limit_execution_to_num_blocks: Optional[int], ): self._shuffle_reduce = s...
_ReduceStageIterator
python
ethereum__web3.py
ens/_normalization.py
{ "start": 1292, "end": 1355 }
class ____(Enum): EMOJI = "emoji" TEXT = "text"
TokenType
python
getsentry__sentry
src/sentry/analytics/events/onboarding_complete.py
{ "start": 76, "end": 230 }
class ____(analytics.Event): user_id: int organization_id: int referrer: str analytics.register(OnboardingCompleteEvent)
OnboardingCompleteEvent
python
Textualize__textual
tests/text_area/test_messages.py
{ "start": 199, "end": 3152 }
class ____(App): def __init__(self): super().__init__() self.messages = [] @on(TextArea.Changed) @on(TextArea.SelectionChanged) def message_received(self, message: Message): self.messages.append(message) def compose(self) -> ComposeResult: yield TextArea("123") de...
TextAreaApp
python
pytorch__pytorch
test/test_tensorboard.py
{ "start": 20560, "end": 26925 }
class ____(BaseTestCase): def test_pytorch_graph(self): dummy_input = (torch.zeros(1, 3),) class myLinear(torch.nn.Module): def __init__(self) -> None: super().__init__() self.l = torch.nn.Linear(3, 5) def forward(self, x): re...
TestTensorBoardPytorchGraph
python
tiangolo__fastapi
docs_src/extra_models/tutorial002.py
{ "start": 300, "end": 824 }
class ____(UserBase): hashed_password: str def fake_password_hasher(raw_password: str): return "supersecret" + raw_password def fake_save_user(user_in: UserIn): hashed_password = fake_password_hasher(user_in.password) user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) print...
UserInDB
python
MongoEngine__mongoengine
tests/test_common.py
{ "start": 95, "end": 362 }
class ____: def test__import_class(self): doc_cls = _import_class("Document") assert doc_cls is Document def test__import_class_raise_if_not_known(self): with pytest.raises(ValueError): _import_class("UnknownClass")
TestCommon
python
django__django
tests/datatypes/models.py
{ "start": 585, "end": 729 }
class ____(models.Model): baked_date = models.DateField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True)
RumBaba
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-ollama/tests/test_embeddings_ollama.py
{ "start": 2015, "end": 8839 }
class ____: """Test cases for the new instruction functionality.""" def test_instruction_fields_default_none(self): """Test that instruction fields default to None.""" embedder = OllamaEmbedding(model_name="test-model") assert embedder.query_instruction is None assert embedder.t...
TestInstructionFunctionality
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 20890, "end": 37982 }
class ____: @skip_xp_backends("torch", reason="dtypes do not match") @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_real(self, axes, xp): a = xp.asarray([1, 2, 3]) expected = xp.asarray([1, 4, 10, 12, 9.]) if axes == '': out = fftconvolve(a, a) ...
TestFFTConvolve
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qunary_test.py
{ "start": 562, "end": 4740 }
class ____(op_bench.TorchBenchmarkBase): def init(self, M, N, dtype, op_func): f_input = torch.rand(M, N) scale = 1.0 zero_point = 0 self.inputs = { "q_input": torch.quantize_per_tensor( f_input, scale=scale, zero_point=zero_point, dtype=dtype ...
QUnaryOpBenchmark
python
wandb__wandb
wandb/vendor/pygments/lexers/webmisc.py
{ "start": 1786, "end": 33366 }
class ____(ExtendedRegexLexer): """ An XQuery lexer, parsing a stream and outputting the tokens needed to highlight xquery code. .. versionadded:: 1.4 """ name = 'XQuery' aliases = ['xquery', 'xqy', 'xq', 'xql', 'xqm'] filenames = ['*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm'] mime...
XQueryLexer
python
kamyu104__LeetCode-Solutions
Python/maximum-star-sum-of-a-graph.py
{ "start": 60, "end": 1851 }
class ____(object): def maxStarSum(self, vals, edges, k): """ :type vals: List[int] :type edges: List[List[int]] :type k: int :rtype: int """ def nth_element(nums, n, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare...
Solution
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 29762, "end": 30425 }
class ____(BaseLinksSerializer): _self = serializers.SerializerMethodField() parent = serializers.SerializerMethodField() def get__self(self, obj): path = reverse( "projects-subprojects-detail", kwargs={ "parent_lookup_parent__slug": obj.parent.slug, ...
SubprojectLinksSerializer
python
pexpect__pexpect
tests/test_constructor.py
{ "start": 1023, "end": 1948 }
class ____(PexpectTestCase.PexpectTestCase): def test_constructor (self): '''This tests that the constructor will work and give the same results for different styles of invoking __init__(). This assumes that the root directory / is static during the test. ''' p1 = pexpect.spa...
TestCaseConstructor
python
gevent__gevent
src/gevent/tests/test__monkey_module_run.py
{ "start": 411, "end": 4368 }
class ____(greentest.TestCase): maxDiff = None def setUp(self): self.abs_pythonpath = absolute_pythonpath() # before we cd self.cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) def tearDown(self): os.chdir(self.cwd) def _run(self, script, module=False): en...
TestRun
python
langchain-ai__langchain
libs/core/langchain_core/runnables/base.py
{ "start": 214242, "end": 214416 }
class ____(Protocol[Input, Output]): def __call__( self, _in: Iterator[Input], /, *, config: RunnableConfig ) -> Iterator[Output]: ...
_RunnableCallableIterator
python
pandas-dev__pandas
pandas/io/excel/_base.py
{ "start": 51981, "end": 67543 }
class ____: """ Class for parsing tabular Excel sheets into DataFrame objects. See read_excel for more documentation. Parameters ---------- path_or_buffer : str, bytes, pathlib.Path, A file-like object, xlrd workbook or openpyxl workbook. If a string or path object, expected to...
ExcelFile
python
ray-project__ray
rllib/policy/torch_policy.py
{ "start": 1663, "end": 48994 }
class ____(Policy): """PyTorch specific Policy class to use with RLlib.""" def __init__( self, observation_space: gym.spaces.Space, action_space: gym.spaces.Space, config: AlgorithmConfigDict, *, model: Optional[TorchModelV2] = None, loss: Optional[ ...
TorchPolicy
python
getsentry__sentry
src/sentry/incidents/endpoints/project_alert_rule_task_details.py
{ "start": 746, "end": 2504 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PRIVATE, } permission_classes = (ProjectSettingPermission,) def get(self, request: Request, project, task_uuid) -> Response: """ Retrieve the status of the async task Ret...
ProjectAlertRuleTaskDetailsEndpoint
python
huggingface__transformers
src/transformers/models/prompt_depth_anything/image_processing_prompt_depth_anything.py
{ "start": 3453, "end": 25202 }
class ____(BaseImageProcessor): r""" Constructs a PromptDepthAnything image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. Can be overridden by `do_resize` in `preprocess`. size (`dict[str, int]` *op...
PromptDepthAnythingImageProcessor
python
getsentry__sentry
src/sentry/utils/cursors.py
{ "start": 2216, "end": 2560 }
class ____(Cursor): @classmethod def from_string(cls, cursor_str: str) -> Cursor: bits = cursor_str.split(":") if len(bits) != 3: raise ValueError try: return Cursor(bits[0], int(bits[1]), int(bits[2])) except (TypeError, ValueError): raise Val...
EAPPageTokenCursor
python
pandas-dev__pandas
pandas/core/base.py
{ "start": 2977, "end": 4249 }
class ____: """ Mixin which prevents adding new attributes. Prevents additional attributes via xxx.attribute = "something" after a call to `self.__freeze()`. Mainly used to prevent the user from using wrong attributes on an accessor (`Series.cat/.str/.dt`). If you really want to add a new attr...
NoNewAttributesMixin
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 46908, "end": 47424 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("ja_JP") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in JaJpProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in JaJp...
TestJaJp
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 31734, "end": 32393 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.layers = nn.ModuleList( SeamlessM4Tv2ConformerAdapterLayer(config) for _ in range(config.num_adapter_layers) ) def forward(self, hidden_states, attention_mask): # down project hidden_states i...
SeamlessM4Tv2ConformerAdapter
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_stateful.py
{ "start": 9019, "end": 9226 }
class ____(RuleBasedStateMachine): values = Bundle("values") @rule(target=values, value=st.lists(values)) def f(self, value): assert len(value) == 0 return value
SourceSameAsTarget
python
sanic-org__sanic
tests/test_exceptions_handler.py
{ "start": 403, "end": 8681 }
class ____(ServerError): pass @pytest.fixture def exception_handler_app(): exception_handler_app = Sanic("test_exception_handler") @exception_handler_app.route("/1", error_format="html") def handler_1(request): raise BadRequest("OK") @exception_handler_app.route("/2", error_format="html"...
ErrorWithRequestCtx
python
mlflow__mlflow
mlflow/genai/git_versioning/git_info.py
{ "start": 282, "end": 389 }
class ____(Exception): """Raised when a git operation fails""" @dataclass(kw_only=True)
GitOperationError
python
doocs__leetcode
lcof2/剑指 Offer II 084. 含有重复元素集合的全排列/Solution.py
{ "start": 0, "end": 602 }
class ____: def permuteUnique(self, nums: List[int]) -> List[List[int]]: n = len(nums) res = [] path = [0] * n used = [False] * n nums.sort() def dfs(u): if u == n: res.append(path.copy()) return for i in range(...
Solution
python
pandas-dev__pandas
pandas/tests/indexing/multiindex/test_partial.py
{ "start": 154, "end": 8358 }
class ____: def test_getitem_partial_int(self): # GH 12416 # with single item l1 = [10, 20] l2 = ["a", "b"] df = DataFrame(index=range(2), columns=MultiIndex.from_product([l1, l2])) expected = DataFrame(index=range(2), columns=l2) result = df[20] tm.as...
TestMultiIndexPartial
python
tensorflow__tensorflow
tensorflow/compiler/mlir/quantization/stablehlo/python/integration_test/quantize_model_test.py
{ "start": 41468, "end": 52648 }
class ____(quantize_model_test_base.QuantizedModelTest): @parameterized.parameters( testing.parameter_combinations([{ 'bias_fn': ( None, nn_ops.bias_add, ), 'activation_fn': ( None, nn_ops.relu, nn_ops.relu6, ...
WeightOnlyQuantizationTest
python
wandb__wandb
wandb/vendor/pygments/lexer.py
{ "start": 24288, "end": 29031 }
class ____(RegexLexer): """ A RegexLexer that uses a context object to store its state. """ def get_tokens_unprocessed(self, text=None, context=None): """ Split ``text`` into (tokentype, text) pairs. If ``context`` is given, use this lexer context instead. """ to...
ExtendedRegexLexer
python
joke2k__faker
tests/providers/test_date_time.py
{ "start": 25374, "end": 25726 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("pl_PL") Faker.seed(0) def test_day(self): day = self.fake.day_of_week() assert day in PlProvider.DAY_NAMES.values() def test_month(self): month = self.fake.month_name() assert month in PlProv...
TestPlPL
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_events_monitors_test.py
{ "start": 8666, "end": 9455 }
class ____(test_util.TensorFlowTestCase): """Unit tests for alert-class objects.""" def testInfNanMonitor(self): alert = debug_events_monitors.InfNanAlert( 1234, "FooOp", 1, size=1000, num_neg_inf=5, num_pos_inf=10, num_nan=20, execution_index=777...
AlertDataObjectsTest
python
pandas-dev__pandas
pandas/core/apply.py
{ "start": 48989, "end": 52414 }
class ____(NDFrameApply): obj: Series axis: AxisInt = 0 by_row: Literal[False, "compat", "_compat"] # only relevant for apply() def __init__( self, obj: Series, func: AggFuncType, *, by_row: Literal[False, "compat", "_compat"] = "compat", args, k...
SeriesApply
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/async_job.py
{ "start": 8559, "end": 19883 }
class ____(AsyncJob): """Wraps FB AdReportRun with retry/split logic driven in _check_status().""" page_size = 100 def __init__( self, edge_object: Union[AdAccount, Campaign, AdSet, Ad], params: Mapping[str, Any], job_timeout: timedelta, primary_key: Optional[List[s...
InsightAsyncJob
python
networkx__networkx
networkx/readwrite/tests/test_leda.py
{ "start": 35, "end": 1392 }
class ____: def test_parse_leda(self): data = """#header section \nLEDA.GRAPH \nstring\nint\n-1\n#nodes section\n5 \n|{v1}| \n|{v2}| \n|{v3}| \n|{v4}| \n|{v5}| \n\n#edges section\n7 \n1 2 0 |{4}| \n1 3 0 |{3}| \n2 3 0 |{2}| \n3 4 0 |{3}| \n3 5 0 |{7}| \n4 5 0 |{6}| \n5 1 0 |{foo}|""" G = nx....
TestLEDA
python
PrefectHQ__prefect
src/prefect/server/events/actions.py
{ "start": 42989, "end": 46750 }
class ____(JinjaTemplateAction): """Call a webhook when an Automation is triggered.""" type: Literal["call-webhook"] = "call-webhook" block_document_id: UUID = Field( description="The identifier of the webhook block to use" ) payload: str = Field( default="", description="An...
CallWebhook
python
doocs__leetcode
solution/0500-0599/0589.N-ary Tree Preorder Traversal/Solution2.py
{ "start": 152, "end": 485 }
class ____: def preorder(self, root: 'Node') -> List[int]: ans = [] if root is None: return ans stk = [root] while stk: node = stk.pop() ans.append(node.val) for child in node.children[::-1]: stk.append(child) re...
Solution
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/multi_client_input_util_test.py
{ "start": 4353, "end": 10617 }
class ____: """tf.data service cluster with dispatcher and workers as subprocesses. To run the cluster in co-located mode, set `num_workers` to 0 and create the tf.data service workers manually in each client process. """ def __init__(self, test_name, num_workers, ...
TFDataServiceCluster
python
python__mypy
mypyc/codegen/emitwrapper.py
{ "start": 32268, "end": 37926 }
class ____: """Helper that simplifies the generation of wrapper functions.""" # TODO: Use this for more wrappers def __init__(self, cl: ClassIR | None, emitter: Emitter) -> None: self.cl = cl self.emitter = emitter self.cleanups: list[str] = [] self.optional_args: list[Runt...
WrapperGenerator
python
doocs__leetcode
solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py
{ "start": 0, "end": 496 }
class ____: def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: n = len(nums) arr = sorted(zip(nums, range(n))) ans = [0] * n i = 0 while i < n: j = i + 1 while j < n and arr[j][0] - arr[j - 1][0] <= limit: ...
Solution
python
numpy__numpy
numpy/_core/tests/test_deprecations.py
{ "start": 7828, "end": 9576 }
class ____(_DeprecationTestCase): message = r".*stop allowing conversion of out-of-bound.*" @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"]) def test_deprecated_scalar(self, dtype): dtype = np.dtype(dtype) info = np.iinfo(dtype) # Cover the most common creation paths (...
TestPyIntConversion
python
PrefectHQ__prefect
tests/server/orchestration/api/test_deployments.py
{ "start": 43518, "end": 45861 }
class ____: async def test_read_deployment_by_name(self, client, flow, deployment): response = await client.get(f"/deployments/name/{flow.name}/{deployment.name}") assert response.status_code == status.HTTP_200_OK assert response.json()["id"] == str(deployment.id) assert response.jso...
TestReadDeploymentByName
python
great-expectations__great_expectations
tests/expectations/metrics/query_metrics/test_query_metrics.py
{ "start": 2234, "end": 2387 }
class ____(QueryColumn): metric_name = "my_query.column" value_keys = ("my_query",) query_param_name: ClassVar[str] = "my_query"
MyQueryColumn
python
pandas-dev__pandas
pandas/core/accessor.py
{ "start": 5690, "end": 17395 }
class ____: """ Custom property-like object. A descriptor for accessors. Parameters ---------- name : str Namespace that will be accessed under, e.g. ``df.foo``. accessor : cls Class with the extension methods. Notes ----- For accessor, The class's __init__ met...
Accessor
python
getsentry__sentry
src/sentry/relay/types/rule_condition.py
{ "start": 1039, "end": 1173 }
class ____(TypedDict): """Less than or equal condition""" op: Literal["lte"] name: str value: Value | None
LteCondition
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 141135, "end": 146748 }
class ____(CythonTransform): # Output closure classes in module scope for all functions # that really need it. def __init__(self, context): super().__init__(context) self.path = [] self.in_lambda = False def visit_ModuleNode(self, node): self.module_scope = node.scope ...
CreateClosureClasses
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_svg.py
{ "start": 51030, "end": 51132 }
class ____(_Backend): backend_version = mpl.__version__ FigureCanvas = FigureCanvasSVG
_BackendSVG
python
openai__openai-python
src/openai/types/shared/response_format_text_grammar.py
{ "start": 202, "end": 418 }
class ____(BaseModel): grammar: str """The custom grammar for the model to follow.""" type: Literal["grammar"] """The type of response format being defined. Always `grammar`."""
ResponseFormatTextGrammar
python
pandas-dev__pandas
pandas/core/arrays/sparse/array.py
{ "start": 7467, "end": 65739 }
class ____(OpsMixin, PandasObject, ExtensionArray): """ An ExtensionArray for storing sparse data. SparseArray efficiently stores data with a high frequency of a specific fill value (e.g., zeros), saving memory by only retaining non-fill elements and their indices. This class is particularly us...
SparseArray
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 153183, "end": 153615 }
class ____(Buffer, Operation): # An operation that produces a single output buffer def get_outputs(self) -> list[Buffer]: return [self] def get_defining_op(self) -> Operation: return self # Skip implementation in Buffer get_operation_name = Operation.get_operation_name def __p...
OperationBuffer
python
astropy__astropy
astropy/modeling/tabular.py
{ "start": 786, "end": 12603 }
class ____(Model): """ Returns an interpolated lookup table value. Parameters ---------- points : tuple of ndarray of float, optional The points defining the regular grid in n dimensions. ndarray must have shapes (m1, ), ..., (mn, ), lookup_table : array-like The data on...
_Tabular
python
getsentry__sentry
tests/sentry/core/endpoints/test_project_keys.py
{ "start": 5476, "end": 9258 }
class ____(APITestCase): def test_simple(self) -> None: project = self.create_project() self.login_as(user=self.user) url = reverse( "sentry-api-0-project-keys", kwargs={ "organization_id_or_slug": project.organization.slug, "project_id...
CreateProjectKeyTest
python
python__mypy
mypy/stubgen.py
{ "start": 59444, "end": 78478 }
class ____(mypy.traverser.TraverserVisitor): def __init__(self) -> None: self.results: list[tuple[str, Expression, Type | None]] = [] def visit_assignment_stmt(self, o: AssignmentStmt) -> None: lvalue = o.lvalues[0] if ( isinstance(lvalue, MemberExpr) and isinsta...
SelfTraverser
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 186256, "end": 206133 }
class ____(QueryTest, AssertsCompiledSQL): __dialect__ = "default" def test_needs_text(self): User = self.classes.User assert_raises_message( sa_exc.ArgumentError, "Textual SQL expression", fixture_session().query(User).from_statement, "select * ...
TextTest
python
keras-team__keras
keras/src/metrics/f_score_metrics.py
{ "start": 9225, "end": 11743 }
class ____(FBetaScore): r"""Computes F-1 Score. Formula: ```python f1_score = 2 * (precision * recall) / (precision + recall) ``` This is the harmonic mean of precision and recall. Its output range is `[0, 1]`. It works for both multi-class and multi-label classification. Args: ...
F1Score
python
pytest-dev__pytest
testing/test_tmpdir.py
{ "start": 1016, "end": 1441 }
class ____: basetemp: str | Path @property def trace(self): return self def get(self, key): return lambda *k: None def getini(self, name): if name == "tmp_path_retention_count": return 3 elif name == "tmp_path_retention_policy": return "all"...
FakeConfig
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 338423, "end": 339134 }
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("EnterpriseServerUserAccountsUploadEdge"), graphql_name="e...
EnterpriseServerUserAccountsUploadConnection
python
langchain-ai__langchain
libs/core/tests/unit_tests/test_tools.py
{ "start": 33106, "end": 33322 }
class ____(BaseTool): name: str = "Foo" description: str = "Foo" @override def _run(self, bar: Any, bar_config: RunnableConfig, **kwargs: Any) -> Any: return assert_bar(bar, bar_config)
FooBase
python
kamyu104__LeetCode-Solutions
Python/reorganize-string.py
{ "start": 108, "end": 917 }
class ____(object): def reorganizeString(self, S): """ :type S: str :rtype: str """ counts = collections.Counter(S) if any(v > (len(S)+1)/2 for k, v in counts.iteritems()): return "" result = [] max_heap = [] for k, v in counts.ite...
Solution
python
walkccc__LeetCode
solutions/1909. Remove One Element to Make the Array Strictly Increasing/1909.py
{ "start": 0, "end": 368 }
class ____: def canBeIncreasing(self, nums: list[int]) -> bool: removed = False for i in range(1, len(nums)): if nums[i - 1] >= nums[i]: if removed: return False removed = True # Remove nums[i - 1]. if i > 1 and nums[i - 2] >= nums[i]: nums[i] = nums[i - 1] ...
Solution
python
scrapy__scrapy
tests/test_utils_request.py
{ "start": 8023, "end": 8282 }
class ____: def test_fingerprint(self): crawler = get_crawler() request = Request("https://example.com") assert crawler.request_fingerprinter.fingerprint(request) == fingerprint( request )
TestRequestFingerprinter
python
scikit-learn__scikit-learn
sklearn/preprocessing/_label.py
{ "start": 1000, "end": 5085 }
class ____(TransformerMixin, BaseEstimator, auto_wrap_output_keys=None): """Encode target labels with value between 0 and n_classes-1. This transformer should be used to encode target values, *i.e.* `y`, and not the input `X`. Read more in the :ref:`User Guide <preprocessing_targets>`. .. version...
LabelEncoder
python
django__django
django/test/utils.py
{ "start": 12956, "end": 15394 }
class ____: """ A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kw...
TestContextDecorator