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
getsentry__sentry
src/sentry/testutils/factories.py
{ "start": 8323, "end": 14689 }
class ____(Enum): ERROR = "error" DEFAULT = "default" def get_fixture_path(*parts: str) -> str: path = os.path.realpath(__file__) for _ in range(4): # src/sentry/testutils/{__file__} path = os.path.dirname(path) return os.path.join(path, "fixtures", *parts) def make_sentence(words=None)...
EventType
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-paint-n-3-grid.py
{ "start": 876, "end": 1206 }
class ____(object): def numOfWays(self, n): """ :type n: int :rtype: int """ MOD = 10**9 + 7 aba, abc = 6, 6 for _ in xrange(n-1): aba, abc = (3*aba%MOD + 2*abc%MOD)%MOD, \ (2*abc%MOD + 2*aba%MOD)%MOD return (aba+abc)...
Solution2
python
jpadilla__pyjwt
jwt/api_jwk.py
{ "start": 5853, "end": 6135 }
class ____: def __init__(self, jwk_set: PyJWKSet): self.jwk_set = jwk_set self.timestamp = time.monotonic() def get_jwk_set(self) -> PyJWKSet: return self.jwk_set def get_timestamp(self) -> float: return self.timestamp
PyJWTSetWithTimestamp
python
walkccc__LeetCode
solutions/302. Smallest Rectangle Enclosing Black Pixels/302.py
{ "start": 0, "end": 857 }
class ____: def minArea(self, image: list[list[str]], x: int, y: int) -> int: DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(image) n = len(image[0]) topLeft = [x, y] bottomRight = [x, y] q = collections.deque([(x, y)]) image[x][y] = '2' # Mark as visited. while q: i, j = q....
Solution
python
pytorch__pytorch
tools/linter/adapters/pylint_linter.py
{ "start": 209, "end": 312 }
class ____(str, Enum): ERROR = "error" WARNING = "warning" DISABLED = "disabled"
LintSeverity
python
scrapy__scrapy
tests/test_engine.py
{ "start": 2544, "end": 2697 }
class ____(MySpider): async def start(self): for url in self.start_urls: yield Request(url) # no dont_filter=True
DupeFilterSpider
python
realpython__materials
python-assignment-statements/point_descriptor.py
{ "start": 0, "end": 386 }
class ____: def __set_name__(self, owner, name): self._name = name def __get__(self, instance, owner): return instance.__dict__[self._name] def __set__(self, instance, value): try: instance.__dict__[self._name] = float(value) except ValueError: raise...
Coordinate
python
huggingface__transformers
src/transformers/models/udop/processing_udop.py
{ "start": 994, "end": 1171 }
class ____(TextKwargs, total=False): word_labels: Optional[Union[list[int], list[list[int]]]] boxes: Optional[Union[list[list[int]], list[list[list[int]]]]]
UdopTextKwargs
python
django-haystack__django-haystack
haystack/exceptions.py
{ "start": 100, "end": 203 }
class ____(HaystackError): """Raised when a backend can not be found.""" pass
SearchBackendError
python
pytorch__pytorch
torch/_inductor/loop_body.py
{ "start": 2543, "end": 17661 }
class ____: """ Captures the body of a Loops subclass into an FX graph. Persists any indexing simplifications and makes it easier to analyze loop bodies. """ indexing_exprs: dict[str, sympy.Expr] submodules: dict[str, Any] subblocks: dict[str, LoopBodyBlock] indirect_vars: list[sympy.S...
LoopBody
python
bokeh__bokeh
src/bokeh/protocol/messages/server_info_reply.py
{ "start": 1669, "end": 3097 }
class ____(Message[ServerInfo]): ''' Define the ``SERVER-INFO-REPLY`` message for replying to Server info requests from clients. The ``content`` fragment of for this message is has the form: .. code-block:: python { 'version_info' : { 'bokeh' : <bokeh library vers...
server_info_reply
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 2264, "end": 7421 }
class ____(GoogleCloudBaseOperator): """ Creates an entry. Currently only entries of 'FILESET' type can be created. The newly created entry ID are saved under the ``entry_id`` key in XCOM. .. seealso:: For more information on how to use this operator, take a look at the guide: :re...
CloudDataCatalogCreateEntryOperator
python
python-poetry__poetry
src/poetry/console/commands/self/show/plugins.py
{ "start": 1063, "end": 3990 }
class ____(SelfCommand): name = "self show plugins" description = "Shows information about the currently installed plugins." help = """\ The <c1>self show plugins</c1> command lists all installed Poetry plugins. Plugins can be added and removed using the <c1>self add</c1> and <c1>self remove</c1> \ command...
SelfShowPluginsCommand
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 13328, "end": 14927 }
class ____(AggregateFnV2[Union[int, float], Union[int, float]]): """Defines sum aggregation. Example: .. testcode:: import ray from ray.data.aggregate import Sum ds = ray.data.range(100) # Schema: {'id': int64} ds = ds.add_column("group_key...
Sum
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 17415, "end": 17546 }
class ____(_TestIDSTBase): def setup_method(self): self.rdt = int self.dec = 4 self.type = 1
TestIDSTIInt
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py
{ "start": 4534, "end": 5636 }
class ____(Benchmark): r""" Alpine01 objective function. The Alpine01 [1]_ global optimization problem is a multimodal minimization problem defined as follows: .. math:: f_{\text{Alpine01}}(x) = \sum_{i=1}^{n} \lvert {x_i \sin \left( x_i \right) + 0.1 x_i} \rvert Here, :mat...
Alpine01
python
celery__celery
celery/events/state.py
{ "start": 4524, "end": 7844 }
class ____: """Worker State.""" heartbeat_max = 4 expire_window = HEARTBEAT_EXPIRE_WINDOW _fields = ('hostname', 'pid', 'freq', 'heartbeats', 'clock', 'active', 'processed', 'loadavg', 'sw_ident', 'sw_ver', 'sw_sys') if not PYPY: # pragma: no cover __slots__ ...
Worker
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_explore_arbitrary_languages.py
{ "start": 907, "end": 963 }
class ____: value: Any child: Any @dataclass
Write
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 110828, "end": 111857 }
class ____(ServerAdapter): def run(self, app): # pragma: no cover from wsgiref.simple_server import WSGIRequestHandler, WSGIServer from wsgiref.simple_server import make_server import socket class FixedHandler(WSGIRequestHandler): def address_string(self): # Prevent reve...
WSGIRefServer
python
huggingface__transformers
tests/models/llava_onevision/test_image_processing_llava_onevision.py
{ "start": 3205, "end": 13816 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = LlavaOnevisionImageProcessor if is_vision_available() else None fast_image_processing_class = LlavaOnevisionImageProcessorFast if is_torchvision_available() else None # Copied from tests.models.clip.test_image_processing_clip...
LlavaOnevisionImageProcessingTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker_unified_studio.py
{ "start": 1515, "end": 6888 }
class ____(BaseOperator): """ Provides Artifact execution functionality for Sagemaker Unified Studio Workflows. Examples: .. code-block:: python from airflow.providers.amazon.aws.operators.sagemaker_unified_studio import SageMakerNotebookOperator notebook_operator = SageMakerNotebook...
SageMakerNotebookOperator
python
apache__airflow
providers/standard/tests/unit/standard/operators/test_python.py
{ "start": 49140, "end": 68513 }
class ____(BaseTestPythonVirtualenvOperator): opcls = PythonVirtualenvOperator @staticmethod def default_kwargs(*, python_version=DEFAULT_PYTHON_VERSION, **kwargs): kwargs["python_version"] = python_version if "do_not_use_caching" in kwargs: kwargs.pop("do_not_use_caching") ...
TestPythonVirtualenvOperator
python
walkccc__LeetCode
solutions/3109. Find the Index of Permutation/3109.py
{ "start": 421, "end": 955 }
class ____: def getPermutationIndex(self, perm: list[int]) -> int: MOD = 1_000_000_007 n = len(perm) ans = 0 tree = FenwickTree(n) fact = [1] * (n + 1) # fact[i] := i! for i in range(2, n + 1): fact[i] = (fact[i - 1] * i) % MOD for i, num in enumerate(perm): # the number of ...
Solution
python
psf__black
src/blib2to3/pgen2/pgen.py
{ "start": 13135, "end": 13502 }
class ____: arcs: list[tuple[str | None, "NFAState"]] def __init__(self) -> None: self.arcs = [] # list of (label, NFAState) pairs def addarc(self, next: "NFAState", label: str | None = None) -> None: assert label is None or isinstance(label, str) assert isinstance(next, NFAState)...
NFAState
python
huggingface__transformers
src/transformers/models/internvl/modular_internvl.py
{ "start": 2678, "end": 4837 }
class ____(JanusVisionAttention): def __init__(self, config: InternVLVisionConfig): super().__init__(config) del self.num_key_value_groups # Needed for flash attention self.is_causal = False qk_norm = config.use_qk_norm self.q_norm = InternVLVisionRMSNorm(self.embed...
InternVLVisionAttention
python
pdm-project__pdm
tests/fixtures/projects/test-plugin-pdm/hello.py
{ "start": 48, "end": 380 }
class ____(BaseCommand): """Say hello to somebody""" def add_arguments(self, parser): parser.add_argument("-n", "--name", help="the person's name") def handle(self, project, options): print(f"Hello, {options.name or 'world'}") def main(core): core.register_command(HelloCommand, "hell...
HelloCommand
python
google__jax
tests/package_structure_test.py
{ "start": 958, "end": 3159 }
class ____(jtu.JaxTestCase): @parameterized.parameters([ # TODO(jakevdp): expand test to other public modules. _mod("jax.errors", exclude=["JaxRuntimeError"]), _mod( "jax.numpy", exclude=[ "array_repr", "array_str", "can_cast", ...
PackageStructureTest
python
apache__airflow
providers/ftp/tests/unit/ftp/operators/test_ftp.py
{ "start": 1271, "end": 8095 }
class ____: def setup_method(self): self.test_local_dir = "ftptmp" self.test_remote_dir = "/ftphome" self.test_remote_dir_int = "/ftphome/interdir" self.test_local_filename = "test_local_file" self.test_remote_filename = "test_remote_file" self.test_local_filepath = f...
TestFTPFileTransmitOperator
python
kamyu104__LeetCode-Solutions
Python/path-crossing.py
{ "start": 29, "end": 536 }
class ____(object): def isPathCrossing(self, path): """ :type path: str :rtype: bool """ x = y = 0 lookup = {(0, 0)} for c in path: if c == 'E': x += 1 elif c == 'W': x -= 1 elif c == 'N': ...
Solution
python
fastai__fastai
fastai/vision/augment.py
{ "start": 41293, "end": 42466 }
class ____(AffineCoordTfm): "Apply perspective warping with `magnitude` and `p` on a batch of matrices" def __init__(self, magnitude:float=0.2, # The default warping magnitude p:float=0.5, # Probability of applying warp draw_x:float|MutableSequence|Callable=None, # User defined warping ...
Warp
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/missingSuper1.py
{ "start": 436, "end": 635 }
class ____(ParentA, ParentB): # This should generate an error. def __init__(self): pass # This should generate an error. def __init_subclass__(cls) -> None: pass
ChildA
python
openai__openai-python
src/openai/resources/beta/assistants.py
{ "start": 46958, "end": 47597 }
class ____: def __init__(self, assistants: AsyncAssistants) -> None: self._assistants = assistants self.create = async_to_streamed_response_wrapper( assistants.create, ) self.retrieve = async_to_streamed_response_wrapper( assistants.retrieve, ) ...
AsyncAssistantsWithStreamingResponse
python
joke2k__faker
faker/providers/date_time/fr_FR/__init__.py
{ "start": 46, "end": 785 }
class ____(DateTimeProvider): DAY_NAMES = { "0": "dimanche", "1": "lundi", "2": "mardi", "3": "mercredi", "4": "jeudi", "5": "vendredi", "6": "samedi", } MONTH_NAMES = { "01": "Janvier", "02": "Février", "03": "Mars", "0...
Provider
python
simonw__datasette
datasette/permissions.py
{ "start": 847, "end": 3739 }
class ____(ABC): """ Base class for all resource types. Each subclass represents a type of resource (e.g., TableResource, DatabaseResource). The class itself carries metadata about the resource type. Instances represent specific resources. """ # Class-level metadata (subclasses must define...
Resource
python
apache__airflow
airflow-core/src/airflow/serialization/json_schema.py
{ "start": 1106, "end": 2445 }
class ____(Protocol): """ This class is only used for type checking. A workaround for IDEs, mypy, etc. due to the way ``Draft7Validator`` is created. They are created or do not inherit from proper classes. Hence, you can not have ``type: Draft7Validator``. """ schema: dict def is_vali...
Validator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 19496, "end": 20355 }
class ____(Metafield): """ { productVariants(query: "updated_at:>='2023-02-07T00:00:00+00:00' AND updated_at:<='2023-12-04T00:00:00+00:00'") { edges { node { id metafields { edges { no...
MetafieldProductVariant
python
jazzband__django-simple-history
simple_history/tests/tests/utils.py
{ "start": 2126, "end": 3554 }
class ____: def db_for_read(self, model, **hints): # Avoids circular importing from ..models import HistoricalModelWithHistoryInDifferentDb if model == HistoricalModelWithHistoryInDifferentDb: return OTHER_DB_NAME return None def db_for_write(self, model, **hints): ...
TestModelWithHistoryInDifferentDbRouter
python
davidhalter__jedi
jedi/inference/base_value.py
{ "start": 13759, "end": 18219 }
class ____: def __init__(self, iterable): self._set = frozenset(iterable) for value in iterable: assert not isinstance(value, ValueSet) @classmethod def _from_frozen_set(cls, frozenset_): self = cls.__new__(cls) self._set = frozenset_ return self @cl...
ValueSet
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 223772, "end": 224977 }
class ____(Response): """ Response of tasks.edit_configuration endpoint. :param updated: Indicates if the task was updated successfully :type updated: int """ _service = "tasks" _action = "edit_configuration" _version = "2.13" _schema = { "definitions": {}, "propert...
EditConfigurationResponse
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/links/stackdriver.py
{ "start": 1176, "end": 1433 }
class ____(BaseGoogleLink): """Helper class for constructing Stackdriver Notifications Link.""" name = "Cloud Monitoring Notifications" key = "stackdriver_notifications" format_str = STACKDRIVER_NOTIFICATIONS_LINK
StackdriverNotificationsLink
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 597506, "end": 627007 }
class ____( FieldChannelMixin, core.FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull, ): r""" Stroke schema wrapper. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, and type aggregate : dict, :class:`Ag...
Stroke
python
matplotlib__matplotlib
lib/matplotlib/tests/test_mlab.py
{ "start": 603, "end": 8329 }
class ____: def setup_method(self): np.random.seed(0) n = 1000 x = np.linspace(0., 100, n) self.sig_zeros = np.zeros(n) self.sig_off = self.sig_zeros + 100. self.sig_slope = np.linspace(-10., 90., n) self.sig_slope_mean = x - x.mean() self.sig_base ...
TestDetrend
python
django__django
tests/model_enums/tests.py
{ "start": 630, "end": 756 }
class ____(models.IntegerChoices): CAR = 1, "Carriage" TRUCK = 2 JET_SKI = 3 __empty__ = _("(Unknown)")
Vehicle
python
scipy__scipy
scipy/optimize/_differentiable_functions.py
{ "start": 29316, "end": 29960 }
class ____(LinearVectorFunction): """Identity vector function and its derivatives. The Jacobian is the identity matrix, returned as a dense array when `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is identically zero and it is returned as a csr matrix. """ def __init__(self...
IdentityVectorFunction
python
python__mypy
mypy/patterns.py
{ "start": 3339, "end": 4048 }
class ____(Pattern): """The pattern Cls(...)""" class_ref: RefExpr positionals: list[Pattern] keyword_keys: list[str] keyword_values: list[Pattern] def __init__( self, class_ref: RefExpr, positionals: list[Pattern], keyword_keys: list[str], keyword_value...
ClassPattern
python
numpy__numpy
numpy/_core/tests/test_indexing.py
{ "start": 22257, "end": 22549 }
class ____: def test_scalar_return_type(self): # Field access on an array should return an array, even if it # is 0-d. a = np.zeros((), [('a', 'f8')]) assert_(isinstance(a['a'], np.ndarray)) assert_(isinstance(a[['a']], np.ndarray))
TestFieldIndexing
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_dataflow.py
{ "start": 29236, "end": 34348 }
class ____: def test_serialize(self, dataflow_start_yaml_job_trigger): actual_data = dataflow_start_yaml_job_trigger.serialize() expected_data = ( "airflow.providers.google.cloud.triggers.dataflow.DataflowStartYamlJobTrigger", { "project_id": PROJECT_ID, ...
TestDataflowStartYamlJobTrigger
python
kamyu104__LeetCode-Solutions
Python/minimize-or-of-remaining-elements-using-operations.py
{ "start": 52, "end": 635 }
class ____(object): def minOrAfterOperations(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ result = 0 l = max(nums).bit_length() mask = (1<<l)-1 for i in reversed(xrange(l)): result <<= 1 curr, c...
Solution
python
scipy__scipy
benchmarks/benchmarks/peak_finding.py
{ "start": 1072, "end": 1523 }
class ____(Benchmark): """Benchmark `scipy.signal.peak_widths`.""" param_names = ['rel_height'] params = [[0, 0.25, 0.5, 0.75, 1]] def setup(self, rel_height): self.x = electrocardiogram() self.peaks = find_peaks(self.x)[0] self.prominence_data = peak_prominences(self.x, self.p...
PeakWidths
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 246754, "end": 247397 }
class ____(Structure): _fields_ = [ ("lowPwrThreshold", c_uint), ] def nvmlDeviceSetNvLinkDeviceLowPowerThreshold(device, l1threshold): c_info = c_nvmlNvLinkPowerThres_t() c_info.lowPwrThreshold = l1threshold fn = _nvmlGetFunctionPointer("nvmlDeviceSetNvLinkDeviceLowPowerThreshold") ret...
c_nvmlNvLinkPowerThres_t
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 30262, "end": 32025 }
class ____(test.Benchmark): def _benchmarkResize(self, image_size, num_channels): batch_size = 1 num_ops = 1000 img = variables.Variable( random_ops.random_normal( [batch_size, image_size[0], image_size[1], num_channels]), name="img") deps = [] for _ in range(num_ops)...
ResizeBicubicBenchmark
python
django-guardian__django-guardian
guardian/mixins.py
{ "start": 838, "end": 2506 }
class ____: """A login required mixin for use with class-based views. This Class is a light wrapper around the Django `login_required` decorator, function parameters are instead attributes defined on the class. Due to Python Method Resolution Order (MRO), this mixin must be added as the left most ...
LoginRequiredMixin
python
ray-project__ray
python/ray/tests/test_multi_node_3.py
{ "start": 8044, "end": 13068 }
class ____: def __init__(self, val: Optional[int]): self.val: Optional[int] = val def custom_serializer(o: CustomObject) -> int: return o.val * multiplier def custom_deserializer(val: int) -> CustomObject: return CustomObject(val) ray.util.register_serializer( CustomObject, serializer=cus...
CustomObject
python
django__django
tests/invalid_models_tests/test_relative_fields.py
{ "start": 84133, "end": 92282 }
class ____(TestCase): def test_db_cascade_support(self): class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, models.DB_CASCADE) field = Child._meta.get_field("parent") expected = ( [] if con...
DatabaseLevelOnDeleteTests
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/read_relationships/tutorial001.py
{ "start": 338, "end": 3852 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship...
Hero
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 68316, "end": 68672 }
class ____(BaseDataset): """ Retrieval of a single field from a scalar compound dataset should strip the field info """ def test_scalar_compound(self): dt = np.dtype([('a', 'i')]) dset = self.f.create_dataset(make_name(), (), dtype=dt) self.assertEqual(dset['a'].dt...
TestScalarCompound
python
dagster-io__dagster
python_modules/libraries/dagster-fivetran/dagster_fivetran_tests/test_asset_specs.py
{ "start": 10908, "end": 13235 }
class ____(DagsterFivetranTranslator): def get_asset_spec(self, props: FivetranConnectorTableProps) -> AssetSpec: default_spec = super().get_asset_spec(props) return default_spec.replace_attributes( key=["wacky", *["".join(reversed(item)) for item in default_spec.key.path], "wow"], ...
MyCustomTranslatorWackyKeys
python
lxml__lxml
src/lxml/tests/test_relaxng.py
{ "start": 258, "end": 6839 }
class ____(HelperTestCase): def test_relaxng(self): tree_valid = self.parse('<a><b></b></a>') tree_invalid = self.parse('<a><c></c></a>') schema = self.parse('''\ <element name="a" xmlns="http://relaxng.org/ns/structure/1.0"> <zeroOrMore> <element name="b"> <text /> </elem...
ETreeRelaxNGTestCase
python
django__django
django/views/generic/edit.py
{ "start": 5619, "end": 5714 }
class ____(FormMixin, ProcessFormView): """A base view for displaying a form."""
BaseFormView
python
pytest-dev__pytest
testing/test_recwarn.py
{ "start": 2471, "end": 4335 }
class ____: def test_recording(self) -> None: rec = WarningsRecorder(_ispytest=True) with rec: assert not rec.list warnings.warn_explicit("hello", UserWarning, "xyz", 13) assert len(rec.list) == 1 warnings.warn(DeprecationWarning("hello")) ...
TestWarningsRecorderChecker
python
kennethreitz__tablib
src/tablib/formats/_dbf.py
{ "start": 169, "end": 1951 }
class ____: title = 'dbf' extensions = ('csv',) DEFAULT_ENCODING = 'utf-8' @classmethod def export_set(cls, dataset): """Returns DBF representation of a Dataset""" new_dbf = dbfnew.dbf_new() temp_file, temp_uri = tempfile.mkstemp() # create the appropriate fields b...
DBFFormat
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/enum1.py
{ "start": 7849, "end": 7970 }
class ____(Enum, metaclass=CustomEnumMeta1): @property def value(self) -> str: return "test"
TestEnum21Base
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/models.py
{ "start": 2705, "end": 2770 }
class ____(models.Model): file1 = models.FileField()
FileFields
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/project.py
{ "start": 317, "end": 1582 }
class ____(serializers.Field): def __init__( self, scope: str | Collection[str] = "project:write", id_allowed: bool = False, **kwags ): """ The scope parameter specifies which permissions are required to access the project field. If multiple scopes are provided, the project can b...
ProjectField
python
encode__starlette
tests/test_routing.py
{ "start": 30580, "end": 42291 }
class ____: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: scope["add_headers_middleware"] = True async def modified_send(msg: Message) -> None: if msg["type"] == "http.response.start": ...
AddHeadersMiddleware
python
huggingface__transformers
tests/models/vitpose/test_modeling_vitpose.py
{ "start": 8326, "end": 12340 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( VitPoseImageProcessor.from_pretrained("usyd-community/vitpose-base-simple") if is_vision_available() else None ) @slow def test_inference_pose_estimation(self)...
VitPoseModelIntegrationTest
python
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 17203, "end": 30629 }
class ____(urllib3.Retry): """ urllib3 Retry class does not allow us to retry on read errors but to exclude read timeout. Retrying after a timeout adds useless load to Snuba. """ def increment( self, method=None, url=None, response=None, error=None, _...
RetrySkipTimeout
python
bokeh__bokeh
src/bokeh/models/mappers.py
{ "start": 10157, "end": 10755 }
class ____(ScanningColorMapper): ''' ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) bins = Int(default=256*256, help="Number of histogram bins") rescale_discrete_levels = Bool(default=False, ...
EqHistColorMapper
python
ethereum__web3.py
tests/core/providers/test_websocket_provider.py
{ "start": 852, "end": 18978 }
class ____(Exception): pass GET_BLOCK_JSON_MESSAGE = { "id": 0, "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", False], } def test_get_endpoint_uri_or_ipc_path_returns_endpoint_uri(): provider = WebSocketProvider("ws://mocked") assert ( provider.get_endpo...
WSException
python
pytorch__pytorch
torch/_inductor/compile_fx_ext.py
{ "start": 6874, "end": 7313 }
class ____: value: bytes def deserialize(self) -> _WireProtocolInput: """ Turn this streamable object back into a _WireProtocolInput. """ from torch.fx._graph_pickler import GraphPickler fake_mode = _current_fake_mode() result = GraphPickler.loads(self.value, fa...
_WireProtocolPickledInput
python
networkx__networkx
networkx/algorithms/tests/test_clique.py
{ "start": 101, "end": 7547 }
class ____: def setup_method(self): z = [3, 4, 3, 4, 2, 4, 2, 1, 1, 1, 1] self.G = cnlti(nx.generators.havel_hakimi_graph(z), first_label=1) self.cl = list(nx.find_cliques(self.G)) H = nx.complete_graph(6) H = nx.relabel_nodes(H, {i: i + 1 for i in range(6)}) H.remove...
TestCliques
python
sympy__sympy
sympy/vector/dyadic.py
{ "start": 5689, "end": 7167 }
class ____(Dyadic, AtomicExpr): """ Class to denote a base dyadic tensor component. """ def __new__(cls, vector1, vector2): Vector = sympy.vector.Vector BaseVector = sympy.vector.BaseVector VectorZero = sympy.vector.VectorZero # Verify arguments if not isinstance...
BaseDyadic
python
nedbat__coveragepy
tests/test_html.py
{ "start": 55959, "end": 57008 }
class ____(HtmlTestHelpers, CoverageTest): """Tests of the helpers in HtmlTestHelpers.""" def test_bad_link(self) -> None: # Does assert_valid_hrefs detect links to non-existent files? self.make_file("htmlcov/index.html", "<a href='nothing.html'>Nothing</a>") msg = "These files link to ...
HtmlHelpersTest
python
astropy__astropy
astropy/coordinates/builtin_frames/equatorial.py
{ "start": 3843, "end": 4865 }
class ____(BaseCoordinateFrame): """ A coordinate or frame in the True Equator Mean Equinox frame (TEME). This frame is a geocentric system similar to CIRS or geocentric apparent place, except that the mean sidereal time is used to rotate from TIRS. TEME coordinates are most often used in combinati...
TEME
python
django__django
tests/admin_inlines/models.py
{ "start": 8608, "end": 8731 }
class ____(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name
Course
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks_test.py
{ "start": 57464, "end": 61949 }
class ____(test.TestCase): def setUp(self): super(ProfilerHookTest, self).setUp() self.output_dir = tempfile.mkdtemp() self.graph = ops.Graph() self.filepattern = os.path.join(self.output_dir, 'timeline-*.json') with self.graph.as_default(): self.global_step = training_util.get_or_create_gl...
ProfilerHookTest
python
RaRe-Technologies__gensim
gensim/test/test_word2vec.py
{ "start": 1523, "end": 53068 }
class ____(unittest.TestCase): def test_build_vocab_from_freq(self): """Test that the algorithm is able to build vocabulary from given frequency table""" freq_dict = { 'minors': 2, 'graph': 3, 'system': 4, 'trees': 3, 'eps': 2, 'computer': 2, 'survey': 2, 'user': 3, '...
TestWord2VecModel
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_take.py
{ "start": 46, "end": 3229 }
class ____: def test_take_slices_not_supported(self, float_frame): # GH#51539 df = float_frame slc = slice(0, 4, 1) with pytest.raises(TypeError, match="slice"): df.take(slc, axis=0) with pytest.raises(TypeError, match="slice"): df.take(slc, axis=1) ...
TestDataFrameTake
python
keras-team__keras
keras/src/layers/rnn/simple_rnn_test.py
{ "start": 130, "end": 9276 }
class ____(testing.TestCase): @pytest.mark.requires_trainable_backend def test_basics(self): self.run_layer_test( layers.SimpleRNN, init_kwargs={"units": 3, "dropout": 0.5, "recurrent_dropout": 0.5}, input_shape=(3, 2, 4), call_kwargs={"training": True}, ...
SimpleRNNTest
python
scipy__scipy
scipy/linalg/tests/test_basic.py
{ "start": 83698, "end": 86145 }
class ____: def test_matrix_norms(self): # Not all of these are matrix norms in the most technical sense. rng = np.random.default_rng(1234) for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4): for t in np.float32, np.float64, np.complex64, np.complex128, np.int64: ...
TestMatrixNorms
python
spack__spack
lib/spack/spack/util/unparse/unparser.py
{ "start": 1005, "end": 2634 }
class ____(object): """ A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the `visit` method. This class is meant to be subclassed, with the subclass adding visitor methods. ...
NodeVisitor
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 228998, "end": 249281 }
class ____(TypedDict, total=False): """ :class:`altair.RectConfig` ``TypedDict`` wrapper. Parameters ---------- align The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of ``"left"``, ``"right"``, ``"center"``. **Note:** Expression refe...
RectConfigKwds
python
joke2k__faker
tests/providers/test_credit_card.py
{ "start": 6373, "end": 7852 }
class ____: mastercard_pattern: Pattern = re.compile( r"(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}", ) visa_pattern: Pattern = re.compile(r"4[0-9]{12}([0-9]{3}){0,2}") maestro_pattern: Pattern = re.compile(r"(67)[0-9]{14}") prostir_pattern: Pattern = re...
TestUkUa
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py
{ "start": 19490, "end": 19562 }
class ____(Sam2VideoMaskEmbedding): pass
Sam3TrackerVideoMaskEmbedding
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 22665, "end": 23667 }
class ____(object): """* jina gRPC service to trigger a restore at the Executor Runtime. """ def restore(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implem...
JinaExecutorRestoreServicer
python
wandb__wandb
tests/unit_tests/test_asyncio_compat.py
{ "start": 516, "end": 1983 }
class ____: def __init__(self) -> None: self._before_exit = asyncio.Event() self._after_exit = asyncio.Event() def start( self, subtasks: list[Coroutine[Any, Any, Any]], main_task: Coroutine[Any, Any, Any] | None = None, ) -> None: """Start the tester. ...
_TaskGroupTester
python
django__django
tests/prefetch_related/tests.py
{ "start": 68864, "end": 69763 }
class ____(TestCase): @classmethod def setUpTestData(cls): book1 = Book.objects.create(title="Poems") book2 = Book.objects.create(title="Jane Eyre") book3 = Book.objects.create(title="Wuthering Heights") book4 = Book.objects.create(title="Sense and Sensibility") author1 ...
Ticket21410Tests
python
django__django
tests/migrate_signals/tests.py
{ "start": 479, "end": 751 }
class ____: def __init__(self, signal): self.call_counter = 0 self.call_args = None signal.connect(self, sender=APP_CONFIG) def __call__(self, signal, sender, **kwargs): self.call_counter += 1 self.call_args = kwargs
Receiver
python
coleifer__peewee
tests/models.py
{ "start": 158405, "end": 159145 }
class ____(ModelTestCase): requires = [SequenceModel] def test_create_table(self): query = SequenceModel._schema._create_table() self.assertSQL(query, ( 'CREATE TABLE IF NOT EXISTS "sequence_model" (' '"id" SERIAL NOT NULL PRIMARY KEY, ' '"seq_id" INTEGER NOT...
TestSequence
python
Pylons__pyramid
tests/test_view.py
{ "start": 40468, "end": 40579 }
class ____: scope = 'notaclass' module = sys.modules['tests'] codeinfo = 'codeinfo'
DummyVenusianInfo
python
getsentry__sentry
src/sentry/sentry_metrics/querying/units.py
{ "start": 3163, "end": 3592 }
class ____(UnitMetadata): """ Represents the unit metadata of a QueryExpression with a unit that need to be computed in the future. A future unit tells the unit normalization algorithm that it needs to apply the normalization to all downstream units once a unit in a formula has been determined. More de...
WithFutureUnit
python
python-openxml__python-docx
tests/test_shape.py
{ "start": 2283, "end": 4702 }
class ____: """Unit-test suite for `docx.shape.InlineShape` objects.""" @pytest.mark.parametrize( ("uri", "content_cxml", "expected_value"), [ # -- embedded picture -- (nsmap["pic"], "/pic:pic/pic:blipFill/a:blip{r:embed=rId1}", WD_INLINE_SHAPE.PICTURE), # --...
DescribeInlineShape
python
econchick__interrogate
src/interrogate/config.py
{ "start": 540, "end": 9195 }
class ____: """Configuration related to interrogating a given codebase. :param bool color: Highlight verbose output with color. :param str docstring_style: Style of docstrings to follow. Choices: "sphinx" (default), "google". :param fail_under: Fail when coverage % is less than a given amount. ...
InterrogateConfig
python
giampaolo__psutil
psutil/_common.py
{ "start": 15951, "end": 25254 }
class ____: """Watches numbers so that they don't overflow and wrap (reset to zero). """ def __init__(self): self.lock = threading.Lock() self.cache = {} self.reminders = {} self.reminder_keys = {} def _add_dict(self, input_dict, name): assert name not in se...
_WrapNumbers
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 134083, "end": 135289 }
class ____(Response): """ Response of tasks.delete_hyper_params endpoint. :param deleted: Indicates if the task was updated successfully :type deleted: int """ _service = "tasks" _action = "delete_hyper_params" _version = "2.9" _schema = { "definitions": {}, "proper...
DeleteHyperParamsResponse
python
python-pillow__Pillow
src/PIL/ImageCms.py
{ "start": 3726, "end": 3849 }
class ____(IntEnum): PERCEPTUAL = 0 RELATIVE_COLORIMETRIC = 1 SATURATION = 2 ABSOLUTE_COLORIMETRIC = 3
Intent
python
ray-project__ray
python/ray/serve/_private/common.py
{ "start": 27800, "end": 29491 }
class ____: """Sent from the HTTP proxy to replicas on the streaming codepath.""" def __init__( self, asgi_scope: Scope, *, proxy_actor_name: Optional[str] = None, receive_asgi_messages: Optional[ Callable[[RequestMetadata], Awaitable[bytes]] ] = None...
StreamingHTTPRequest
python
mwaskom__seaborn
seaborn/relational.py
{ "start": 7244, "end": 14853 }
class ____(_RelationalPlotter): _legend_attributes = ["color", "linewidth", "marker", "dashes"] def __init__( self, *, data=None, variables={}, estimator=None, n_boot=None, seed=None, errorbar=None, sort=True, orient="x", err_style=None, err_kws=None, legend=None ): ...
_LinePlotter
python
huggingface__transformers
src/transformers/models/gptj/configuration_gptj.py
{ "start": 793, "end": 5502 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`GPTJModel`]. It is used to instantiate a GPT-J model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configurat...
GPTJConfig
python
mlflow__mlflow
mlflow/genai/judges/base.py
{ "start": 579, "end": 1178 }
class ____(ABC): """ Abstract base class for judge alignment optimizers. Alignment optimizers improve judge accuracy by learning from traces that contain human feedback. """ @abstractmethod def align(self, judge: Judge, traces: list[Trace]) -> Judge: """ Align a judge using...
AlignmentOptimizer