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
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_chartarea03.py
{ "start": 315, "end": 1735 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_chartarea03.xlsx") def test_create_file(self): """Test XlsxWriter chartarea properties.""" workbook = Workbook(self.got_file...
TestCompareXLSXFiles
python
pennersr__django-allauth
allauth/account/views.py
{ "start": 8004, "end": 8359 }
class ____(SignupView): template_name = "account/signup_by_passkey." + app_settings.TEMPLATE_EXTENSION def get_form_kwargs(self): ret = super().get_form_kwargs() ret["by_passkey"] = True return ret signup_by_passkey = SignupByPasskeyView.as_view() @method_decorator(login_not_require...
SignupByPasskeyView
python
yandexdataschool__Practical_RL
week06_policy_based/atari_wrappers.py
{ "start": 417, "end": 1359 }
class ____(Wrapper): """Sets done flag to true when agent dies.""" def __init__(self, env): super().__init__(env) self.lives = 0 self.real_done = True def step(self, action): obs, reward, terminated, truncated, info = self.env.step(action) self.real_done = terminate...
EpisodicLife
python
django__django
django/db/migrations/operations/models.py
{ "start": 31349, "end": 31505 }
class ____(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower()
IndexOperation
python
networkx__networkx
networkx/utils/heaps.py
{ "start": 3216, "end": 8383 }
class ____(MinHeap): """A pairing heap.""" class _Node(MinHeap._Item): """A node in a pairing heap. A tree in a pairing heap is stored using the left-child, right-sibling representation. """ __slots__ = ("left", "next", "prev", "parent") def __init__(self, key...
PairingHeap
python
google__pytype
pytype_extensions/instrumentation_for_testing.py
{ "start": 1727, "end": 1905 }
class ____(Generic[_T]): def __init__(self, production_type: _T): pass def __call__(self, instrumented_type: Any) -> _T: return instrumented_type
SealAsProductionType
python
getsentry__sentry
src/sentry/preprod/api/validators.py
{ "start": 152, "end": 3007 }
class ____(serializers.Serializer[Any]): """Validator for preprod list builds endpoint parameters.""" app_id = serializers.CharField(required=False, help_text="Filter by app identifier") state = serializers.ChoiceField( choices=PreprodArtifact.ArtifactState.as_choices(), required=False, ...
PreprodListBuildsValidator
python
scipy__scipy
scipy/_lib/_docscrape.py
{ "start": 2677, "end": 18075 }
class ____(Mapping): """Parses a numpydoc string to an abstract representation Instances define a mapping from section title to structured data. """ sections = { "Signature": "", "Summary": [""], "Extended Summary": [], "Parameters": [], "Attributes": [], ...
NumpyDocString
python
sympy__sympy
sympy/physics/mechanics/loads.py
{ "start": 218, "end": 819 }
class ____(ABC, namedtuple('LoadBase', ['location', 'vector'])): """Abstract base class for the various loading types.""" def __add__(self, other): raise TypeError(f"unsupported operand type(s) for +: " f"'{self.__class__.__name__}' and " f"'{other.__clas...
LoadBase
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 24733, "end": 25126 }
class ____(Interface): """A policy for generating URLs to static assets""" def add(config, name, spec, **extra): """Add a new static info registration""" def generate(path, request, **kw): """Generate a URL for the given path""" def add_cache_buster(config, spec, cache_buster): ...
IStaticURLInfo
python
pytorch__pytorch
torch/distributed/elastic/events/api.py
{ "start": 1874, "end": 3313 }
class ____: """ Dataclass to represent any rendezvous event. Args: name: Event name. (E.g. Current action being performed) run_id: The run id of the rendezvous message: The message describing the event hostname: Hostname of the node pid: The process id of the node ...
RdzvEvent
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 321, "end": 1247 }
class ____: """Unit tests for OCIAuth class.""" def setup_method(self): self.signer_mock = Mock() self.oci_auth = OCIAuth(self.signer_mock) def test_auth_flow(self): """Ensures that the auth_flow signs the request correctly.""" request = httpx.Request("POST", "https://examp...
TestOCIAuth
python
celery__celery
t/unit/app/test_amqp.py
{ "start": 7193, "end": 7494 }
class ____: def setup_method(self): self.simple_message = self.app.amqp.as_task_v2( uuid(), 'foo', create_sent_event=True, ) self.simple_message_no_sent_event = self.app.amqp.as_task_v2( uuid(), 'foo', create_sent_event=False, )
test_AMQP_Base
python
fsspec__filesystem_spec
fsspec/implementations/reference.py
{ "start": 47349, "end": 48814 }
class ____(AbstractBufferedFile): def __init__( self, fs, path, mode="rb", block_size="default", autocommit=True, cache_type="readahead", cache_options=None, size=None, **kwargs, ): super().__init__( fs, ...
ReferenceFile
python
streamlit__streamlit
lib/streamlit/elements/lib/column_types.py
{ "start": 4323, "end": 4388 }
class ____(TypedDict): type: Literal["image"]
ImageColumnConfig
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 1353, "end": 2027 }
class ____(Benchmark): param_names = ['sparse_type', 'format', 'XY', 'op'] params = [ ['spmatrix', 'sparray'], ['csr', 'csc', 'coo', 'dia'], ['AA', 'AB', 'BA', 'BB'], ['__add__', '__sub__', 'multiply', '__mul__'] ] def setup(self, sparse_type, format, XY, op): ma...
Arithmetic
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_tp_integration.py
{ "start": 1408, "end": 2412 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.net1 = torch.nn.Linear(5, 8) self.relu = torch.nn.ReLU() self.net2 = torch.nn.Linear(8, 4) self.net3 = torch.nn.Linear(4, 12) def forward(self, x): return self.net3(self.net2(self.re...
SimpleModel
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/execution/executors/gevent.py
{ "start": 118, "end": 495 }
class ____(object): def __init__(self): self.jobs = [] def wait_until_finished(self): [j.join() for j in self.jobs] # gevent.joinall(self.jobs) def execute(self, fn, *args, **kwargs): promise = Promise() job = gevent.spawn(process, promise, fn, args, kwargs) ...
GeventExecutor
python
astropy__astropy
astropy/io/ascii/sextractor.py
{ "start": 295, "end": 4534 }
class ____(core.BaseHeader): """Read the header from a file produced by SExtractor.""" comment = r"^\s*#\s*\S\D.*" # Find lines that don't have "# digit" def get_cols(self, lines): """ Initialize the header Column objects from the table ``lines`` for a SExtractor header. The SExt...
SExtractorHeader
python
pytorch__pytorch
torch/testing/_internal/common_subclass.py
{ "start": 3161, "end": 4100 }
class ____(WrapperTensor): @classmethod def get_wrapper_properties(cls, t, requires_grad=False): return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "strides"} def __init__(self, t, requires_grad=False): self.t = t @classmethod def __torch_dispatch__(cls, fu...
WrapperTensorWithCustomStrides
python
PyCQA__pylint
pylint/typing.py
{ "start": 2576, "end": 3051 }
class ____(TypedDict, total=False): """All allowed keys in the extra options for message definitions.""" scope: str old_names: list[tuple[str, str]] maxversion: tuple[int, int] minversion: tuple[int, int] shared: bool default_enabled: bool MessageDefinitionTuple = ( tuple[str, str, st...
ExtraMessageOptions
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 12757, "end": 13704 }
class ____(TestEdgeDataView): @classmethod def setup_class(cls): cls.G = nx.path_graph(9, create_using=nx.MultiGraph()) cls.eview = nx.reportviews.MultiEdgeView def modify_edge(self, G, e, **kwds): G._adj[e[0]][e[1]][0].update(kwds) def test_repr(self): ev = self.eview(...
TestMultiEdgeDataView
python
doocs__leetcode
solution/3700-3799/3731.Find Missing Elements/Solution.py
{ "start": 0, "end": 201 }
class ____: def findMissingElements(self, nums: List[int]) -> List[int]: mn, mx = min(nums), max(nums) s = set(nums) return [x for x in range(mn + 1, mx) if x not in s]
Solution
python
joke2k__faker
faker/providers/lorem/ja_JP/__init__.py
{ "start": 68, "end": 3547 }
class ____(LoremProvider): """Implement lorem provider for ``ja_JP`` locale.""" word_connector = "" sentence_punctuation = "。" word_list = ( "コミュニティ", "隠す", "葉", "陶器", "錯覚", "バーゲン", "リニア", "コーラス", "仕上げ", "叔父", "移動",...
Provider
python
pytest-dev__pytest-xdist
src/xdist/looponfail.py
{ "start": 8221, "end": 10144 }
class ____: def __init__(self, rootdirlist: Sequence[Path]) -> None: self.rootdirlist = rootdirlist self.statcache: dict[Path, os.stat_result] = {} self.check() # snapshot state def fil(self, p: Path) -> bool: return p.is_file() and not p.name.startswith(".") and p.suffix != "....
StatRecorder
python
plotly__plotly.py
plotly/graph_objs/scattermapbox/selected/_marker.py
{ "start": 233, "end": 3615 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattermapbox.selected" _path_str = "scattermapbox.selected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of selected points. The 'color' property is a color ...
Marker
python
spyder-ide__spyder
spyder/plugins/mainmenu/api.py
{ "start": 4119, "end": 4311 }
class ____(SpyderMenu): """ Spyder main window application menu. This class provides application menus with some predefined functionality. """ APP_MENU = True
ApplicationMenu
python
huggingface__transformers
src/transformers/models/ovis2/modular_ovis2.py
{ "start": 2893, "end": 3584 }
class ____(SiglipEncoder): def __init__(self, config: Ovis2VisionConfig): super().__init__(config) self.layers = nn.ModuleList([Ovis2VisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) @can_return_tuple @auto_docstring def forward( self, inputs_embeds, ...
Ovis2VisionEncoder
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 8055, "end": 8243 }
class ____(graphene.InputObjectType): run_id = graphene.String() run_uuid = graphene.String() path = graphene.String() page_token = graphene.String()
MlflowListArtifactsInput
python
protocolbuffers__protobuf
python/google/protobuf/descriptor.py
{ "start": 17951, "end": 28758 }
class ____(DescriptorBase): """Descriptor for a single field in a .proto file. Attributes: name (str): Name of this field, exactly as it appears in .proto. full_name (str): Name of this field, including containing scope. This is particularly relevant for extensions. index (int): Dense, 0-indexed...
FieldDescriptor
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 25325, "end": 25940 }
class ____(MixinSequenceOfValues): """ Facet labels along the horizontal axis Parameters ---------- theme_element : element_text """ _omit = ["margin", "ha", "va"] def apply_figure(self, figure: Figure, targets: ThemeTargets): super().apply_figure(figure, targets) if t...
strip_text_x
python
docker__docker-py
tests/integration/api_container_test.py
{ "start": 28157, "end": 28729 }
class ____(BaseAPIIntegrationTest): def test_rename_container(self): version = self.client.version()['Version'] name = 'hong_meiling' res = self.client.create_container(TEST_IMG, 'true') assert 'Id' in res self.tmp_containers.append(res['Id']) self.client.rename(res, ...
RenameContainerTest
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_side_effects.py
{ "start": 291, "end": 1628 }
class ____(Generic[TYPE]): """ Simple class with slots """ __slots__ = ['value'] def __init__(self, value): self.value = value # tests/functional/d/dangerous_default_value_py30.py def function4(value=set()): # [dangerous-default-value] """set is mutable and dangerous.""" return value def...
Cls
python
openai__gym
gym/wrappers/pixel_observation.py
{ "start": 263, "end": 8049 }
class ____(gym.ObservationWrapper): """Augment observations by pixel values. Observations of this wrapper will be dictionaries of images. You can also choose to add the observation of the base environment to this dictionary. In that case, if the base environment has an observation space of type :class:...
PixelObservationWrapper
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/cloud_run.py
{ "start": 1245, "end": 1393 }
class ____(Enum): """Enum to represent the status of a job run.""" SUCCESS = "Success" FAIL = "Fail" TIMEOUT = "Timeout"
RunJobStatus
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 30506, "end": 31097 }
class ____(PlotActionTool): ''' *toolbar icon*: |reset_icon| The reset tool is an action. When activated in the toolbar, the tool resets the data bounds of the plot to their values when the plot was initially created. .. |reset_icon| image:: /_images/icons/reset.svg :height: 24px :...
ResetTool
python
tensorflow__tensorflow
tensorflow/python/saved_model/keras_injection_test.py
{ "start": 936, "end": 1434 }
class ____(tf.test.TestCase): def test_keras_optimizer_injected(self): save_path = test.test_src_dir_path( 'cc/saved_model/testdata/OptimizerSlotVariableModule') _ = tf.saved_model.load(save_path) # Make sure keras optimizers are registed without accessing keras code # when loading a model wi...
KerasInjectionTest
python
pytest-dev__pytest
src/_pytest/fixtures.py
{ "start": 47196, "end": 48789 }
class ____: scope: _ScopeName | Callable[[str, Config], _ScopeName] params: tuple[object, ...] | None autouse: bool = False ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None name: str | None = None _ispytest: dataclasses.InitVar[bool] = False def __post_init__(s...
FixtureFunctionMarker
python
boto__boto3
boto3/dynamodb/conditions.py
{ "start": 5771, "end": 5888 }
class ____(ConditionBase): expression_operator = 'contains' expression_format = '{operator}({0}, {1})'
Contains
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 695103, "end": 695561 }
class ____(sgqlc.types.Type): """Autogenerated return type of MergeBranch""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "merge_commit") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutat...
MergeBranchPayload
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_C.py
{ "start": 15535, "end": 17137 }
class ____(Benchmark): r""" Csendes objective function. This class defines the Csendes [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Csendes}}(x) = \sum_{i=1}^n x_i^6 \left[ 2 + \sin \left( \frac{1}{x_i} \right )...
Csendes
python
google__pytype
pytype/tests/test_typing_self.py
{ "start": 155, "end": 7679 }
class ____(test_base.BaseTest): """Tests for typing.Self.""" def test_instance_method_return(self): self.Check(""" from typing_extensions import Self class A: def f(self) -> Self: return self class B(A): pass assert_type(A().f(), A) assert_type(B().f(), B...
SelfTest
python
sqlalchemy__sqlalchemy
test/ext/test_extendedattr.py
{ "start": 1683, "end": 2441 }
class ____(instrumentation.InstrumentationManager): def instrument_attribute(self, class_, key, attr): pass def install_descriptor(self, class_, key, attr): pass def uninstall_descriptor(self, class_, key): pass def instrument_collection_class(self, class_, key, collection_cla...
MyTypesManager
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 77939, "end": 78366 }
class ____( BlackwellTMATemplateConfigMixin, CUDAConfigHeuristic ): """Blackwell Persistent TMA template""" def __init__(self) -> None: super().__init__() self.mm_configs = self.blackwell_persistent_mm_configs @register_template_heuristic( persistent_tma_mm_template.uid, "cuda", ...
CUDABlackwellPersistentTMATemplateConfigHeuristic
python
doocs__leetcode
solution/2600-2699/2613.Beautiful Pairs/Solution.py
{ "start": 0, "end": 1516 }
class ____: def beautifulPair(self, nums1: List[int], nums2: List[int]) -> List[int]: def dist(x1: int, y1: int, x2: int, y2: int) -> int: return abs(x1 - x2) + abs(y1 - y2) def dfs(l: int, r: int): if l >= r: return inf, -1, -1 m = (l + r) >> 1 ...
Solution
python
pallets__click
src/click/_utils.py
{ "start": 69, "end": 943 }
class ____(enum.Enum): """Enum used to define sentinel values. .. seealso:: `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_. """ UNSET = object() FLAG_NEEDS_VALUE = object() def __repr__(self) -> str: return f"{self.__class__.__name__}.{self.name}" UNSET = ...
Sentinel
python
pennersr__django-allauth
allauth/headless/account/views.py
{ "start": 4821, "end": 7234 }
class ____(APIView): input_class = VerifyEmailInput def handle(self, request, *args, **kwargs): self.stage = LoginStageController.enter(request, EmailVerificationStage.key) if ( not self.stage and account_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED and not re...
VerifyEmailView
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 57430, "end": 57644 }
class ____(_CudaLegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal() return self._dtype @classproperty def _dtype(self): return torch.bool
BoolStorage
python
django__django
django/contrib/admin/templatetags/base.py
{ "start": 100, "end": 1465 }
class ____(InclusionNode): """ Template tag that allows its template to be overridden per model, per app, or globally. """ def __init__(self, parser, token, func, template_name, takes_context=True): self.template_name = template_name params, varargs, varkw, defaults, kwonly, kwonly_...
InclusionAdminNode
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/package_entry.py
{ "start": 634, "end": 1742 }
class ____: namespace: str name: str @property def package(self) -> str: return self.namespace.split(".")[0] def to_typename(self) -> str: return f"{self.namespace}.{self.name}" @staticmethod def is_valid_typename(typename: str) -> bool: """Check if the typename is...
EnvRegistryKey
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_init.py
{ "start": 21083, "end": 26773 }
class ____(FSDPTestMultiThread): @property def world_size(self) -> int: return 2 @skip_if_lt_x_gpu(1) def test_fully_shard_is_root(self): """ Tests that ``_is_root`` is set correctly after lazy initialization. FSDP(model( 0: MLP(FSDP(in_proj), FSDP(out_proj)...
TestFullyShardLazyInit
python
ipython__ipython
tests/fake_llm.py
{ "start": 344, "end": 2536 }
class ____(BaseProvider, FakeListLLM): # type: ignore[misc, valid-type] id = "my_provider" name = "My Provider" model_id_key = "model" models = ["model_a"] def __init__(self, **kwargs): kwargs["responses"] = ["This fake response will not be used for completion"] kwargs["model_id"] ...
FibonacciCompletionProvider
python
scipy__scipy
scipy/ndimage/tests/test_filters.py
{ "start": 4714, "end": 111097 }
class ____: def _validate_complex(self, xp, array, kernel, type2, mode='reflect', cval=0, check_warnings=True): # utility for validating complex-valued correlations real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype expected = _complex_correlate( xp...
TestNdimageFilters
python
ansible__ansible
test/units/modules/test_known_hosts.py
{ "start": 306, "end": 4319 }
class ____(unittest.TestCase): def _create_file(self, content): tmp_file = tempfile.NamedTemporaryFile(prefix='ansible-test-', suffix='-known_hosts', delete=False) tmp_file.write(to_bytes(content)) tmp_file.close() self.addCleanup(os.unlink, tmp_file.name) return tmp_file.na...
KnownHostsDiffTestCase
python
pytorch__pytorch
test/cpp_api_parity/sample_module.py
{ "start": 392, "end": 3462 }
class ____(torch.nn.Module): def __init__(self, has_parity, has_submodule): super().__init__() self.has_parity = has_parity if has_submodule: self.submodule = SampleModule(self.has_parity, False) self.has_submodule = has_submodule self.register_parameter("param",...
SampleModule
python
modin-project__modin
modin/pandas/accessor.py
{ "start": 6305, "end": 14422 }
class ____: """ Namespace class for accessing additional Modin functions that are not available in pandas. Parameters ---------- data : DataFrame or Series Object to operate on. """ _data: Union[DataFrame, Series] def __init__(self, data: Union[DataFrame, Series]): sel...
ModinAPI
python
Pylons__pyramid
tests/test_integration.py
{ "start": 11547, "end": 12210 }
class ____(IntegrationBase, unittest.TestCase): package = 'tests.pkgs.fixtureapp' def test_another(self): res = self.testapp.get('/another.html', status=200) self.assertEqual(res.body, b'fixture') def test_root(self): res = self.testapp.get('/', status=200) self.assertEqual...
TestFixtureApp
python
mlflow__mlflow
mlflow/tracing/trace_manager.py
{ "start": 1661, "end": 8139 }
class ____: """ Manage spans and traces created by the tracing system in memory. """ _instance_lock = threading.RLock() _instance = None @classmethod def get_instance(cls): if cls._instance is None: with cls._instance_lock: if cls._instance is None: ...
InMemoryTraceManager
python
getsentry__sentry
tests/sentry/seer/explorer/test_tools.py
{ "start": 44210, "end": 51540 }
class ____(APITransactionTestCase): def test_get_repository_definition_success(self): """Test successful repository lookup""" Repository.objects.create( organization_id=self.organization.id, name="getsentry/seer", provider="integrations:github", extern...
TestGetRepositoryDefinition
python
lazyprogrammer__machine_learning_examples
rl2/cartpole/q_learning.py
{ "start": 2308, "end": 4731 }
class ____: def __init__(self, env, feature_transformer): self.env = env self.models = [] self.feature_transformer = feature_transformer for i in range(env.action_space.n): model = SGDRegressor(feature_transformer.dimensions) self.models.append(model) def predict(self, s): X = self....
Model
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 66968, "end": 68325 }
class ____: def test_laplace(self): # test against Laplace (special case for kappa=1) points = np.array([1, 2, 3]) pdf1 = stats.laplace_asymmetric.pdf(points, 1) pdf2 = stats.laplace.pdf(points) assert_allclose(pdf1, pdf2) def test_asymmetric_laplace_pdf(self): #...
TestLaplaceasymmetric
python
pytorch__pytorch
torch/_dynamo/bytecode_transformation.py
{ "start": 1991, "end": 3811 }
class ____: """A mutable version of dis.Instruction""" opcode: int opname: str arg: Optional[int] argval: Any offset: Optional[int] = None starts_line: Optional[int] = None is_jump_target: bool = False positions: Optional["dis.Positions"] = None # extra fields to make modificati...
Instruction
python
tornadoweb__tornado
tornado/test/httpclient_test.py
{ "start": 2220, "end": 2450 }
class ____(RequestHandler): def get(self, count): count = int(count) if count > 0: self.redirect(self.reverse_url("countdown", count - 1)) else: self.write("Zero")
CountdownHandler
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zenloop/source_zenloop/streams.py
{ "start": 6215, "end": 7159 }
class ____(ChildStreamMixin, ZenloopStream): # API Doc: https://docs.zenloop.com/reference/get-list-of-properties primary_key = "id" has_date_param = False extra_params = {"page": "1"} parent_stream_class = Surveys def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Ma...
Properties
python
scrapy__scrapy
tests/AsyncCrawlerProcess/twisted_reactor_custom_settings_same.py
{ "start": 63, "end": 254 }
class ____(scrapy.Spider): name = "asyncio_reactor1" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", }
AsyncioReactorSpider1
python
dateutil__dateutil
src/dateutil/tz/win.py
{ "start": 8730, "end": 12935 }
class ____(tzwinbase): """ Class representing the local time zone information in the Windows registry While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` module) to retrieve time zone information, ``tzwinlocal`` retrieves the rules directly from the Windows registry and creat...
tzwinlocal
python
doocs__leetcode
solution/1200-1299/1206.Design Skiplist/Solution.py
{ "start": 0, "end": 151 }
class ____: __slots__ = ['val', 'next'] def __init__(self, val: int, level: int): self.val = val self.next = [None] * level
Node
python
pytorch__pytorch
torch/_dynamo/variables/base.py
{ "start": 5908, "end": 6504 }
class ____(AttributeMutation): """ This case of VariableTracker.mutation_type marker indicates 1. Dynamo allows mutation on the value's attributes. 2. The value exists before Dynamo tracing started. For instance, Dynamo could model a pre-existing object with this marker, indicating that if we e...
AttributeMutationExisting
python
tornadoweb__tornado
maint/test/redbot/red_test.py
{ "start": 718, "end": 960 }
class ____(RequestHandler): @asynchronous @gen.engine def get(self): self.write('hello ') yield gen.Task(self.flush) self.write('world') yield gen.Task(self.flush) self.finish()
ChunkedHandler
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/validators/base/detector.py
{ "start": 1310, "end": 10535 }
class ____(CamelSnakeSerializer): enforce_single_datasource = False """ Set to True in subclasses to enforce that only a single data source can be configured. This prevents invalid configurations for detector types that don't support multiple data sources. """ name = serializers.CharField( ...
BaseDetectorTypeValidator
python
spack__spack
lib/spack/spack/util/windows_registry.py
{ "start": 15287, "end": 15529 }
class ____(RegistryError): """Runtime Error describing issue with invalid key access to Windows registry""" def __init__(self, key): message = f"Cannot query invalid key: {key}" super().__init__(message)
InvalidKeyError
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/context.py
{ "start": 13866, "end": 14818 }
class ____: """Wrapper to access Variable values in template.""" def __init__(self, deserialize_json: bool) -> None: self._deserialize_json = deserialize_json def __eq__(self, other): if not isinstance(other, VariableAccessor): return False # All instances of VariableAc...
VariableAccessor
python
rushter__MLAlgorithms
mla/knn.py
{ "start": 1682, "end": 2079 }
class ____(KNNBase): """Nearest neighbors classifier. Note: if there is a tie for the most common label among the neighbors, then the predicted label is arbitrary.""" def aggregate(self, neighbors_targets): """Return the most common target label.""" most_common_label = Counter(neighbo...
KNNClassifier
python
django__django
django/contrib/admin/utils.py
{ "start": 17193, "end": 22002 }
class ____(Exception): pass def get_model_from_relation(field): if hasattr(field, "path_infos"): return field.path_infos[-1].to_opts.model else: raise NotRelationField def reverse_field_path(model, path): """Create a reversed field path. E.g. Given (Order, "user__groups"), r...
NotRelationField
python
Textualize__rich
benchmarks/benchmarks.py
{ "start": 1828, "end": 2163 }
class ____: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) def time_wrapping_unicode_heavy_warm_cache(self): for _ in range(20): Text(snippets.UNICODE_HEAVY_TEXT).wrap(self.console, 12, overflow="fold") ...
TextHotCacheSuite
python
numpy__numpy
numpy/_build_utils/tempita/_tempita.py
{ "start": 13216, "end": 14008 }
class ____(dict): def __init__(self, **kw): for name, value in kw.items(): setattr(self, name, value) def __setattr__(self, name, value): self[name] = value def __getattr__(self, name): try: return self[name] except KeyError: raise Attrib...
bunch
python
conda__conda
conda/auxlib/entity.py
{ "start": 17704, "end": 17869 }
class ____(Field): _type = str def box(self, instance, instance_type, val): return str(val) if isinstance(val, NumberField._type) else val
StringField
python
ray-project__ray
doc/source/serve/doc_code/http_guide/http_guide.py
{ "start": 533, "end": 968 }
class ____: @app.get("/") def root(self): return "Hello, world!" serve.run(MyFastAPIDeployment.bind(), route_prefix="/hello") resp = requests.get("http://localhost:8000/hello") assert resp.json() == "Hello, world!" # __end_fastapi__ # __begin_fastapi_multi_routes__ import ray import requests from fa...
MyFastAPIDeployment
python
rq__rq
tests/test_cron_job.py
{ "start": 166, "end": 12641 }
class ____(RQTestCase): """Tests for the CronJob class""" def setUp(self): super().setUp() self.queue = Queue(connection=self.connection) def test_cron_job_initialization(self): """CronJob correctly initializes with the provided parameters""" # Test with minimum required pa...
TestCronJob
python
nedbat__coveragepy
coverage/files.py
{ "start": 7688, "end": 8604 }
class ____: """A matcher for modules in a tree.""" def __init__(self, module_names: Iterable[str], name: str = "unknown") -> None: self.modules = list(module_names) self.name = name def __repr__(self) -> str: return f"<ModuleMatcher {self.name} {self.modules!r}>" def info(self...
ModuleMatcher
python
getsentry__sentry
src/sentry/integrations/github/integration.py
{ "start": 45943, "end": 50059 }
class ____: def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase: self.active_user_organization = determine_active_organization(request) if self.active_user_organization is None: return error( request, None, ...
GithubOrganizationSelection
python
ipython__ipython
IPython/extensions/deduperreload/deduperreload.py
{ "start": 3338, "end": 4481 }
class ____(ast.NodeVisitor): def __init__(self) -> None: self.is_constexpr = True self._allow_builtins_exceptions = True @contextlib.contextmanager def disallow_builtins_exceptions(self) -> Generator[None, None, None]: prev_allow = self._allow_builtins_exceptions self._allow...
ConstexprDetector
python
allegroai__clearml
clearml/backend_api/services/v2_20/projects.py
{ "start": 82731, "end": 86232 }
class ____(Request): """ Get a list of all hyper parameter sections and names used in tasks within the given project. :param project: Project ID :type project: str :param page: Page number :type page: int :param page_size: Page size :type page_size: int :param include_subprojects: I...
GetHyperParametersRequest
python
anthropics__anthropic-sdk-python
src/anthropic/types/text_block_param.py
{ "start": 374, "end": 659 }
class ____(TypedDict, total=False): text: Required[str] type: Required[Literal["text"]] cache_control: Optional[CacheControlEphemeralParam] """Create a cache control breakpoint at this content block.""" citations: Optional[Iterable[TextCitationParam]]
TextBlockParam
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 941466, "end": 942214 }
class ____(sgqlc.types.relay.Connection): """The connection type for RepositoryRule.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("RepositoryRuleEdge"), graphql_name="edges") """A list of edges.""" ...
RepositoryRuleConnection
python
streamlit__streamlit
lib/tests/streamlit/elements/divider_test.py
{ "start": 919, "end": 2345 }
class ____(DeltaGeneratorTestCase): """Test ability to marshall divider protos.""" def test_divider(self): st.divider() c = self.get_delta_from_queue().new_element assert c.markdown.body == "---" @parameterized.expand( [ (500, WidthConfigFields.PIXEL_WIDTH, 500...
DividerTest
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 12263, "end": 12365 }
class ____(models.Model): books = models.ForeignKey(HardbackBook, on_delete=models.CASCADE)
Bookcase
python
pytorch__pytorch
torch/package/package_exporter.py
{ "start": 1186, "end": 1955 }
class ____(Enum): """Represents one of the actions that :class:`PackageExporter` can take on a module. See :meth:`PackageExporter.extern` and friends for a description of what the actions do. """ INTERN = 1 EXTERN = 2 MOCK = 3 DENY = 4 # Special case: when a module is mocked, PackageEx...
_ModuleProviderAction
python
huggingface__transformers
src/transformers/models/falcon/modeling_falcon.py
{ "start": 55933, "end": 59639 }
class ____(FalconPreTrainedModel): def __init__(self, config: FalconConfig): super().__init__(config) self.num_labels = config.num_labels self.transformer = FalconModel(config) if getattr(config, "classifier_dropout", None) is not None: classifier_dropout = config.classi...
FalconForTokenClassification
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_userroles_index.py
{ "start": 170, "end": 1168 }
class ____(APITestCase): endpoint = "sentry-api-0-userroles" def setUp(self) -> None: super().setUp() self.user = self.create_user(is_superuser=True) self.login_as(user=self.user, superuser=True) self.add_user_permission(self.user, "users.admin") def test_fails_without_supe...
UserRolesTest
python
langchain-ai__langchain
libs/partners/anthropic/langchain_anthropic/chat_models.py
{ "start": 102564, "end": 112444 }
class ____(TypedDict): type: Literal["tool_use"] name: str input: dict id: str def _lc_tool_calls_to_anthropic_tool_use_blocks( tool_calls: list[ToolCall], ) -> list[_AnthropicToolUse]: return [ _AnthropicToolUse( type="tool_use", name=tool_call["name"], ...
_AnthropicToolUse
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_v2_func_graphs.py
{ "start": 1963, "end": 2131 }
class ____(ControlFlowFuncGraph): """FuncGraph for the body of tf.while_loop(). This is used to distinguish while bodies from other functions. """
WhileBodyFuncGraph
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 665, "end": 1731 }
class ____(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path, target=None): # Check if the import is the problematic one if fullname in redirect_imports: try: # Attempt to import the standalone module name = fullname.removeprefix("test.") ...
RedirectImportFinder
python
run-llama__llama_index
llama-index-core/llama_index/core/objects/tool_node_mapping.py
{ "start": 3873, "end": 5046 }
class ____(BaseQueryToolNodeMapping): """Simple query tool mapping.""" def __init__(self, objs: Optional[Sequence[QueryEngineTool]] = None) -> None: objs = objs or [] self._tools = {tool.metadata.name: tool for tool in objs} def validate_object(self, obj: QueryEngineTool) -> None: ...
SimpleQueryToolNodeMapping
python
apache__airflow
devel-common/src/tests_common/test_utils/mock_executor.py
{ "start": 1345, "end": 5307 }
class ____(BaseExecutor): """TestExecutor is used for unit testing purposes.""" supports_pickling = False mock_module_path = "mock.executor.path" mock_alias = "mock_executor" def __init__(self, do_update=True, *args, **kwargs): self.do_update = do_update self.callback_sink = MagicM...
MockExecutor
python
scrapy__scrapy
tests/test_pipeline_files.py
{ "start": 26337, "end": 27990 }
class ____: def setup_method(self): self.tempdir = mkdtemp() self.crawler = get_crawler(None, {"FILES_STORE": self.tempdir}) def teardown_method(self): rmtree(self.tempdir) def test_simple(self): class Pipeline(FilesPipeline): pass with warnings.catch_w...
TestBuildFromCrawler
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 65765, "end": 66171 }
class ____(GenericFunction[_T]): r"""Implement the ``CUBE`` grouping operation. This function is used as part of the GROUP BY of a statement, e.g. :meth:`_expression.Select.group_by`:: stmt = select( func.sum(table.c.value), table.c.col_1, table.c.col_2 ).group_by(func.cube(tab...
cube
python
getsentry__sentry
tests/sentry/web/frontend/test_error_500.py
{ "start": 142, "end": 357 }
class ____(TestCase): def test_renders(self) -> None: resp = self.client.get(reverse("error-500")) assert resp.status_code == 500 self.assertTemplateUsed(resp, "sentry/500.html")
Error500Test
python
pytorch__pytorch
torch/utils/data/sampler.py
{ "start": 3752, "end": 4234 }
class ____(Sampler[int]): r"""Samples elements sequentially, always in the same order. Args: data_source (Sized): data source to sample from. Must implement __len__. """ data_source: Sized def __init__(self, data_source: Sized) -> None: self.data_source = data_source def __it...
SequentialSampler
python
kamyu104__LeetCode-Solutions
Python/find-if-array-can-be-sorted.py
{ "start": 36, "end": 671 }
class ____(object): def canSortArray(self, nums): """ :type nums: List[int] :rtype: bool """ def popcount(x): return bin(x).count("1") left = mx = 0 for right in xrange(len(nums)): if right+1 != len(nums) and popcount(nums[right+1]...
Solution