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
zarr-developers__zarr-python
src/zarr/registry.py
{ "start": 1098, "end": 11490 }
class ____(dict[str, type[T]], Generic[T]): def __init__(self) -> None: super().__init__() self.lazy_load_list: list[EntryPoint] = [] def lazy_load(self, use_entrypoint_name: bool = False) -> None: for e in self.lazy_load_list: self.register(e.load(), qualname=e.name if use_...
Registry
python
PyCQA__pyflakes
pyflakes/test/test_api.py
{ "start": 6356, "end": 9375 }
class ____(TestCase): """ Tests for L{Reporter}. """ def test_syntaxError(self): """ C{syntaxError} reports that there was a syntax error in the source file. It reports to the error stream and includes the filename, line number, error message, actual line of source and ...
TestReporter
python
coleifer__peewee
tests/postgres.py
{ "start": 27064, "end": 28729 }
class ____(ModelTestCase): database = db requires = [IDAlways, IDByDefault] def test_identity_field_always(self): iq = IDAlways.insert_many([(d,) for d in ('d1', 'd2', 'd3')]) curs = iq.execute() self.assertEqual(list(curs), [(1,), (2,), (3,)]) # Cannot specify id when gene...
TestIdentityField
python
django-guardian__django-guardian
guardian/testapp/tests/test_admin.py
{ "start": 868, "end": 1086 }
class ____(GuardedInlineAdminMixin, admin.StackedInline): """Test inline for UserProfile model using GuardedInlineAdminMixin.""" model = UserProfile extra = 0 # Test admin class with inline
UserProfileInline
python
encode__django-rest-framework
tests/test_validation_error.py
{ "start": 774, "end": 2161 }
class ____(TestCase): def setUp(self): self.DEFAULT_HANDLER = api_settings.EXCEPTION_HANDLER def exception_handler(exc, request): data = exc.get_full_details() return Response(data, status=status.HTTP_400_BAD_REQUEST) api_settings.EXCEPTION_HANDLER = exception_handl...
TestValidationErrorWithFullDetails
python
weaviate__weaviate-python-client
weaviate/users/users.py
{ "start": 519, "end": 587 }
class ____(UserBase): user_type: UserTypes = UserTypes.OIDC
UserOIDC
python
Lightning-AI__lightning
src/lightning/pytorch/callbacks/gradient_accumulation_scheduler.py
{ "start": 1139, "end": 6114 }
class ____(Callback): r"""Change gradient accumulation factor according to scheduling. Args: scheduling: scheduling in format {epoch: accumulation_factor} Note: The argument scheduling is a dictionary. Each key represent an epoch and its associated accumulation factor value. ...
GradientAccumulationScheduler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/override1.py
{ "start": 305, "end": 534 }
class ____: def method3(self) -> None: pass @overload def method5(self, x: int) -> int: ... @overload def method5(self, x: str) -> str: ... def method5(self, x: int | str) -> int | str: ...
ClassB
python
numba__numba
numba/cuda/cudamath.py
{ "start": 3788, "end": 3978 }
class ____(ConcreteTemplate): cases = [ signature(types.UniTuple(types.float64, 2), types.float64), signature(types.UniTuple(types.float32, 2), types.float32) ]
Math_modf
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_collections.py
{ "start": 59949, "end": 60331 }
class ____(MutableSet): def __init__(self, it=()): self.data = set(it) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __contains__(self, item): return item in self.data def add(self, item): self.data.add(item) ...
WithSet
python
ray-project__ray
python/ray/tests/autoscaler/test_providers.py
{ "start": 153, "end": 1063 }
class ____(unittest.TestCase): def test_node_providers(self): for provider_name, provider_cls in _NODE_PROVIDERS.items(): config = {"module": "ray.autoscaler._private"} try: provider_cls(config) except ImportError as e: if f"ray.autoscaler...
TestProviders
python
nmslib__hnswlib
tests/python/bindings_test_stress_mt_replace.py
{ "start": 54, "end": 2831 }
class ____(unittest.TestCase): def testRandomSelf(self): dim = 16 num_elements = 1_000 max_num_elements = 2 * num_elements # Generating sample data # batch 1 first_id = 0 last_id = num_elements labels1 = np.arange(first_id, last_id) data1 = np...
RandomSelfTestCase
python
getsentry__sentry
tests/sentry/notifications/test_notifications.py
{ "start": 2894, "end": 25152 }
class ____(APITestCase): """ Enable Slack AND email notification settings for a user """ def setUp(self) -> None: self.integration, _ = self.create_provider_integration_for( self.organization, self.user, provider="slack", name="Team A", ...
ActivityNotificationTest
python
viewflow__viewflow
tests/components/test_field_checkbox.py
{ "start": 949, "end": 1570 }
class ____(forms.Form): field = forms.BooleanField() urlpatterns = [ path( "", Site( viewsets=[ Application( title="Test Application", urlpatterns=[ path( "form/", ...
TestForm
python
django__django
tests/backends/tests.py
{ "start": 11591, "end": 25155 }
class ____(TransactionTestCase): available_apps = ["backends"] def create_squares_with_executemany(self, args): self.create_squares(args, "format", True) def create_squares(self, args, paramstyle, multiple): opts = Square._meta tbl = connection.introspection.identifier_converter(op...
BackendTestCase
python
huggingface__transformers
src/transformers/utils/dummy_pt_objects.py
{ "start": 13175, "end": 13435 }
class ____(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) def apply_chunking_to_forward(*args, **kwargs): requires_backends(apply_chunking_to_forward, ["torch"])
Conv1D
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 967129, "end": 967533 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field(SecurityVulnerability, gra...
SecurityVulnerabilityEdge
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink43.py
{ "start": 315, "end": 907 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink43.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workb...
TestCompareXLSXFiles
python
aimacode__aima-python
agents.py
{ "start": 1051, "end": 1813 }
class ____: """This represents any physical object that can appear in an Environment. You subclass Thing to get the things you want. Each thing can have a .__name__ slot (used for output only).""" def __repr__(self): return '<{}>'.format(getattr(self, '__name__', self.__class__.__name__)) ...
Thing
python
facebook__pyre-check
tools/generate_taint_models/tests/get_models_filtered_by_callable_test.py
{ "start": 792, "end": 1195 }
class ____(ModelGenerator[TestModel]): def gather_functions_to_model(self) -> Iterable[Callable[..., object]]: return [] def compute_models( self, functions_to_model: Iterable[Callable[..., object]] ) -> List[TestModel]: return [TestModel(0), TestModel(1), TestModel(2)] def is_eve...
TestModelGenerator
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
{ "start": 63366, "end": 64399 }
class ____: def test_get_start_date(self, client, session, create_task_instance): ti = create_task_instance( task_id="test_ti_update_state_reschedule_mysql_limit", state=State.RUNNING, start_date=timezone.datetime(2024, 1, 1), session=session, ) ...
TestGetRescheduleStartDate
python
automl__auto-sklearn
autosklearn/data/feature_validator.py
{ "start": 455, "end": 17533 }
class ____(BaseEstimator): """ Checks the input data to Auto-Sklearn. It also determines what columns are categorical and which ones are numerical, so that the pre-processing pipeline can process this columns accordingly. Attributes ---------- feat_type: Optional[List[str]] = None ...
FeatureValidator
python
Lightning-AI__lightning
examples/fabric/reinforcement_learning/rl/agent.py
{ "start": 3602, "end": 9238 }
class ____(LightningModule): def __init__( self, envs: gym.vector.SyncVectorEnv, act_fun: str = "relu", ortho_init: bool = False, vf_coef: float = 1.0, ent_coef: float = 0.0, clip_coef: float = 0.2, clip_vloss: bool = False, normalize_advantage...
PPOLightningAgent
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI049.py
{ "start": 95, "end": 153 }
class ____(typing.TypedDict): bar: int
_UnusedTypedDict2
python
huggingface__transformers
src/transformers/models/glm4v/modeling_glm4v.py
{ "start": 5968, "end": 12302 }
class ____(nn.Module): def __init__(self, config: Glm4vVisionConfig): super().__init__() self.config = config self.embed_dim = config.hidden_size self.image_size = config.image_size self.patch_size = config.patch_size self.num_patches = (self.image_size // self.patch...
Glm4vVisionEmbeddings
python
scipy__scipy
scipy/interpolate/_ndgriddata.py
{ "start": 563, "end": 12154 }
class ____(NDInterpolatorBase): """Nearest-neighbor interpolator in N > 1 dimensions. Methods ------- __call__ Parameters ---------- x : (npoints, ndims) 2-D ndarray of floats Data point coordinates. y : (npoints, ...) N-D ndarray of float or complex Data values. The le...
NearestNDInterpolator
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_dialect.py
{ "start": 34062, "end": 37703 }
class ____(fixtures.TestBase): __backend__ = True __only_on__ = "oracle" @testing.fixture def scalar_strings(self, connection): connection.exec_driver_sql( "CREATE OR REPLACE TYPE strings_t IS TABLE OF VARCHAR2 (100)" ) connection.exec_driver_sql( r""" CR...
TableValuedTest
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/completion/base.py
{ "start": 11053, "end": 12091 }
class ____(Completer): """ Completer class that can dynamically returns any Completer. :param get_completer: Callable that returns a :class:`.Completer` instance. """ def __init__(self, get_completer: Callable[[], Completer | None]) -> None: self.get_completer = get_completer def get_...
DynamicCompleter
python
python-markdown__markdown
tests/test_apis.py
{ "start": 6170, "end": 7195 }
class ____(unittest.TestCase): """ Test Markdown's `HtmlStash`. """ def setUp(self): self.stash = markdown.util.HtmlStash() self.placeholder = self.stash.store('foo') def testSimpleStore(self): """ Test `HtmlStash.store`. """ self.assertEqual(self.placeholder, self.stash.ge...
TestHtmlStash
python
ray-project__ray
python/ray/llm/tests/batch/gpu/processor/test_vllm_engine_proc.py
{ "start": 8670, "end": 10232 }
class ____: @pytest.mark.parametrize( "experimental_config", [ {"max_tasks_in_flight_per_actor": 10}, {}, ], ) def test_experimental_max_tasks_in_flight_per_actor_usage( self, experimental_config ): """Tests that max_tasks_in_flight_per_act...
TestVLLMEngineProcessorConfig
python
django-haystack__django-haystack
haystack/exceptions.py
{ "start": 539, "end": 672 }
class ____(HaystackError): """Raised when a model instance has not been provided for More Like This.""" pass
MoreLikeThisError
python
huggingface__transformers
src/transformers/models/olmo/modeling_olmo.py
{ "start": 15000, "end": 15536 }
class ____(PreTrainedModel): config: OlmoConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["OlmoDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True ...
OlmoPreTrainedModel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor24.py
{ "start": 993, "end": 1158 }
class ____(Container[int]): def increment(self): # This should generate an error if strictParameterNoneValue is false. self.value += 1
IntContainer
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 8006, "end": 8264 }
class ____(ActionTool): ''' A base class action tools acting on plots. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @abstract
PlotActionTool
python
pytorch__pytorch
test/test_testing.py
{ "start": 14366, "end": 17200 }
class ____(MultiProcessTestCase): @slowTest def test_throw_unrecoverable_cuda_exception(self, device): x = torch.rand(10, device=device) # cause unrecoverable CUDA exception, recoverable on CPU y = x[torch.tensor([25])].cpu() @slowTest def test_trivial_passing_test_case_on_cpu_...
TestThatContainsCUDAAssertFailure
python
kamyu104__LeetCode-Solutions
Python/count-subarrays-where-max-element-appears-at-least-k-times.py
{ "start": 564, "end": 1051 }
class ____(object): def countSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ mx = max(nums) result = (len(nums)+1)*len(nums)//2 left = cnt = 0 for right in xrange(len(nums)): cnt += int(nums[right] =...
Solution2
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels30.py
{ "start": 315, "end": 1734 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels30.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
PrefectHQ__prefect
src/integrations/prefect-docker/tests/test_containers.py
{ "start": 1978, "end": 2456 }
class ____: async def test_stop_kwargs(self, mock_docker_host: MagicMock): stop_kwargs = dict(container_id="42") with disable_run_logger(): container = await stop_docker_container.fn( docker_host=mock_docker_host, **stop_kwargs ) assert container.id ==...
TestStopDockerContainer
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/op_selection.py
{ "start": 847, "end": 1373 }
class ____: def __init__(self, query: Iterable[str]): self.query = query def resolve(self, graph_def: GraphDefinition) -> AbstractSet[str]: if any(["." in item for item in self.query]): resolved_node_paths = set(self.query) _validate_node_paths(resolved_node_paths, graph...
OpSelection
python
pytorch__pytorch
torch/_inductor/fx_passes/split_cat.py
{ "start": 44824, "end": 48761 }
class ____(SplitCatSimplifier): """ Helper class to merge Unbind->Cat/Stack. Many of the cases are similar to SplitCatSimplifier. Unbind can't be simplified like splits. So, we can only remove the unbind node. Other than this, other cases like multiple users, additional args, dim mismatch are similar t...
UnbindCatRemover
python
ipython__ipython
tests/test_ultratb.py
{ "start": 3893, "end": 4577 }
class ____(unittest.TestCase): """ Regression test for the following issues: https://github.com/ipython/ipython/issues/8293 https://github.com/ipython/ipython/issues/8205 """ def test_nested_genexpr(self): code = dedent( """\ class SpecificException(Exception): ...
NestedGenExprTestCase
python
pydata__xarray
xarray/core/options.py
{ "start": 5974, "end": 13716 }
class ____: """ Set options for xarray in a controlled context. Parameters ---------- arithmetic_join : {"inner", "outer", "left", "right", "exact"}, default: "inner" DataArray/Dataset alignment in binary operations: - "outer": use the union of object indexes - "inner": use...
set_options
python
getsentry__sentry
src/sentry/integrations/discord/message_builder/base/embed/base.py
{ "start": 938, "end": 2598 }
class ____: """ Represents a rich embed object. Some fields are not implemented, add to this as needed. https://discord.com/developers/docs/resources/channel#embed-object """ def __init__( self, title: str | None = None, description: str | None = None, url: str...
DiscordMessageEmbed
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/cdxgen.py
{ "start": 18526, "end": 27423 }
class ____(SbomApplicationJob): provider_id: str provider_version: str folder_name: str def get_job_name(self) -> str: return f"{self.provider_id}:{self.provider_version}:python{self.python_version}" def produce(self, output: Output | None, port: int, github_token: str | None) -> tuple[int...
SbomProviderJob
python
PyCQA__isort
isort/io.py
{ "start": 2067, "end": 2219 }
class ____(StringIO): def write(self, *args: Any, **kwargs: Any) -> None: # type: ignore # skipcq: PTC-W0049 pass Empty = _EmptyIO()
_EmptyIO
python
encode__httpx
httpx/_transports/asgi.py
{ "start": 1352, "end": 5501 }
class ____(AsyncBaseTransport): """ A custom AsyncTransport that handles sending requests directly to an ASGI app. ```python transport = httpx.ASGITransport( app=app, root_path="/submount", client=("1.2.3.4", 123) ) client = httpx.AsyncClient(transport=transport) ```...
ASGITransport
python
wireservice__csvkit
csvkit/cli.py
{ "start": 577, "end": 1552 }
class ____: """ A proxy for a File object that delays opening it until a read method is called. Currently this implements only the minimum methods to be useful, but it could easily be expanded. """ def __init__(self, init, *args, **kwargs): self.init = init self.f = None ...
LazyFile
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 131522, "end": 132121 }
class ____(sgqlc.types.Input): """Autogenerated input type of AddProjectColumn""" __schema__ = github_schema __field_names__ = ("project_id", "name", "client_mutation_id") project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId") """The Node ID of the project.""" name ...
AddProjectColumnInput
python
weaviate__weaviate-python-client
weaviate/backup/backup_location.py
{ "start": 550, "end": 684 }
class ____(_BackupLocationConfig): """The dynamic location of a backup for GCP.""" path: str bucket: str
_BackupLocationGCP
python
python-openxml__python-docx
src/docx/opc/pkgreader.py
{ "start": 8640, "end": 9588 }
class ____: """Read-only sequence of |_SerializedRelationship| instances corresponding to the relationships item XML passed to constructor.""" def __init__(self): super(_SerializedRelationships, self).__init__() self._srels = [] def __iter__(self): """Support iteration, e.g. 'f...
_SerializedRelationships
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column.py
{ "start": 104187, "end": 106138 }
class ____(_CategoricalColumn, collections.namedtuple( '_HashedCategoricalColumn', ['key', 'hash_bucket_size', 'dtype'])): """see `categorical_column_with_hash_bucket`.""" @property def name(self): return sel...
_HashedCategoricalColumn
python
jina-ai__jina
tests/k8s/conftest.py
{ "start": 338, "end": 8578 }
class ____: def __init__(self, kind_cluster: KindCluster, logger: JinaLogger) -> None: self._cluster = kind_cluster self._cluster.ensure_kubectl() self._kube_config_path = os.path.join( os.getcwd(), '.pytest-kind/pytest-kind/kubeconfig' ) self._log = logger ...
KindClusterWrapper
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 29817, "end": 36194 }
class ____(BaseTest): def test_str(self): mod = self.module() s = str(mod).strip() self.assertTrue(s.startswith('; ModuleID ='), s) def test_close(self): mod = self.module() str(mod) mod.close() with self.assertRaises(ctypes.ArgumentError): s...
TestModuleRef
python
lxml__lxml
src/lxml/tests/test_xpathevaluator.py
{ "start": 183, "end": 18401 }
class ____(HelperTestCase): """XPath tests etree""" def test_xpath_boolean(self): tree = self.parse('<a><b></b><b></b></a>') self.assertTrue(tree.xpath('boolean(/a/b)')) self.assertTrue(not tree.xpath('boolean(/a/c)')) def test_xpath_number(self): tree = self.parse('<a>1</a...
ETreeXPathTestCase
python
dagster-io__dagster
examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_omni_utils.py
{ "start": 259, "end": 2536 }
class ____(OmniWorkspace): async def fetch_omni_state(self) -> OmniWorkspaceData: """Returns mock Omni workspace data.""" # Create mock folder folder = OmniFolder( id="folder_1", name="Analytics", path="Analytics", scope="shared", ) ...
MockOmniWorkspace
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess25.py
{ "start": 1283, "end": 1378 }
class ____(ClassA[int]): pass ClassC.x = 1 ClassC.x del ClassC.x ClassC.x del ClassC.x
ClassC
python
scipy__scipy
scipy/optimize/tests/test__shgo.py
{ "start": 8304, "end": 10297 }
class ____(StructTestFunction): """ Test function with no feasible domain. """ def f(self, x, *args): return x[0] ** 2 + x[1] ** 2 def g1(x): return x[0] + x[1] - 1 def g2(x): return -(x[0] + x[1] - 1) def g3(x): return -x[0] + x[1] - 1 def g4(x): ...
StructTestInfeasible
python
PrefectHQ__prefect
src/prefect/blocks/notifications.py
{ "start": 15074, "end": 19467 }
class ____(AbstractAppriseNotificationBlock): """ Enables sending notifications via a provided Opsgenie webhook. See [Apprise notify_opsgenie docs](https://github.com/caronc/apprise/wiki/Notify_opsgenie) for more info on formatting the URL. Examples: Load a saved Opsgenie webhook and send a...
OpsgenieWebhook
python
django__django
django/contrib/auth/models.py
{ "start": 10936, "end": 15585 }
class ____(models.Model): """ Add the fields and methods necessary to support the Group and Permission models using the ModelBackend. """ is_superuser = models.BooleanField( _("superuser status"), default=False, help_text=_( "Designates that this user has all per...
PermissionsMixin
python
apache__airflow
providers/datadog/tests/unit/datadog/hooks/test_datadog.py
{ "start": 1370, "end": 4861 }
class ____: def setup_method(self): with mock.patch("airflow.providers.datadog.hooks.datadog.initialize"): with mock.patch("airflow.providers.datadog.hooks.datadog.DatadogHook.get_connection") as m: m.return_value = Connection( extra=json.dumps( ...
TestDatadogHook
python
charliermarsh__ruff
crates/ty_python_semantic/resources/corpus/77_class__class__.py
{ "start": 44, "end": 644 }
class ____: def test_various___class___pathologies(self): # See issue #12370 class X(): #A): def f(self): return super().f() __class__ = 413 x = X() class X: x = __class__ def f(): __class__ ...
Foo
python
doocs__leetcode
solution/1400-1499/1464.Maximum Product of Two Elements in an Array/Solution.py
{ "start": 0, "end": 224 }
class ____: def maxProduct(self, nums: List[int]) -> int: ans = 0 for i, a in enumerate(nums): for b in nums[i + 1 :]: ans = max(ans, (a - 1) * (b - 1)) return ans
Solution
python
matplotlib__matplotlib
lib/matplotlib/artist.py
{ "start": 48850, "end": 63911 }
class ____: """ A helper class to inspect an `~matplotlib.artist.Artist` and return information about its settable properties and their current values. """ def __init__(self, o): r""" Initialize the artist inspector with an `Artist` or an iterable of `Artist`\s. If an itera...
ArtistInspector
python
ray-project__ray
python/ray/util/client/common.py
{ "start": 22996, "end": 25777 }
class ____: """Holds the handles to the registered gRPC servicers and their server.""" task_servicer: ray_client_pb2_grpc.RayletDriverServicer data_servicer: ray_client_pb2_grpc.RayletDataStreamerServicer logs_servicer: ray_client_pb2_grpc.RayletLogStreamerServicer grpc_server: grpc.Server def...
ClientServerHandle
python
scipy__scipy
scipy/sparse/_data.py
{ "start": 476, "end": 4720 }
class ____(_spbase): def __init__(self, arg1, *, maxprint=None): _spbase.__init__(self, arg1, maxprint=maxprint) @property def dtype(self): return self.data.dtype @dtype.setter def dtype(self, newtype): self.data = self.data.view(newtype) def _deduped_data(self): ...
_data_matrix
python
cherrypy__cherrypy
cherrypy/process/wspbus.py
{ "start": 4579, "end": 5241 }
class ____(object): class State(object): name = None def __repr__(self): return 'states.%s' % self.name def __setattr__(self, key, value): if isinstance(value, self.State): value.name = key object.__setattr__(self, key, value) states = _StateEnum() sta...
_StateEnum
python
huggingface__transformers
src/transformers/models/conditional_detr/modeling_conditional_detr.py
{ "start": 21204, "end": 27304 }
class ____(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Here, we add position embeddings to the queries and keys (as explained in the DETR paper). """ def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, ...
DetrAttention
python
tox-dev__tox
src/tox/tox_env/python/pip/req/file.py
{ "start": 4080, "end": 4792 }
class ____: def __init__( self, filename: str, lineno: int, args: str, opts: Namespace, constraint: bool, # noqa: FBT001 ) -> None: self.filename = filename self.lineno = lineno self.opts = opts self.constraint = constraint ...
ParsedLine
python
scipy__scipy
scipy/special/tests/test_logit.py
{ "start": 3670, "end": 6470 }
class ____: def test_large_negative(self): x = np.array([-10000.0, -750.0, -500.0, -35.0]) y = log_expit(x) assert_equal(y, x) def test_large_positive(self): x = np.array([750.0, 1000.0, 10000.0]) y = log_expit(x) # y will contain -0.0, and -0.0 is used in the e...
TestLogExpit
python
eventlet__eventlet
tests/mock.py
{ "start": 9988, "end": 10474 }
class ____: """Access attributes to return a named object, usable as a sentinel.""" def __init__(self): self._sentinels = {} def __getattr__(self, name): if name == '__bases__': # Without this help(mock) raises an exception raise AttributeError return self._...
_Sentinel
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 255293, "end": 256423 }
class ____(Response): """ Response of tasks.make_public endpoint. :param updated: Number of tasks updated :type updated: int """ _service = "tasks" _action = "make_public" _version = "2.9" _schema = { "definitions": {}, "properties": { "updated": { ...
MakePublicResponse
python
huggingface__transformers
src/transformers/models/phi3/modular_phi3.py
{ "start": 4006, "end": 7284 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", conf...
Phi3Attention
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/qual_names_test.py
{ "start": 1069, "end": 6360 }
class ____(test.TestCase): def test_from_str(self): a = QN('a') b = QN('b') a_dot_b = QN(a, attr='b') a_sub_b = QN(a, subscript=b) self.assertEqual(qual_names.from_str('a.b'), a_dot_b) self.assertEqual(qual_names.from_str('a'), a) self.assertEqual(qual_names.from_str('a[b]'), a_sub_b) ...
QNTest
python
sqlalchemy__sqlalchemy
test/sql/test_external_traversal.py
{ "start": 1885, "end": 10817 }
class ____( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ): """test ClauseVisitor's traversal, particularly its ability to copy and modify a ClauseElement in place.""" @classmethod def setup_test_class(cls): global A, B # establish two fictitious ClauseElements. ...
TraversalTest
python
django__django
tests/m2m_through/models.py
{ "start": 2512, "end": 2772 }
class ____(models.Model): first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE) second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="+") date_friended = models.DateField() # Custom through link fields
SymmetricalFriendship
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_tensor_slices_test.py
{ "start": 1597, "end": 13245 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testFromTensorSlicesEmptyComponent(self): components = () with self.assertRaises(ValueError): dataset_ops.Dataset.from_tensor_slices(components) @combinations.generate(...
FromTensorSlicesTest
python
walkccc__LeetCode
solutions/2091. Removing Minimum and Maximum From Array/2091.py
{ "start": 0, "end": 224 }
class ____: def minimumDeletions(self, nums: list[int]) -> int: n = len(nums) a = nums.index(min(nums)) b = nums.index(max(nums)) if a > b: a, b = b, a return min(a + 1 + n - b, b + 1, n - a)
Solution
python
PrefectHQ__prefect
tests/test_serializers.py
{ "start": 3558, "end": 5716 }
class ____: @pytest.mark.parametrize("data", SERIALIZER_TEST_CASES) def test_simple_roundtrip(self, data): serializer = PickleSerializer() serialized = serializer.dumps(data) assert serializer.loads(serialized) == data @pytest.mark.parametrize("data", EXCEPTION_TEST_CASES) def t...
TestPickleSerializer
python
pytest-dev__pytest
src/_pytest/_py/path.py
{ "start": 5661, "end": 7161 }
class ____: if TYPE_CHECKING: @property def size(self) -> int: ... @property def mtime(self) -> float: ... def __getattr__(self, name: str) -> Any: return getattr(self._osstatresult, "st_" + name) def __init__(self, path, osstatresult): self.path = path ...
Stat
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_ls_commands.py
{ "start": 132, "end": 3096 }
class ____: """Test suite for ls commands.""" def setup_method(self): """Set up test fixtures.""" self.runner = CliRunner() def test_ls_symbols_with_package_dagster(self): """Test listing symbols from dagster package.""" result = self.runner.invoke(ls, ["symbols", "--packag...
TestLsCommands
python
pandas-dev__pandas
pandas/io/formats/excel.py
{ "start": 1173, "end": 1652 }
class ____: __fields__ = ("row", "col", "val", "style", "mergestart", "mergeend") __slots__ = __fields__ def __init__( self, row: int, col: int, val, style=None, mergestart: int | None = None, mergeend: int | None = None, ) -> None: self.r...
ExcelCell
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_privacy_urls.py
{ "start": 18989, "end": 19146 }
class ____(PublicUserProfileMixin, TestCase): def login(self): pass def is_admin(self): return False
PublicUserProfileUnauthAccessTest
python
docker__docker-py
tests/integration/api_container_test.py
{ "start": 30864, "end": 32635 }
class ____(BaseAPIIntegrationTest): def test_wait(self): res = self.client.create_container(TEST_IMG, ['sleep', '3']) id = res['Id'] self.tmp_containers.append(id) self.client.start(id) exitcode = self.client.wait(id)['StatusCode'] assert exitcode == 0 inspect...
WaitTest
python
neetcode-gh__leetcode
python/0355-design-twitter.py
{ "start": 0, "end": 1429 }
class ____: def __init__(self): self.count = 0 self.tweetMap = defaultdict(list) # userId -> list of [count, tweetIds] self.followMap = defaultdict(set) # userId -> set of followeeId def postTweet(self, userId: int, tweetId: int) -> None: self.tweetMap[userId].append([self.cou...
Twitter
python
getsentry__sentry
tests/sentry/release_health/test_tasks.py
{ "start": 22574, "end": 25790 }
class ____(TestMetricReleaseMonitor): def test_adopt_releases_respects_environment_and_threshold(self) -> None: # Empty environment should be ignored adopt_releases( self.organization.id, {self.project1.id: {"": {"releases": {"0.1": 1}, "total_sessions": 1}}}, ) ...
TestAdoptReleasesPath
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_container_upload_block_param.py
{ "start": 337, "end": 602 }
class ____(TypedDict, total=False): file_id: Required[str] type: Required[Literal["container_upload"]] cache_control: Optional[BetaCacheControlEphemeralParam] """Create a cache control breakpoint at this content block."""
BetaContainerUploadBlockParam
python
chardet__chardet
chardet/enums.py
{ "start": 152, "end": 322 }
class ____: """ This enum represents the different states a universal detector can be in. """ PURE_ASCII = 0 ESC_ASCII = 1 HIGH_BYTE = 2
InputState
python
google__pytype
pytype/tools/analyze_project/pytype_runner_test.py
{ "start": 2080, "end": 7814 }
class ____(unittest.TestCase): """Test deps_from_import_graph.""" def setUp(self): super().setUp() init = Local('/foo/bar/__init__.py', 'bar/__init__.py', 'bar') a = Local('/foo/bar/a.py', 'bar/a.py', 'bar.a') b = Local('/foo/bar/b.py', 'bar/b.py', 'bar.b') self.sources = [x.path for x in [init...
TestDepsFromImportGraph
python
jazzband__tablib
src/tablib/_vendor/dbfpy/fields.py
{ "start": 1568, "end": 6739 }
class ____: """Abstract field definition. Child classes must override ``type`` class attribute to provide datatype information of the field definition. For more info about types visit `https://www.clicketyclick.dk/databases/xbase/format/data_types.html` Also child classes must override ``defaultVa...
DbfFieldDef
python
catalyst-team__catalyst
catalyst/contrib/layers/pooling.py
{ "start": 985, "end": 1776 }
class ____(nn.Module): """Applies a 2D global max pooling operation over an input signal composed of several input planes. @TODO: Docs (add `Example`). Contribution is welcome. """ def __init__(self): """Constructor method for the ``GlobalMaxPool2d`` class.""" super().__init__() ...
GlobalMaxPool2d
python
django__django
django/template/backends/jinja2.py
{ "start": 334, "end": 1803 }
class ____(BaseEngine): app_dirname = "jinja2" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() super().__init__(params) self.context_processors = options.pop("context_processors", []) environment = options.pop("environment", "j...
Jinja2
python
gevent__gevent
src/greentest/3.9/test_httplib.py
{ "start": 52207, "end": 55116 }
class ____(TestCase): def test_all(self): # Documented objects defined in the module should be in __all__ expected = {"responses"} # Allowlist documented dict() object # HTTPMessage, parse_headers(), and the HTTP status code constants are # intentionally omitted for simplicity ...
OfflineTest
python
joke2k__faker
faker/providers/internet/pt_BR/__init__.py
{ "start": 46, "end": 607 }
class ____(InternetProvider): safe_email_tlds = ("com", "net", "br", "br") free_email_domains = ( "gmail.com", "hotmail.com", "yahoo.com.br", "uol.com.br", "bol.com.br", "ig.com.br", ) tlds = ("com", "com", "com", "net", "org", "br", "br", "br") replac...
Provider
python
numpy__numpy
benchmarks/benchmarks/bench_function_base.py
{ "start": 5311, "end": 6769 }
class ____(Benchmark): """ This benchmark tests sorting performance with several different types of arrays that are likely to appear in real-world applications. """ params = [ # In NumPy 1.17 and newer, 'merge' can be one of several # stable sorts, it isn't necessarily merge sort...
Sort
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/5_Deep_Q_Network/maze_env.py
{ "start": 589, "end": 4165 }
class ____(tk.Tk, object): def __init__(self): super(Maze, self).__init__() self.action_space = ['u', 'd', 'l', 'r'] self.n_actions = len(self.action_space) self.n_features = 2 self.title('maze') self.geometry('{0}x{1}'.format(MAZE_W * UNIT, MAZE_H * UNIT)) se...
Maze
python
getsentry__sentry
src/sentry/codecov/client.py
{ "start": 795, "end": 932 }
class ____(SentryAPIException): status_code = status.HTTP_500_INTERNAL_SERVER_ERROR code = "configuration-error"
ConfigurationError
python
kamyu104__LeetCode-Solutions
Python/find-the-longest-valid-obstacle-course-at-each-position.py
{ "start": 510, "end": 3009 }
class ____(object): # 0-based index def __init__(self, N, build_fn=lambda x, y: [y]*(2*x), query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y)) update_fn=lambda x, y: y, default_val=0): self....
SegmentTree
python
getsentry__sentry
src/sentry/sentry_apps/models/sentry_app.py
{ "start": 2882, "end": 9846 }
class ____(ParanoidModel, HasApiScopes, Model): __relocation_scope__ = RelocationScope.Global application = models.OneToOneField( "sentry.ApiApplication", null=True, on_delete=models.SET_NULL, related_name="sentry_app" ) # Much of the OAuth system in place currently depends on a User existing....
SentryApp
python
doocs__leetcode
solution/2500-2599/2532.Time to Cross a Bridge/Solution.py
{ "start": 0, "end": 1595 }
class ____: def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: time.sort(key=lambda x: x[0] + x[2]) cur = 0 wait_in_left, wait_in_right = [], [] work_in_left, work_in_right = [], [] for i in range(k): heappush(wait_in_left, -i) while...
Solution
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 36633, "end": 36862 }
class ____(BoringModel): def on_validation_batch_end(self, outputs, batch, batch_idx): if not self.trainer.sanity_checking and batch_idx == 1: raise RuntimeError("Trouble!")
TroubledModelOnValidationBatchEnd