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
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 360782, "end": 370565 }
class ____(FieldChannelMixin, core.SecondaryFieldDef): r""" Longitude2 schema wrapper. A field definition of a secondary channel that shares a scale with another primary channel. For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``. Parameters ---------- shorthan...
Longitude2
python
pytorch__pytorch
test/dynamo/test_compile.py
{ "start": 7145, "end": 8369 }
class ____(TestCase): def check_signature(self, public_fn_name, private_fn_name, private_namespace): public_fn = getattr(torch.compiler, public_fn_name) private_fn = getattr(private_namespace, private_fn_name) public_sig = inspect.signature(public_fn) private_sig = inspect.signature...
PublicTorchCompilerTests
python
walkccc__LeetCode
solutions/2351. First Letter to Appear Twice/2351.py
{ "start": 0, "end": 191 }
class ____: def repeatedCharacter(self, s: str) -> str: seen = [False] * 26 for c in s: if seen[ord(c) - ord('a')]: return c seen[ord(c) - ord('a')] = True
Solution
python
getsentry__sentry
src/sentry/api/endpoints/organization_events_has_measurements.py
{ "start": 1137, "end": 1684 }
class ____(serializers.Serializer): transaction = serializers.CharField(max_length=200) type = serializers.ChoiceField(choices=list(MEASUREMENT_TYPES.keys())) def validate(self, data): # only allow one project at a time in order to cache the results # for a unique transaction projec...
EventsHasMeasurementsQuerySerializer
python
getsentry__sentry
tests/sentry/web/frontend/test_openidtoken.py
{ "start": 346, "end": 5408 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.application = ApiApplication.objects.create( owner=self.user, redirect_uris="https://example.com" ) self.id_token = OpenIDToken("ex_client_id", self.user.id, "shared_secret", nonce="abcd") def test_g...
OpenIDTokenTest
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 21110, "end": 22034 }
class ____(TopLevel): # metadata __slots__ = ("path", "resolved_path", "source_id", "is_interface", "settings") """ settings: Settings settings result from parsing the compiler pragmas in the file. """ _special_decoders = {"settings": Settings.from_dict} def to_dict(self): r...
Module
python
agronholm__apscheduler
tests/test_marshalling.py
{ "start": 619, "end": 2268 }
class ____: @pytest.mark.parametrize( "obj, error", [ (partial(DummyClass.meth), "Cannot create a reference to a partial()"), (lambda: None, "Cannot create a reference to a lambda"), ], ids=["partial", "lambda"], ) def test_errors(self, obj, error): ...
TestCallableToRef
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_alloy_db.py
{ "start": 2048, "end": 2347 }
class ____: def test_class_attributes(self): assert AlloyDBUsersLink.key == EXPECTED_ALLOY_DB_USERS_LINK_KEY assert AlloyDBUsersLink.name == EXPECTED_ALLOY_DB_USERS_LINK_NAME assert AlloyDBUsersLink.format_str == EXPECTED_ALLOY_DB_USERS_LINK_FORMAT_STR
TestAlloyDBUsersLink
python
tornadoweb__tornado
tornado/test/locale_test.py
{ "start": 3337, "end": 6359 }
class ____(unittest.TestCase): def test_format_date(self): locale = tornado.locale.get("en_US") date = datetime.datetime(2013, 4, 28, 18, 35) self.assertEqual( locale.format_date(date, full_format=True), "April 28, 2013 at 6:35 pm" ) aware_dt = datetime.datetime....
EnglishTest
python
joke2k__faker
faker/providers/date_time/fil_PH/__init__.py
{ "start": 46, "end": 829 }
class ____(DateTimeProvider): """Provider for datetimes for fil_PH locale""" DAY_NAMES = { "0": "Linggo", "1": "Lunes", "2": "Martes", "3": "Miyerkules", "4": "Huwebes", "5": "Biyernes", "6": "Sabado", } MONTH_NAMES = { "01": "Enero", ...
Provider
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_opensearch_serverless.py
{ "start": 917, "end": 1199 }
class ____: def test_opensearch_serverless_hook(self): hook = OpenSearchServerlessHook() service_name = "opensearchserverless" assert hook.conn is not None assert hook.conn.meta.service_model.service_name == service_name
TestOpenSearchServerlessHook
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/util_test.py
{ "start": 24318, "end": 28412 }
class ____(test.TestCase): def setUp(self): self._rng = np.random.RandomState(42) def _fill_triangular(self, x, upper=False): """Numpy implementation of `fill_triangular`.""" x = np.asarray(x) # Formula derived by solving for n: m = n(n+1)/2. m = np.int32(x.shape[-1]) n = np.sqrt(0.25 + 2....
FillTriangularTest
python
celery__celery
t/unit/backends/test_redis.py
{ "start": 4470, "end": 5013 }
class ____(conftest.MockCallbacks): def __init__(self, sentinels, min_other_sentinels=0, sentinel_kwargs=None, **connection_kwargs): self.sentinel_kwargs = sentinel_kwargs self.sentinels = [Redis(hostname, port, **self.sentinel_kwargs) for hostname, port in...
Sentinel
python
fastapi__sqlmodel
tests/test_deprecations.py
{ "start": 46, "end": 84 }
class ____(SQLModel): name: str
Item
python
bokeh__bokeh
tests/unit/bokeh/util/test_callback_manager.py
{ "start": 1918, "end": 2238 }
class ____: def __init__(self) -> None: self.last_name = None self.last_old = None self.last_new = None def __call__(self, event): self.method(event) def method(self, event): self.event = event def partially_good(self, arg, event): pass
_GoodEventCallback
python
spack__spack
lib/spack/spack/solver/runtimes.py
{ "start": 439, "end": 13471 }
class ____: """An object of this class is injected in callbacks to compilers, to let them declare properties of the runtimes they support and of the runtimes they provide, and to add runtime dependencies to the nodes using said compiler. The usage of the object is the following. First, a runtime packag...
RuntimePropertyRecorder
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 335, "end": 1987 }
class ____(NonStrictDataModel): """ :param metric: The metric name :type metric: str :param variants: The names of the metric variants :type variants: Sequence[str] """ _schema = { "properties": { "metric": {"description": "The metric name", "type": ["string", "null"]}, ...
MetricVariants
python
aio-libs__aiohttp
aiohttp/streams.py
{ "start": 994, "end": 1415 }
class ____: __slots__ = ("_stream",) def __init__(self, stream: "StreamReader") -> None: self._stream = stream def __aiter__(self) -> "ChunkTupleAsyncStreamIterator": return self async def __anext__(self) -> tuple[bytes, bool]: rv = await self._stream.readchunk() if r...
ChunkTupleAsyncStreamIterator
python
rapidsai__cudf
python/cudf/cudf/tests/input_output/test_json.py
{ "start": 36540, "end": 48582 }
class ____: @pytest.mark.parametrize("chunk_size", [10, 100, 1024, 1024 * 1024]) def test_chunked_nested_json_reader(self, tag, data, chunk_size): expected = cudf.read_json(StringIO(data), lines=True) source_size = len(data) chunks = [] for chunk_start in range(0, source_size, c...
TestNestedJsonReaderCommon
python
python-pillow__Pillow
Tests/test_color_lut.py
{ "start": 267, "end": 10622 }
class ____: def generate_identity_table( self, channels: int, size: int | tuple[int, int, int] ) -> tuple[int, tuple[int, int, int], list[float]]: if isinstance(size, tuple): size_1d, size_2d, size_3d = size else: size_1d, size_2d, size_3d = (size, size, size) ...
TestColorLut3DCoreAPI
python
sympy__sympy
sympy/physics/mechanics/wrapping_geometry.py
{ "start": 548, "end": 1895 }
class ____(ABC): """Abstract base class for all geometry classes to inherit from. Notes ===== Instances of this class cannot be directly instantiated by users. However, it can be used to created custom geometry types through subclassing. """ @property @abstractmethod def point(cl...
WrappingGeometryBase
python
scrapy__scrapy
tests/test_webclient.py
{ "start": 6276, "end": 6519 }
class ____(resource.Resource): def render(self, request): # only sends 3 bytes even though it claims to send 5 request.setHeader(b"content-length", b"5") request.write(b"abc") return b""
BrokenDownloadResource
python
mwaskom__seaborn
tests/_core/test_plot.py
{ "start": 1250, "end": 2065 }
class ____(Mark): _grouping_props = ["color"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.passed_keys = [] self.passed_data = [] self.passed_axes = [] self.passed_scales = None self.passed_orient = None self.n_splits = 0 ...
MockMark
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_montana_zip.py
{ "start": 742, "end": 1743 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_montana_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _panda...
ColumnValuesToBeValidMontanaZip
python
has2k1__plotnine
tools/term.py
{ "start": 546, "end": 794 }
class ____(Enum): """ Background color codes """ black = "\033[40m" red = "\033[41m" green = "\033[42m" orange = "\033[43m" blue = "\033[44m" purple = "\033[45m" cyan = "\033[46m" lightgrey = "\033[47m"
Bg
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/misc_execution_tests/test_retries.py
{ "start": 23430, "end": 25114 }
class ____(ConfigurableResource): parent_dir: str def create_resource(self, context: InitResourceContext) -> None: filepath = os.path.join(self.parent_dir, f"{context.run_id}_resource.txt") if not os.path.exists(filepath): open(filepath, "a", encoding="utf8").close() rai...
FailOnceResource
python
getsentry__sentry
src/sentry/migrations/0908_increase_email_field_length.py
{ "start": 155, "end": 1446 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
realpython__materials
python-contact-book/source_code_step_2/rpcontacts/views.py
{ "start": 243, "end": 1391 }
class ____(QMainWindow): """Main Window.""" def __init__(self, parent=None): """Initializer.""" super().__init__(parent) self.setWindowTitle("RP Contacts") self.resize(550, 250) self.centralWidget = QWidget() self.setCentralWidget(self.centralWidget) self...
Window
python
apache__thrift
lib/py/src/Thrift.py
{ "start": 787, "end": 1357 }
class ____(object): STOP = 0 VOID = 1 BOOL = 2 BYTE = 3 I08 = 3 DOUBLE = 4 I16 = 6 I32 = 8 I64 = 10 STRING = 11 UTF7 = 11 STRUCT = 12 MAP = 13 SET = 14 LIST = 15 UTF8 = 16 UTF16 = 17 _VALUES_TO_NAMES = ( 'STOP', 'VOID', 'BO...
TType
python
py-pdf__pypdf
pypdf/_page.py
{ "start": 82217, "end": 89201 }
class ____(Sequence[PageObject]): def __init__( self, length_function: Callable[[], int], get_function: Callable[[int], PageObject], ) -> None: self.length_function = length_function self.get_function = get_function self.current = -1 def __len__(self) -> int:...
_VirtualList
python
celery__celery
t/unit/backends/test_mongodb.py
{ "start": 26367, "end": 27799 }
class ____: def __init__(self, a): self.a = a def __eq__(self, other): assert self.__class__ == type(other) return self.a == other.a SUCCESS_RESULT_TEST_DATA = [ # json types { "result": "A simple string", "serializers": ["bson", "pickle", "yaml", "json", "msg...
_MyTestClass
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 9067, "end": 11402 }
class ____(nn.Module): def __init__(self, config: Dinov2WithRegistersConfig): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size {config.hidden_size} is not a multiple o...
Dinov2WithRegistersSelfAttention
python
qdrant__qdrant-client
qdrant_client/http/api/aliases_api.py
{ "start": 1311, "end": 3043 }
class ____: def __init__(self, api_client: "Union[ApiClient, AsyncApiClient]"): self.api_client = api_client def _build_for_get_collection_aliases( self, collection_name: str, ): """ Get list of all aliases for a collection """ path_params = { ...
_AliasesApi
python
pypa__warehouse
warehouse/packaging/models.py
{ "start": 40811, "end": 41729 }
class ____(db.Model): """ Store an alternate repository name, url, description for a project. One project can have zero, one, or more alternate repositories. For each project, ensures the url and name are unique. Urls must start with http(s). """ __tablename__ = "alternate_repositories" ...
AlternateRepository
python
getsentry__sentry
tests/sentry/issues/test_grouptype.py
{ "start": 494, "end": 1367 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.registry_patcher = patch("sentry.issues.grouptype.registry", new=GroupTypeRegistry()) self.registry_patcher.__enter__() class ErrorGroupType(GroupType): type_id = -1 slug = "error" ...
BaseGroupTypeTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/refurb/FURB189.py
{ "start": 429, "end": 476 }
class ____(dict[str, str]): pass
SubscriptDict
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_audio.py
{ "start": 32762, "end": 37675 }
class ____(Data2VecAudioPreTrainedModel): def __init__(self, config): r""" target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`Dat...
Data2VecAudioForCTC
python
spack__spack
lib/spack/spack/builder.py
{ "start": 1637, "end": 9054 }
class ____: def __init__(self, builder, phase_fn): self.builder = builder self.phase_fn = phase_fn def __call__(self, spec, prefix): return self.phase_fn(self.builder.pkg, spec, prefix) def get_builder_class(pkg, name: str) -> Optional[Type["Builder"]]: """Return the builder class...
_PhaseAdapter
python
spyder-ide__spyder
spyder/plugins/tours/widgets.py
{ "start": 1614, "end": 4639 }
class ____(QDialog): """A general fade in/fade out QDialog with some builtin functions""" sig_key_pressed = Signal() def __init__(self, parent, opacity, duration, easing_curve): super().__init__(parent) self.parent = parent self.opacity_min = min(opacity) self.opacity_max =...
FadingDialog
python
scrapy__scrapy
scrapy/extensions/feedexport.py
{ "start": 11715, "end": 14413 }
class ____: def __init__( self, storage: FeedStorageProtocol, uri: str, format: str, # noqa: A002 store_empty: bool, batch_id: int, uri_template: str, filter: ItemFilter, # noqa: A002 feed_options: dict[str, Any], spider: Spider, ...
FeedSlot
python
ray-project__ray
python/ray/experimental/collective/operations.py
{ "start": 6151, "end": 6968 }
class ____: """Wrapper for NCCL reduce-scatter.""" def bind( self, input_nodes: List["ray.dag.DAGNode"], op: ReduceOp = ReduceOp.SUM, transport: Optional[Union[str, Communicator]] = None, ) -> List[CollectiveOutputNode]: if not isinstance(op, ReduceOp): r...
ReduceScatterWrapper
python
huggingface__transformers
src/transformers/models/helium/modular_helium.py
{ "start": 3792, "end": 4094 }
class ____(GraniteAttention): def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None): super().__init__(config, layer_idx) self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False) self.scaling = 1 / math.sqrt(self.head_dim)
HeliumAttention
python
h5py__h5py
h5py/_hl/selections2.py
{ "start": 1949, "end": 2723 }
class ____: """ Implements slicing for scalar datasets. """ def __init__(self, fspace, args): if args == (): self.mshape = None elif args == (Ellipsis,): self.mshape = () else: raise ValueError("Illegal slicing argument for scalar dataspa...
ScalarReadSelection
python
PrefectHQ__prefect
tests/_internal/pydantic/test_validated_func.py
{ "start": 243, "end": 1638 }
class ____: """Test basic function argument validation.""" def test_simple_function(self): def greet(name: str, age: int = 0): return f"Hello {name}, you are {age} years old" vf = ValidatedFunction(greet) result = vf.validate_call_args(("Alice",), {"age": 30}) asse...
TestBasicValidation
python
pytorch__pytorch
torch/_dynamo/variables/functions.py
{ "start": 85421, "end": 86733 }
class ____(UserFunctionVariable): def as_python_constant(self) -> Any: return self.fn def call_function( self, tx: "InstructionTranslator", args: Sequence[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: constant_args = check_consta...
CollectionsNamedTupleFunction
python
Netflix__metaflow
metaflow/sidecar/sidecar_subprocess.py
{ "start": 553, "end": 670 }
class ____(Exception): """raised when unable to write to pipe given allotted time""" pass
PipeUnavailableError
python
huggingface__transformers
src/transformers/models/vitmatte/image_processing_vitmatte_fast.py
{ "start": 1371, "end": 6033 }
class ____(BaseImageProcessorFast): do_rescale: bool = True rescale_factor: Union[int, float] = 1 / 255 do_normalize: bool = True image_mean: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_MEAN image_std: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_STD do_pad: bool = True ...
VitMatteImageProcessorFast
python
encode__django-rest-framework
tests/test_api_client.py
{ "start": 5264, "end": 5381 }
class ____(APIView): def get(self, request): return HttpResponse('123', content_type='text/plain')
TextView
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 14669, "end": 15568 }
class ____(TestOutMultiEdgeDataView): @classmethod def setup_class(cls): cls.G = nx.path_graph(9, create_using=nx.MultiDiGraph()) cls.eview = nx.reportviews.InMultiEdgeView def test_repr(self): ev = self.eview(self.G)(data=True) rep = ( "InMultiEdgeDataView([(0, ...
TestInMultiEdgeDataView
python
tornadoweb__tornado
demos/chat/chatdemo.py
{ "start": 1770, "end": 1910 }
class ____(tornado.web.RequestHandler): def get(self): self.render("index.html", messages=global_message_buffer.cache)
MainHandler
python
ApeWorX__ape
src/ape_test/accounts.py
{ "start": 3133, "end": 3633 }
class ____(ApeSigner, TestAccountAPI): index: int address_str: str __test__ = False @property def alias(self) -> str: return f"TEST::{self.index}" @cached_property def address(self) -> AddressType: # Overridden. return self.network_manager.ethereum.decode_address(s...
TestAccount
python
celery__celery
t/unit/utils/test_dispatcher.py
{ "start": 659, "end": 851 }
class ____: def __call__(self, val, **kwargs): return val def a(self, val, **kwargs): return val a_signal = Signal(providing_args=['val'], use_caching=False)
Callable
python
pola-rs__polars
py-polars/src/polars/dataframe/group_by.py
{ "start": 948, "end": 27435 }
class ____: """Starts a new GroupBy operation.""" def __init__( self, df: DataFrame, *by: IntoExpr | Iterable[IntoExpr], maintain_order: bool, predicates: Iterable[Any] | None, **named_by: IntoExpr, ) -> None: """ Utility class for performing ...
GroupBy
python
TheAlgorithms__Python
data_structures/binary_tree/treap.py
{ "start": 64, "end": 4751 }
class ____: """ Treap's node Treap is a binary tree by value and heap by priority """ def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: ...
Node
python
has2k1__plotnine
plotnine/mapping/_atomic.py
{ "start": 2115, "end": 2479 }
class ____(ae_value[str | tuple]): """ A single color value """ def __post_init__(self): if isinstance(self.value, str): return elif is_color_tuple(self.value): self.value = tuple(self.value) return raise ValueError(f"{self.value} is not a kn...
color
python
google__jax
docs/autodidax.py
{ "start": 9143, "end": 10204 }
class ____: array_abstraction_level = 1 shape: tuple[int, ...] dtype: np.dtype def __init__(self, shape, dtype): self.shape = shape self.dtype = dtype @property def ndim(self): return len(self.shape) _neg = staticmethod(neg) _add = staticmethod(add) _radd = staticmethod(swap(add)) _mu...
ShapedArray
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/snapshot.py
{ "start": 548, "end": 1144 }
class ____(GrapheneIPipelineSnapshotMixin, graphene.ObjectType): class Meta: # pyright: ignore[reportIncompatibleVariableOverride] interfaces = (GrapheneSolidContainer, GrapheneIPipelineSnapshot, GraphenePipelineReference) name = "PipelineSnapshot" def __init__(self, represented_job: Represent...
GraphenePipelineSnapshot
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py
{ "start": 3972, "end": 4878 }
class ____(Benchmark): """ Univariate Problem06 objective function. This class defines the Univariate Problem06 global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\\text{Problem06}}(x) = - \\left[x + \\sin(x) \\right] e^{-x^2} Boun...
Problem06
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-nvidia-triton/llama_index/llms/nvidia_triton/utils.py
{ "start": 9110, "end": 13918 }
class ____(_BaseTritonClient): """GRPC connection to a triton inference server.""" @property def _inference_server_client( self, ) -> Type["grpcclient.InferenceServerClient"]: """Return the preferred InferenceServerClient class.""" import tritonclient.grpc as grpcclient ...
GrpcTritonClient
python
streamlit__streamlit
lib/tests/streamlit/elements/select_slider_test.py
{ "start": 15158, "end": 17014 }
class ____(DeltaGeneratorTestCase): def test_select_slider_with_width_pixels(self): """Test that select_slider can be displayed with a specific width in pixels.""" st.select_slider("Label", options=["a", "b", "c"], width=500) element = self.get_delta_from_queue().new_element assert (...
SelectSliderWidthTest
python
openai__openai-python
src/openai/_module_client.py
{ "start": 1631, "end": 1754 }
class ____(LazyProxy["Audio"]): @override def __load__(self) -> Audio: return _load_client().audio
AudioProxy
python
streamlit__streamlit
lib/streamlit/testing/v1/element_tree.py
{ "start": 32310, "end": 34408 }
class ____(Widget, Generic[T]): """A representation of ``st.select_slider``.""" _value: T | Sequence[T] | None proto: SliderProto = field(repr=False) label: str data_type: SliderProto.DataType.ValueType options: list[str] help: str form_id: str def __init__(self, proto: SliderProt...
SelectSlider
python
python__mypy
mypy/report.py
{ "start": 3030, "end": 4466 }
class ____(metaclass=ABCMeta): def __init__(self, reports: Reports, output_dir: str) -> None: self.output_dir = output_dir if output_dir != "<memory>": os.makedirs(output_dir, exist_ok=True) @abstractmethod def on_file( self, tree: MypyFile, modules: dict...
AbstractReporter
python
pytorch__pytorch
test/test_prims.py
{ "start": 11650, "end": 13141 }
class ____(TestCase): def test_torch_ops(self): r = make_tensor((2,), device='cpu', dtype=torch.float) self.assertEqual(torch.ops.prims.sin(r), torch.sin(r)) r = LoggingTensor(r) with capture_logs() as logs: log_input("input", r) prims.sin(r) self.ass...
TestPrimsBasic
python
ansible__ansible
lib/ansible/plugins/action/uri.py
{ "start": 466, "end": 3434 }
class ____(ActionBase): TRANSFERS_FILES = True def run(self, tmp=None, task_vars=None): self._supports_async = True self._supports_check_mode = False if task_vars is None: task_vars = dict() super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no l...
ActionModule
python
numpy__numpy
tools/swig/test/testVector.py
{ "start": 302, "end": 10633 }
class ____(unittest.TestCase): def __init__(self, methodName="runTest"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # Test the (type IN_ARRAY1[ANY]) typemap def testLength(self): "Test length function" print(self.typeStr...
VectorTestCase
python
pypa__warehouse
tests/common/db/observations.py
{ "start": 128, "end": 210 }
class ____(WarehouseFactory): class Meta: model = Observer
ObserverFactory
python
django__django
tests/managers_regress/models.py
{ "start": 2135, "end": 2315 }
class ____(AbstractBase3): name = models.CharField(max_length=25) default = OnlyFred() objects = models.Manager() def __str__(self): return self.name
Child5
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 57784, "end": 59578 }
class ____(nn.Module): def __init__(self, config: PatchTSTConfig): super().__init__() self.use_cls_token = config.use_cls_token self.pooling_type = config.pooling_type self.flatten = nn.Flatten(start_dim=1) self.dropout = nn.Dropout(config.head_dropout) if config.head_dropout...
PatchTSTClassificationHead
python
pdm-project__pdm
src/pdm/cli/commands/fix/fixers.py
{ "start": 910, "end": 2400 }
class ____(BaseFixer): """Fix the project config""" identifier = "project-config" def get_message(self) -> str: return ( "[success]python.path[/] config needs to be moved to [info].pdm-python[/] and " "[info].pdm.toml[/] needs to be renamed to [info]pdm.toml[/]" ) ...
ProjectConfigFixer
python
walkccc__LeetCode
solutions/3527. Find the Most Common Response/3527.py
{ "start": 0, "end": 366 }
class ____: def findCommonResponse(self, responses: list[list[str]]) -> str: count = collections.Counter() for response in responses: for response in set(response): count[response] += 1 maxFreq = max(count.values()) return min([response for response, count in count.item...
Solution
python
bokeh__bokeh
tests/unit/bokeh/colors/test_color__colors.py
{ "start": 5693, "end": 11505 }
class ____: def test_init(self) -> None: c = bcc.RGB(10, 20, 30) assert c assert c.a == 1.0 assert c.r == 10 assert c.g == 20 assert c.b == 30 c = bcc.RGB(10, 20, 30, 0.3) assert c assert c.a == 0.3 assert c.r == 10 assert c.g ...
Test_RGB
python
django__django
tests/admin_inlines/admin.py
{ "start": 9208, "end": 9324 }
class ____(admin.TabularInline): model = Class extra = 1 filter_vertical = ["person"]
ClassTabularVertical
python
pandas-dev__pandas
pandas/core/computation/pytables.py
{ "start": 13453, "end": 17016 }
class ____(BaseExprVisitor): const_type: ClassVar[type[ops.Term]] = Constant term_type: ClassVar[type[Term]] = Term def __init__(self, env, engine, parser, **kwargs) -> None: super().__init__(env, engine, parser) for bin_op in self.binary_ops: bin_node = self.binary_op_nodes_map...
PyTablesExprVisitor
python
getsentry__sentry
src/sentry/integrations/msteams/webhook.py
{ "start": 6532, "end": 26463 }
class ____(Endpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "POST": ApiPublishStatus.PRIVATE, } authentication_classes = () permission_classes = () provider = IntegrationProviderSlug.MSTEAMS.value def __init__(self, **kwargs) -> None: super().__init__(**kwargs) ...
MsTeamsWebhookEndpoint
python
jschneier__django-storages
tests/test_sftp.py
{ "start": 338, "end": 7943 }
class ____(TestCase): def setUp(self): self.storage = sftpstorage.SFTPStorage(host="foo", root_path="root") def test_init(self): pass @patch("paramiko.SSHClient") def test_no_known_hosts_file(self, mock_ssh): self.storage.known_host_file = "not_existed_file" self.storag...
SFTPStorageTest
python
pytorch__pytorch
test/profiler/test_python_tracer.py
{ "start": 281, "end": 3018 }
class ____(TestCase): @skipIfPythonVersionMismatch(lambda major, minor, micro: major == 3 and minor == 12) def test_method_with_c_function(self): class A: method_with_c_function = classmethod(repr) def get_key(x): A().method_with_c_function() time.sleep(1.2) ...
TestPythonTracer
python
doocs__leetcode
lcof2/剑指 Offer II 045. 二叉树最底层最左边的值/Solution.py
{ "start": 192, "end": 638 }
class ____: def findBottomLeftValue(self, root: TreeNode) -> int: q = deque([root]) ans = -1 while q: n = len(q) for i in range(n): node = q.popleft() if i == 0: ans = node.val if node.left: ...
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol26.py
{ "start": 561, "end": 884 }
class ____(Protocol[_T_co]): @overload def __getitem__(self, index: int, /) -> "_T_co | NestedSequence[_T_co]": ... @overload def __getitem__(self, index: slice, /) -> "NestedSequence[_T_co]": ... def func(t: TupleLike[int]): x: int | NestedSequence[int] = t y: NestedSequence[int] = t
NestedSequence
python
modin-project__modin
modin/config/envvars.py
{ "start": 43351, "end": 44252 }
class ____(EnvironmentVariable, type=bool): """ Whether to cast a DataFrame in-place when performing a merge when using hybrid mode. This flag modifies the behavior of a cast performed on operations involving more than one type of query compiler. If enabled the actual cast will be performed in-place ...
BackendMergeCastInPlace
python
ray-project__ray
release/llm_tests/serve/benchmark/firehose_utils.py
{ "start": 630, "end": 2697 }
class ____(BaseModel): record_name: RecordName record_metrics: Dict[str, Any] @field_validator("record_name", mode="before") def validate_record_name(cls, v): if isinstance(v, str): return RecordName(v) return v def write(self, verbose: bool = False): final_resu...
FirehoseRecord
python
hynek__structlog
src/structlog/tracebacks.py
{ "start": 10907, "end": 16573 }
class ____: """ Return a list of exception stack dictionaries for an exception. These dictionaries are based on :class:`Stack` instances generated by :func:`extract()` and can be dumped to JSON. Args: show_locals: Whether or not to include the values of a stack frame's local ...
ExceptionDictTransformer
python
rq__rq
tests/__init__.py
{ "start": 1342, "end": 2127 }
class ____(unittest.TestCase): """Base class to inherit test cases from for RQ. It sets up the Redis connection (available via self.connection), turns off logging to the terminal and flushes the Redis database before and after running each test. """ @classmethod def setUpClass(cls): ...
RQTestCase
python
django__django
django/tasks/base.py
{ "start": 4721, "end": 5272 }
class ____: exception_class_path: str traceback: str @property def exception_class(self): # Lazy resolve the exception class. exception_class = import_string(self.exception_class_path) if not isclass(exception_class) or not issubclass( exception_class, BaseException...
TaskError
python
sympy__sympy
sympy/codegen/fnodes.py
{ "start": 17022, "end": 17784 }
class ____(Token): """ AST node explicitly mapped to a fortran "return". Explanation =========== Because a return statement in fortran is different from C, and in order to aid reuse of our codegen ASTs the ordinary ``.codegen.ast.Return`` is interpreted as assignment to the result variable...
FortranReturn
python
ApeWorX__ape
src/ape/utils/abi.py
{ "start": 10577, "end": 14702 }
class ____: """ A class for contract return values using the struct data-structure. """ def items(self) -> dict: """Override""" return {} def __setitem__(self, key, value): """Override""" def create_struct(name: str, types: Sequence[ABIType], output_values: Sequence) -> A...
Struct
python
facebook__pyre-check
tools/generate_taint_models/model.py
{ "start": 11628, "end": 12229 }
class ____(Model): annotation: str target: str def __init__(self, annotation: str, target: str) -> None: if "-" in target: raise ValueError("The target is not supported") self.annotation = annotation self.target = target def __str__(self) -> str: return f"{s...
AssignmentModel
python
numpy__numpy
benchmarks/benchmarks/bench_ufunc.py
{ "start": 7330, "end": 7840 }
class ____(Benchmark): """ Benchmark for the methods which take an argument """ params = [['__floordiv__', '__mod__'], [dt for dt in TYPES1 if not dt.startswith('complex')]] param_names = ['methods', 'npdtypes'] timeout = 10 def setup(self, methname, npdtypes): values = ge...
MethodsV1NoComplex
python
gevent__gevent
src/greentest/3.12/test_ftplib.py
{ "start": 34335, "end": 39268 }
class ____(TestCase): """Specific TLS_FTP class tests.""" def setUp(self, encoding=DEFAULT_ENCODING): self.server = DummyTLS_FTPServer((HOST, 0), encoding=encoding) self.server.start() self.client = ftplib.FTP_TLS(timeout=TIMEOUT) self.client.connect(self.server.host, self.serve...
TestTLS_FTPClass
python
nedbat__coveragepy
coverage/cmdline.py
{ "start": 1217, "end": 10323 }
class ____: """A namespace class for individual options we'll build parsers from.""" # Keep these entries alphabetized (roughly) by the option name as it # appears on the command line. append = optparse.make_option( "-a", "--append", action="store_true", help="Append da...
Opts
python
huggingface__transformers
src/transformers/models/oneformer/processing_oneformer.py
{ "start": 801, "end": 9013 }
class ____(ProcessorMixin): r""" Constructs an OneFormer processor which wraps [`OneFormerImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`] into a single processor that inherits both the image processor and tokenizer functionalities. Args: image_processor ([`OneFormerImageProcess...
OneFormerProcessor
python
pytorch__pytorch
test/distributed/elastic/rendezvous/api_test.py
{ "start": 464, "end": 7155 }
class ____(TestCase): def setUp(self) -> None: self._backend = "dummy_backend" self._endpoint = "dummy_endpoint" self._run_id = "dummy_run_id" self._min_nodes = 3 self._max_nodes = 6 self._kwargs: dict[str, Any] = {} def _create_params(self) -> RendezvousParamete...
RendezvousParametersTest
python
ray-project__ray
python/ray/train/tests/test_trainer_restore.py
{ "start": 1543, "end": 12494 }
class ____(Callback): """Inject failure at the configured iteration number.""" def __init__(self, fail_marker_path: Path, num_iters: int = 2): self.num_iters = num_iters self.fail_marker_path = fail_marker_path def on_trial_result( self, iteration: int, trials: List[Trial], trial: ...
FailureInjectionCallback
python
astropy__astropy
astropy/cosmology/_src/traits/scale_factor.py
{ "start": 298, "end": 1635 }
class ____: """The trait for computing the cosmological scale factor. The scale factor is defined as :math:`a = a_0 / (1 + z)`. """ @property def scale_factor0(self) -> u.Quantity: r"""Scale factor at redshift 0. The scale factor is defined as :math:`a = a_0 / (1 + z)`. The commo...
ScaleFactor
python
jina-ai__jina
tests/integration/dynamic_batching/test_dynamic_batching_config.py
{ "start": 160, "end": 1315 }
class ____(Executor): @requests(on=['/cat', '/kitten']) @dynamic_batching(preferred_batch_size=4, timeout=2000) def cat_fun(self, docs, **kwargs): return DocumentArray([Document(text='cat')]) @requests() @dynamic_batching(preferred_batch_size=10, timeout=10000) def default_fun(self, doc...
MyExecutor
python
docker__docker-py
tests/unit/dockertypes_test.py
{ "start": 10877, "end": 11848 }
class ____(unittest.TestCase): def test_create_host_config_dict_logconfig(self): dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}} config = create_host_config( version=DEFAULT_DOCKER_API_VERSION, log_config=dct ) assert 'LogConfig' in config asser...
LogConfigTest
python
tensorflow__tensorflow
tensorflow/python/saved_model/tracing_utils_test.py
{ "start": 1063, "end": 1448 }
class ____(base.Trackable): def __init__(self): self.a = variables.Variable(0) self.b = variables.Variable(1) def _serialize_to_tensors(self): return {"a": self.a, "b": self.b} def _restore_from_tensors(self, restored_tensors): return control_flow_ops.group( self.a.assign(restored_tenso...
MyTrackable
python
getsentry__sentry
src/sentry/issues/endpoints/group_hashes.py
{ "start": 1006, "end": 5557 }
class ____(GroupEndpoint): publish_status = { "PUT": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, group: Group) -> Response: """ List an Issue's Hashes `````````````````````` This endpoint lists an issue's hash...
GroupHashesEndpoint
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 77460, "end": 85025 }
class ____(SeamlessM4Tv2PreTrainedModel): def __init__( self, config: SeamlessM4Tv2Config, embed_tokens: Optional[nn.Embedding] = None, ): r""" embed_tokens (`nn.Embedding`, *optional*): Input embedding """ super().__init__(config) self...
SeamlessM4Tv2Decoder
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/strings.py
{ "start": 13823, "end": 14655 }
class ____(SearchStrategy): def __init__(self, min_size: int, max_size: int | None): super().__init__() self.min_size = min_size self.max_size = ( max_size if max_size is not None else COLLECTION_DEFAULT_MAX_SIZE ) def do_draw(self, data: ConjectureData) -> bytes: ...
BytesStrategy