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
rq__rq
rq/local.py
{ "start": 6745, "end": 12818 }
class ____: """Acts as a proxy for a werkzeug local. Forwards all operations to a proxied object. The only operations not supported for forwarding are right handed operands and any kind of assignment. Example usage:: from werkzeug.local import Local l = Local() # these are p...
LocalProxy
python
altair-viz__altair
tests/utils/test_core.py
{ "start": 1060, "end": 1168 }
class ____(FieldChannel, schemapi.SchemaBase): _schema = {json_schema_dict_str} _encoding_name = "x"
X
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/provision.py
{ "start": 738, "end": 17429 }
class ____: def __init__(self, decorator=None): self.fns = {} self.decorator = decorator @classmethod def init(cls, fn): return register().for_db("*")(fn) @classmethod def init_decorator(cls, decorator): return register(decorator).for_db("*") def for_db(self, *...
register
python
pypa__packaging
tests/test_metadata.py
{ "start": 10761, "end": 31352 }
class ____: def _invalid_with_cause( self, meta: metadata.Metadata, attr: str, cause: type[BaseException] | None = None, *, field: str | None = None, ) -> None: if field is None: field = attr with pytest.raises(metadata.InvalidMetadata)...
TestMetadata
python
scrapy__scrapy
tests/AsyncCrawlerProcess/twisted_reactor_asyncio.py
{ "start": 63, "end": 328 }
class ____(scrapy.Spider): name = "asyncio_reactor" process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } ) process.crawl(AsyncioReactorSpider) process.start()
AsyncioReactorSpider
python
ray-project__ray
python/ray/actor.py
{ "start": 2520, "end": 2710 }
class ____(Generic[_Ret, _T0]): def remote(self, __arg0: "Union[_T0, ObjectRef[_T0]]") -> "ObjectRef[_Ret]": ... def bind(self, __arg0: _T0) -> Any: ...
_RemoteMethod0
python
pdm-project__pdm
src/pdm/cli/commands/venv/utils.py
{ "start": 1828, "end": 2652 }
class ____(BaseProvider): """A Python provider for project venv pythons""" def __init__(self, project: Project) -> None: self.project = project @classmethod def create(cls) -> t.Self | None: return None def find_pythons(self) -> t.Iterable[PythonVersion]: for _, venv in it...
VenvProvider
python
euske__pdfminer
pdfminer/cmapdb.py
{ "start": 738, "end": 1173 }
class ____: debug = 0 def __init__(self, **kwargs): self.attrs = kwargs.copy() return def is_vertical(self): return self.attrs.get('WMode', 0) != 0 def set_attr(self, k, v): self.attrs[k] = v return def add_code2cid(self, code, cid): return d...
CMapBase
python
networkx__networkx
networkx/readwrite/tests/test_adjlist.py
{ "start": 2711, "end": 7601 }
class ____: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) cls.XG = nx.MultiGraph() cls.XG...
TestAdjlist
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/networks.py
{ "start": 22493, "end": 27653 }
class ____(nn.Module, Actor): MODEL_EXPORT_VERSION = 3 # Corresponds to ModelApiVersion.MLAgents2_0 def __init__( self, observation_specs: List[ObservationSpec], network_settings: NetworkSettings, action_spec: ActionSpec, conditional_sigma: bool = False, tanh_sq...
SimpleActor
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 16341, "end": 16632 }
class ____(PatternExpr): """ Capture an arg which will become an input to the handler. Args are passed in depth first order. """ def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: return Match(ctx, self, args=[node]) # matches anything
Arg
python
spyder-ide__spyder
spyder/utils/color_system.py
{ "start": 1620, "end": 1997 }
class ____: """ Group colors for light palette. It does not start with B0 because it doesn't use black. """ B10 = '#FF6700' B20 = '#FFB000' B30 = '#FFE600' B40 = '#7FDD05' B50 = '#00A585' B60 = '#22BCF2' B70 = '#1256CC' B80 = '#803AD0' B90 = '#B568F2' B100 = '#C...
GroupLight
python
ethereum__web3.py
web3/middleware/formatting.py
{ "start": 2763, "end": 7784 }
class ____(Web3MiddlewareBuilder): request_formatters: Formatters = None result_formatters: Formatters = None error_formatters: Formatters = None sync_formatters_builder: SYNC_FORMATTERS_BUILDER = None async_formatters_builder: ASYNC_FORMATTERS_BUILDER = None @staticmethod @curry def bu...
FormattingMiddlewareBuilder
python
huggingface__transformers
src/transformers/models/clvp/configuration_clvp.py
{ "start": 15038, "end": 19421 }
class ____(PreTrainedConfig): r""" [`ClvpConfig`] is the configuration class to store the configuration of a [`ClvpModelForConditionalGeneration`]. It is used to instantiate a CLVP model according to the specified arguments, defining the text model, speech model and decoder model configs. Instantiating ...
ClvpConfig
python
gevent__gevent
src/gevent/tests/test__threading.py
{ "start": 2434, "end": 2586 }
class ____(TestLockThread): def _spawn(self, func): return gevent.spawn(func) if __name__ == '__main__': greentest.main()
TestLockGreenlet
python
pytorch__pytorch
torch/export/graph_signature.py
{ "start": 3448, "end": 3614 }
class ____: gradients_to_parameters: dict[str, str] gradients_to_user_inputs: dict[str, str] loss_output: str @dataclasses.dataclass
ExportBackwardSignature
python
ray-project__ray
python/ray/util/actor_pool.py
{ "start": 195, "end": 14541 }
class ____: """Utility class to operate on a fixed pool of actors. Arguments: actors: List of Ray actor handles to use in this pool. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: ...
ActorPool
python
instagram__MonkeyType
monkeytype/stubs.py
{ "start": 24455, "end": 26251 }
class ____(Stub): def __init__( self, function_stubs: Optional[Iterable[FunctionStub]] = None, class_stubs: Optional[Iterable[ClassStub]] = None, imports_stub: Optional[ImportBlockStub] = None, typed_dict_class_stubs: Optional[Iterable[ClassStub]] = None, ) -> None: ...
ModuleStub
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/sentry_app_installation.py
{ "start": 793, "end": 1029 }
class ____(TypedDict): app: SentryAppInstallationAppResult organization: SentryAppInstallationOrganizationResult uuid: str status: str code: NotRequired[str] @register(SentryAppInstallation)
SentryAppInstallationResult
python
streamlit__streamlit
lib/tests/streamlit/delta_generator_test.py
{ "start": 28188, "end": 28798 }
class ____(DeltaGeneratorTestCase): def test_ids_are_diff_when_keys_are_diff(self): id1 = compute_and_register_element_id( "text_input", user_key="some_key1", label="Label #1", default="Value #1", key_as_main_identity=False, dg=None, ...
KeyWidgetIdTests
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 13164, "end": 19116 }
class ____(test_util.TensorFlowTestCase): _IND_2_5_6 = np.array( [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]], dtype=np.int64) _VAL_2_5_6 = np.array([0, 10, 13, 14, 32, 33], dtype=np.int32) _SHP_2_5_6 = np.array([2, 5, 6], dtype=np.int64) def _SparseTensor_2x5x6(self): re...
SparseResetShapeTest
python
doocs__leetcode
solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py
{ "start": 0, "end": 237 }
class ____: def checkIfExist(self, arr: List[int]) -> bool: s = set() for x in arr: if x * 2 in s or (x % 2 == 0 and x // 2 in s): return True s.add(x) return False
Solution
python
django__django
tests/file_storage/tests.py
{ "start": 23501, "end": 23910 }
class ____(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Append numbers to duplicate files rather than underscores, like Trac. """ basename, *ext = os.path.splitext(name) number = 2 while self.exists(name): name = "".join([ba...
CustomStorage
python
encode__django-rest-framework
tests/test_relations.py
{ "start": 1033, "end": 3388 }
class ____(APISimpleTestCase): def setUp(self): self.queryset = MockQueryset([ MockObject(pk=i, name=str(i)) for i in range(0, 1100) ]) self.monkeypatch = MonkeyPatch() def test_no_settings(self): # The default is 1,000, so sans settings it should be 1,000 plus one. ...
TestRelatedFieldHTMLCutoff
python
geekcomputers__Python
Colors/print_colors.py
{ "start": 13, "end": 400 }
class ____: CYAN = "\033[36m" GREEN = "\033[32m" YELLOW = "\033[33m" BLUE = "\033[34m" RED = "\033[31m" ENDC = "\033[0m" def printc(color, message): print(color + message + colors.ENDC) printc(colors.CYAN, sys.argv[1]) printc(colors.GREEN, sys.argv[1]) printc(colors.YELLOW, sys.argv[1]) ...
colors
python
pypa__pipenv
pipenv/vendor/plette/models/base.py
{ "start": 50, "end": 1450 }
class ____: def __init__(self, data): self.validate(data) self._data = data def __repr__(self): return "{0}({1!r})".format(type(self).__name__, self._data) def __eq__(self, other): if not isinstance(other, type(self)): raise TypeError( "cannot c...
DataModel
python
gevent__gevent
src/gevent/_tracer.py
{ "start": 575, "end": 4426 }
class ____(object): def __init__(self): # A counter, incremented by the greenlet trace function # we install on every greenlet switch. This is reset when the # periodic monitoring thread runs. self.greenlet_switch_counter = 0 # The greenlet last switched to. self.ac...
GreenletTracer
python
anthropics__anthropic-sdk-python
src/anthropic/pagination.py
{ "start": 2997, "end": 3720 }
class ____(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): data: List[_T] has_more: Optional[bool] = None next_page: Optional[str] = None @override def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] return data @override def ha...
AsyncTokenPage
python
streamlit__streamlit
lib/tests/streamlit/elements/iframe_test.py
{ "start": 2748, "end": 6897 }
class ____(DeltaGeneratorTestCase): """Test the streamlit.components.v1.iframe and html functions.""" def test_iframe_no_width_uses_stretch_width_config(self): """Test that components.iframe without width uses 'stretch' in width_config.""" st.components.v1.iframe("https://example.com") ...
IFrameComponentTest
python
doocs__leetcode
solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.py
{ "start": 0, "end": 340 }
class ____: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l = s = 0 ans = inf for r, x in enumerate(nums): s += x while s >= target: ans = min(ans, r - l + 1) s -= nums[l] l += 1 return 0 if ans ...
Solution
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 37827, "end": 38244 }
class ____(Projection): r"""Base class for quad cube projections. Quadrilateralized spherical cube (quad-cube) projections belong to the class of polyhedral projections in which the sphere is projected onto the surface of an enclosing polyhedron. The six faces of the quad-cube projections are numb...
QuadCube
python
automl__auto-sklearn
test/test_evaluation/test_test_evaluator.py
{ "start": 2703, "end": 2978 }
class ____: def __init__(self): self.info = {"task": MULTICLASS_CLASSIFICATION, "is_sparse": False} self.feat_type = { 0: "numerical", 1: "Numerical", 2: "numerical", 3: "numerical", }
DummyDatamanager
python
huggingface__transformers
examples/modular-transformers/modeling_super.py
{ "start": 1258, "end": 1981 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ SuperRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_...
SuperRMSNorm
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/shrinking/collection.py
{ "start": 649, "end": 3237 }
class ____(Shrinker): def setup( self, *, ElementShrinker, min_size, to_order=identity, from_order=identity ): self.ElementShrinker = ElementShrinker self.to_order = to_order self.from_order = from_order self.min_size = min_size def make_immutable(self, value): ...
Collection
python
huggingface__transformers
src/transformers/models/grounding_dino/modeling_grounding_dino.py
{ "start": 61294, "end": 66393 }
class ____(nn.Module): def __init__(self, config: GroundingDinoConfig): super().__init__() self.embed_dim = config.d_model # self-attention self.self_attn = GroundingDinoMultiheadAttention(config, num_attention_heads=config.decoder_attention_heads) self.dropout = config.dro...
GroundingDinoDecoderLayer
python
getsentry__sentry
src/sentry/integrations/pagerduty/integration.py
{ "start": 9280, "end": 10155 }
class ____: def get_app_url(self, account_name: str | None = None) -> str: if not account_name: account_name = "app" app_id = options.get("pagerduty.app-id") setup_url = absolute_uri("/extensions/pagerduty/setup/") return f"https://{account_name}.pagerduty.com/install/i...
PagerDutyInstallationRedirect
python
coleifer__peewee
tests/results.py
{ "start": 5607, "end": 5677 }
class ____(TestModel): key = TextField() ts = DateTimeField()
Reg
python
spyder-ide__spyder
spyder/api/utils.py
{ "start": 2453, "end": 4043 }
class ____(BaseABCMeta): """ Metaclass to mark abstract classes. Adds support for abstract attributes. If a class has abstract attributes and is instantiated, a NotImplementedError is raised. Usage ----- .. code-block:: python class MyABC(metaclass=ABCMeta): @abstract...
ABCMeta
python
sympy__sympy
sympy/core/mul.py
{ "start": 809, "end": 2345 }
class ____: is_Order = False is_Mul = False is_Number = False is_Poly = False is_commutative = False def _mulsort(args): # in-place sorting of args args.sort(key=_args_sortkey) def _unevaluated_Mul(*args): """Return a well-formed unevaluated Mul: Numbers are collected and put in...
NC_Marker
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 9012, "end": 10202 }
class ____(Sky2PixProjection, Zenithal): r""" Zenithal perspective projection - sky to pixel. Corresponds to the ``AZP`` projection in FITS WCS. .. math:: x &= R \sin \phi \\ y &= -R \sec \gamma \cos \theta where: .. math:: R = \frac{180^{\circ}}{\pi} \frac{(\mu + 1) ...
Sky2Pix_ZenithalPerspective
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_details.py
{ "start": 286, "end": 1259 }
class ____(UserNotificationDetailsTestBase): def test_lookup_self(self) -> None: self.get_success_response("me") def test_lookup_other_user(self) -> None: user_b = self.create_user(email="b@example.com") self.get_error_response(user_b.id, status_code=403) def test_superuser(self) -...
UserNotificationDetailsGetTest
python
joke2k__faker
faker/providers/job/az_AZ/__init__.py
{ "start": 42, "end": 2489 }
class ____(BaseProvider): jobs = [ "Aktyor", "Akustik Mühəndisi", "Allerqoloq", "Analitik", "Androloq", "Antropoloq", "Aqronom", "Aqronom-Torpaqşünas", "Arxeoloq", "Arxivçi", "Astrofizik", "Astronom", "Aviatexnik...
Provider
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_automation_rules.py
{ "start": 11328, "end": 13303 }
class ____: @pytest.fixture(autouse=True) def setup_method(self): self.project = get(Project) def test_add_rule_regex(self): assert not self.project.automation_rules.all() rule = RegexAutomationRule.objects.create( project=self.project, description="First ru...
TestAutomationRuleManager
python
google__pytype
pytype/tools/config.py
{ "start": 1774, "end": 2366 }
class ____(ConfigSection): """A section of an INI config file.""" def __init__(self, parser, section): self._parser = parser self._section = section @classmethod def create_from_file(cls, filepath, section): parser = configparser.ConfigParser() try: parser.read(filepath) except confi...
IniConfigSection
python
streamlit__streamlit
lib/tests/streamlit/elements/lib/column_config_utils_test.py
{ "start": 1566, "end": 3150 }
class ____: def __str__(self): return "TestObject" def _get_arrow_schema_field(column: pd.Series) -> pa.Field | None: """Get the Arrow schema field for a pandas Series.""" try: arrow_schema = pa.Table.from_pandas(column.to_frame()).schema return arrow_schema.field(0) except (pa...
TestObject
python
pytorch__pytorch
torch/_dynamo/variables/base.py
{ "start": 8832, "end": 27381 }
class ____(metaclass=VariableTrackerMeta): """ Base class for tracked locals and stack values VariableTracker instances are immutable and should be copied in order to change them. Prefer the factory function VariableTracker.build() over VariableTracker.__init__(). """ # fields to leave un...
VariableTracker
python
ray-project__ray
python/ray/util/iter.py
{ "start": 26472, "end": 42040 }
class ____(Generic[T]): """An iterator over a single shard of data. It implements similar transformations as ParallelIterator[T], but the transforms will be applied locally and not remotely in parallel. This class is **serializable** and can be passed to other remote tasks and actors. However, it ...
LocalIterator
python
huggingface__transformers
tests/repo_utils/test_check_copies.py
{ "start": 8009, "end": 17551 }
class ____(unittest.TestCase): def test_find_code_in_transformers(self): with tempfile.TemporaryDirectory() as tmp_folder: create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): code = find_code_in_transformers("models.bert.modeling_bert.BertAttenti...
CopyCheckTester
python
scrapy__scrapy
tests/test_webclient.py
{ "start": 6519, "end": 6747 }
class ____(resource.Resource): def render(self, request): request.setResponseCode(401) if request.args.get(b"showlength"): request.setHeader(b"content-length", b"0") return b""
ErrorResource
python
doocs__leetcode
solution/3300-3399/3326.Minimum Division Operations to Make Array Non Decreasing/Solution.py
{ "start": 178, "end": 503 }
class ____: def minOperations(self, nums: List[int]) -> int: ans = 0 for i in range(len(nums) - 2, -1, -1): if nums[i] > nums[i + 1]: nums[i] = lpf[nums[i]] if nums[i] > nums[i + 1]: return -1 ans += 1 return ans...
Solution
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 5306, "end": 12656 }
class ____: """ Represents a successfully matched pattern. The `Match` object is returned to represent a successfully matched pattern. Included in the Match are the pattern that was matched, the graph nodes matched, and any args that were used during the matching. The args and kwargs are speci...
Match
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py
{ "start": 20242, "end": 23794 }
class ____(LearningRateSchedule): """A LearningRateSchedule that uses a cosine decay schedule. See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983), SGDR: Stochastic Gradient Descent with Warm Restarts. When training a model, it is often useful to lower the learning rate as the training pro...
CosineDecay
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 6743, "end": 7591 }
class ____(BaseConfig): secrets_path: str = Field(None, description="Path in the setup/teardown container at which to copy connector secrets.") client_container_dockerfile_path: str = Field( None, description="Path to Dockerfile to run before each test for which a config is provided." ) setup_co...
ClientContainerConfig
python
pypa__setuptools
setuptools/build_meta.py
{ "start": 19078, "end": 20140 }
class ____(SetuptoolsDeprecationWarning): _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools" _DETAILS = """ Ensure that any custom bdist_wheel implementation is a subclass of setuptools.command.bdist_wheel.bdist_wheel. """ _DUE_DATE = (2025, 10, 15) # Initially in...
_IncompatibleBdistWheel
python
doocs__leetcode
solution/1400-1499/1429.First Unique Number/Solution.py
{ "start": 0, "end": 639 }
class ____: def __init__(self, nums: List[int]): self.cnt = Counter(nums) self.unique = OrderedDict({v: 1 for v in nums if self.cnt[v] == 1}) def showFirstUnique(self) -> int: return -1 if not self.unique else next(v for v in self.unique.keys()) def add(self, value: int) -> None: ...
FirstUnique
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 15986, "end": 16158 }
class ____(QuantoQuantizationTest): EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" weights = "int4"
QuantoQuantizationQBitsTensorTest
python
getsentry__sentry
src/sentry/api/event_search.py
{ "start": 23091, "end": 23449 }
class ____(NamedTuple): key: AggregateKey operator: str value: SearchValue def to_query_string(self) -> str: return f"{self.key.name}:{self.operator}{self.value.to_query_string()}" def __str__(self) -> str: return f"{self.key.name}{self.operator}{self.value.raw_value}" @dataclass...
AggregateFilter
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar13.py
{ "start": 884, "end": 2843 }
class ____(Generic[_T1, _T2, _T3, _P, Unpack[_Ts]]): def meth1( self, val1: _T1, val2: _T2, val3: _T3, cond: bool ) -> list[_T1] | list[_T2] | list[_T3]: if cond: # This should generate an error. return [0] if cond or 3 > 2: if isinstance(val1, str): ...
Class1
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 8641, "end": 17905 }
class ____(TaskRunOrchestrationRule): """ Checks relevant concurrency slots are available before entering a Running state. This rule checks if concurrency limits have been set on the tags associated with a TaskRun. If so, a concurrency slot will be secured against each concurrency limit before bein...
SecureTaskConcurrencySlots
python
pytorch__pytorch
torch/distributed/tensor/parallel/style.py
{ "start": 1036, "end": 7051 }
class ____(ParallelStyle): """ Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding. Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules. (i.e. MLP, Attention) Keyword Args: input_layouts ...
ColwiseParallel
python
numba__numba
numba/cuda/tests/doc_examples/test_cg.py
{ "start": 529, "end": 2905 }
class ____(CUDATestCase): def test_ex_grid_sync(self): # magictoken.ex_grid_sync_kernel.begin from numba import cuda, int32 import numpy as np sig = (int32[:,::1],) @cuda.jit(sig) def sequential_rows(M): col = cuda.grid(1) g = cuda.cg.this_gr...
TestCooperativeGroups
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py
{ "start": 33562, "end": 33729 }
class ____: inside_record: bool = False record_text_buffer: List[str] = field(default_factory=list) record_nesting_depth: int = 0 @dataclass
RecordParseState
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/base.py
{ "start": 2288, "end": 2587 }
class ____(Input): """ Abstraction for pipe input. """ @abstractmethod def send_bytes(self, data: bytes) -> None: """Feed byte string into the pipe""" @abstractmethod def send_text(self, data: str) -> None: """Feed a text string into the pipe"""
PipeInput
python
pandas-dev__pandas
pandas/tests/frame/test_constructors.py
{ "start": 116624, "end": 122273 }
class ____: @pytest.fixture(params=[list, dict, None]) def box(self, request): return request.param @pytest.fixture def constructor(self, frame_or_series, box): extra = {"index": range(2)} if frame_or_series is DataFrame: extra["columns"] = ["A"] if box is N...
TestFromScalar
python
apache__airflow
helm-tests/tests/helm_tests/other/test_flower.py
{ "start": 22514, "end": 25966 }
class ____: """Tests flower network policy.""" def test_off_by_default(self): docs = render_chart( show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert len(docs) == 0 def test_defaults(self): docs = render_chart( values={ ...
TestFlowerNetworkPolicy
python
PrefectHQ__prefect
tests/test_background_tasks.py
{ "start": 8881, "end": 9255 }
class ____: async def test_call(self, async_foo_task: Task[Any, int]): result = await async_foo_task(42) assert result == 42 async def test_call_with_return_state(self, async_foo_task: Task[Any, int]): state = await async_foo_task(42, return_state=True) assert state.is_complet...
TestCall
python
tensorflow__tensorflow
tensorflow/tools/api/tests/api_compatibility_test.py
{ "start": 7967, "end": 21638 }
class ____(test.TestCase): def __init__(self, *args, **kwargs): super(ApiCompatibilityTest, self).__init__(*args, **kwargs) golden_update_warning_filename = os.path.join( resource_loader.get_root_dir_with_all_resources(), _UPDATE_WARNING_FILE) self._update_golden_warning = file_io.read_file_to_s...
ApiCompatibilityTest
python
MongoEngine__mongoengine
mongoengine/errors.py
{ "start": 952, "end": 1285 }
class ____(MongoEngineException): """Raised when trying to set a field not declared in a :class:`~mongoengine.Document` or an :class:`~mongoengine.EmbeddedDocument`. To avoid this behavior on data loading, you should set the :attr:`strict` to ``False`` in the :attr:`meta` dictionary. """
FieldDoesNotExist
python
doocs__leetcode
solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/Solution2.py
{ "start": 0, "end": 650 }
class ____: def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: @cache def dfs(state, x): if state == mask: return 0 vis = [False] * batchSize res = 0 for i, v in enumerate(g): if state >> i & 1 == 0 and ...
Solution
python
ray-project__ray
rllib/algorithms/dreamerv3/torch/dreamerv3_torch_rl_module.py
{ "start": 687, "end": 2982 }
class ____(TorchRLModule, DreamerV3RLModule): """The torch-specific RLModule class for DreamerV3. Serves mainly as a thin-wrapper around the `DreamerModel` (a torch.nn.Module) class. """ framework = "torch" @override(TorchRLModule) def _forward_inference(self, batch: Dict[str, Any], **kwargs)...
DreamerV3TorchRLModule
python
numba__numba
numba/tests/test_compiler_flags.py
{ "start": 602, "end": 1335 }
class ____(TestCase): def test_fastmath_in_overload(self): def fastmath_status(): pass @overload(fastmath_status) def ov_fastmath_status(): flags = ConfigStack().top() val = "Has fastmath" if flags.fastmath else "No fastmath" def codegen(): ...
TestCompilerFlagCachedOverload
python
graphql-python__graphene
setup.py
{ "start": 563, "end": 2667 }
class ____(TestCommand): user_options = [("pytest-args=", "a", "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] ...
PyTest
python
tornadoweb__tornado
tornado/test/testing_test.py
{ "start": 7497, "end": 10509 }
class ____(AsyncTestCase): def setUp(self): super().setUp() self.finished = False def tearDown(self): self.assertTrue(self.finished) super().tearDown() @gen_test def test_sync(self): self.finished = True @gen_test def test_async(self): yield gen...
GenTest
python
sympy__sympy
sympy/core/relational.py
{ "start": 25598, "end": 27701 }
class ____(Relational): """An unequal relation between two objects. Explanation =========== Represents that two objects are not equal. If they can be shown to be definitively equal, this will reduce to False; if definitively unequal, this will reduce to True. Otherwise, the relation is maint...
Unequality
python
PyCQA__pylint
tests/functional/u/unsubscriptable_value.py
{ "start": 1586, "end": 1712 }
class ____(LibSubscriptable): pass MaybeSubscriptable()[0] # subscriptable classes (through metaclasses)
MaybeSubscriptable
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/memcache/guestbook/main.py
{ "start": 1354, "end": 4465 }
class ____(webapp2.RequestHandler): def get(self): self.response.out.write("<html><body>") guestbook_name = self.request.get("guestbook_name") greetings = self.get_greetings(guestbook_name) stats = memcache.get_stats() self.response.write("<b>Cache Hits:{}</b><br>".format(s...
MainPage
python
jazzband__prettytable
tests/test_prettytable.py
{ "start": 4361, "end": 6469 }
class ____: """Make sure that building a table row-by-row and column-by-column yield the same results""" @pytest.mark.parametrize( ["left_hand", "right_hand"], [ ( lf("row_prettytable"), lf("col_prettytable"), ), ( ...
TestBuildEquivalence
python
simplejson__simplejson
simplejson/tests/test_subclass.py
{ "start": 190, "end": 393 }
class ____(float): def __repr__(self): return 'invalid json' __str__ = __repr__ # class AlternateDecimal(Decimal): # def __repr__(self): # return 'invalid json'
AlternateFloat
python
redis__redis-py
redis/auth/token.py
{ "start": 579, "end": 866 }
class ____: def __init__(self, token: TokenInterface): self._token = token def get_token(self) -> TokenInterface: return self._token def get_ttl_ms(self) -> float: return self._token.get_expires_at_ms() - self._token.get_received_at_ms()
TokenResponse
python
pdm-project__pdm
tests/test_plugin.py
{ "start": 210, "end": 4420 }
class ____(BaseCommand): def add_arguments(self, parser) -> None: parser.add_argument("-n", "--name", help="The person's name") def handle(self, project, options) -> None: greeting = "Hello world" if options.name: greeting = f"Hello, {options.name}" print(greeting) ...
HelloCommand
python
yaml__pyyaml
lib/yaml/events.py
{ "start": 1834, "end": 1873 }
class ____(NodeEvent): pass
AliasEvent
python
scipy__scipy
scipy/stats/_distn_infrastructure.py
{ "start": 16452, "end": 19254 }
class ____: # generic type compatibility with scipy-stubs __class_getitem__ = classmethod(types.GenericAlias) def __init__(self, dist, *args, **kwds): self.args = args self.kwds = kwds # create a new instance self.dist = dist.__class__(**dist._updated_ctor_param()) ...
rv_frozen
python
getsentry__sentry
src/sentry/overwatch_webhooks/overwatch_consent/service.py
{ "start": 530, "end": 1479 }
class ____(RpcService): key = "overwatch_consent" local_mode = SiloMode.REGION @classmethod def get_local_implementation(cls) -> RpcService: from sentry.overwatch_webhooks.overwatch_consent.impl import ( DatabaseBackedOverwatchConsentService, ) return DatabaseBacked...
OverwatchConsentService
python
Lightning-AI__lightning
src/lightning/pytorch/demos/boring_classes.py
{ "start": 5846, "end": 6837 }
class ____(LightningDataModule): """ .. warning:: This is meant for testing/debugging and is experimental. """ def __init__(self) -> None: super().__init__() def setup(self, stage: str) -> None: if stage == "fit": self.random_train = RandomIterableDataset(32, 512) ...
BoringDataModuleNoLen
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/cli/test_ecs_worker.py
{ "start": 1623, "end": 14806 }
class ____: def setup_method(self): self.runner = CliRunner() @patch("prefect_aws._cli.ecs_worker.load_template") def test_deploy_service_dry_run( self, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-service command with dry-run.""" mock_load_t...
TestECSWorkerCLI
python
scikit-learn__scikit-learn
sklearn/multioutput.py
{ "start": 11425, "end": 15021 }
class ____(RegressorMixin, _MultiOutputEstimator): """Multi target regression. This strategy consists of fitting one regressor per target. This is a simple strategy for extending regressors that do not natively support multi-target regression. .. versionadded:: 0.18 Parameters ---------- ...
MultiOutputRegressor
python
networkx__networkx
networkx/algorithms/tests/test_cluster.py
{ "start": 10838, "end": 12748 }
class ____: @classmethod def setup_class(cls): pytest.importorskip("numpy") def test_clustering(self): G = nx.Graph() assert list(nx.clustering(G).values()) == [] assert nx.clustering(G) == {} def test_path(self): G = nx.path_graph(10) assert list(nx.clu...
TestClustering
python
getsentry__sentry
tests/sentry/releases/endpoints/test_project_release_file_details.py
{ "start": 795, "end": 7064 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) releasefile = ReleaseFile.obj...
ReleaseFileDetailsTest
python
getsentry__sentry
src/sentry/api/serializers/types.py
{ "start": 348, "end": 886 }
class ____(TypedDict, total=False): ref: str | None url: str | None dateReleased: datetime | None dateCreated: datetime | None dateStarted: datetime | None owner: dict[str, Any] | None lastCommit: dict[str, Any] | None lastDeploy: LastDeploy | None firstEvent: datetime | None las...
ReleaseSerializerResponseOptional
python
sqlalchemy__sqlalchemy
test/base/test_events.py
{ "start": 26705, "end": 33661 }
class ____(TearDownLocalEventsFixture, fixtures.TestBase): def setup_test(self): class TargetEvents(event.Events): def event_one(self, target, arg): pass class BaseTarget: dispatch = event.dispatcher(TargetEvents) class TargetFactory(BaseTarget): ...
JoinTest
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 14436, "end": 16382 }
class ____(Operation): def __init__(self, axis=None, keepdims=False, *, name=None): super().__init__(name=name) if isinstance(axis, int): axis = [axis] self.axis = axis self.keepdims = keepdims def call(self, x): return backend.numpy.amin(x, axis=self.axis, k...
Amin
python
fluentpython__example-code-2e
24-class-metaprog/tinyenums/microenum_demo.py
{ "start": 165, "end": 224 }
class ____(MicroEnum): cocoa coconut vanilla
Flavor
python
kamyu104__LeetCode-Solutions
Python/search-suggestions-system.py
{ "start": 1937, "end": 2750 }
class ____(object): def suggestedProducts(self, products, searchWord): """ :type products: List[str] :type searchWord: str :rtype: List[List[str]] """ products.sort() trie = TrieNode2() for i in xrange(len(products)): trie.insert(products, ...
Solution2
python
lazyprogrammer__machine_learning_examples
airline/rnn.py
{ "start": 689, "end": 5069 }
class ____(object): def __init__(self, hidden_layer_sizes): self.hidden_layer_sizes = hidden_layer_sizes def fit(self, X, Y, activation=T.tanh, learning_rate=1e-1, mu=0.5, reg=0, epochs=2000, show_fig=False): N, t, D = X.shape self.hidden_layers = [] Mi = D for Mo in se...
RNN
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 9095, "end": 9548 }
class ____(Enum): """Enumerate the reasons an asset may have failed to materialize. Can be used to provide more granular information about the failure to the user. """ FAILED_TO_MATERIALIZE = "FAILED_TO_MATERIALIZE" # The asset failed to materialize UPSTREAM_FAILED_TO_MATERIALIZE = "UPSTREAM_FAILE...
AssetMaterializationFailureReason
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/table.py
{ "start": 574, "end": 833 }
class ____(graphene.ObjectType): nullable = graphene.NonNull(graphene.Boolean) unique = graphene.NonNull(graphene.Boolean) other = non_null_list(graphene.String) class Meta: name = "TableColumnConstraints"
GrapheneTableColumnConstraints
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 140063, "end": 156261 }
class ____: def test_degenerate(self, xp): # 0-order filter is just a passthrough # Even-order filters have DC gain of -rp dB b, a = cheby1(0, 10*math.log10(2), xp.asarray(1), analog=True) assert_array_almost_equal( b, xp.asarray([1 / math.sqrt(2)], dtype=xp.float64) ...
TestCheby1
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-reduce-an-integer-to-0.py
{ "start": 451, "end": 748 }
class ____(object): def minOperations(self, n): """ :type n: int :rtype: int """ result = 0 while n: if n&1: n >>= 1 n += n&1 result += 1 n >>= 1 return result
Solution2
python
pypa__hatch
tests/backend/builders/test_sdist.py
{ "start": 1098, "end": 2421 }
class ____: def test_default(self, isolation): builder = SdistBuilder(str(isolation)) assert builder.config.core_metadata_constructor is builder.config.core_metadata_constructor assert builder.config.core_metadata_constructor is get_core_metadata_constructors()[DEFAULT_METADATA_VERSION] ...
TestCoreMetadataConstructor
python
sympy__sympy
sympy/stats/frv_types.py
{ "start": 5337, "end": 7243 }
class ____(SingleFiniteDistribution): _argnames = ('sides',) @staticmethod def check(sides): _value_check((sides.is_positive, sides.is_integer), "number of sides must be a positive integer.") @property def is_symbolic(self): return not self.sides.is_number ...
DieDistribution