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
numba__numba
numba/tests/test_listobject.py
{ "start": 38574, "end": 39513 }
class ____(MemoryLeakMixin, TestCase): """Test list iter. """ def test_list_iter(self): @njit def foo(items): l = listobject.new_list(int32) l.extend(items) # use a simple sum to check this w/o having to return a list r = 0 for j in l:...
TestIter
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 34824, "end": 37057 }
class ____(Response): """ Response of events.add_batch endpoint. :param added: :type added: int :param errors: :type errors: int :param errors_info: :type errors_info: dict """ _service = "events" _action = "add_batch" _version = "2.13" _schema = { "definiti...
AddBatchResponse
python
getsentry__sentry
src/sentry/api/endpoints/organization_stats_v2.py
{ "start": 6635, "end": 6816 }
class ____(TypedDict): start: str end: str intervals: list[str] groups: list[_StatsGroup] @extend_schema(tags=["Organizations"]) @region_silo_endpoint
StatsApiResponse
python
kubernetes-client__python
kubernetes/client/models/authentication_v1_token_request.py
{ "start": 383, "end": 7746 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
AuthenticationV1TokenRequest
python
apache__airflow
providers/microsoft/azure/src/airflow/providers/microsoft/azure/sensors/wasb.py
{ "start": 1319, "end": 4326 }
class ____(BaseSensorOperator): """ Waits for a blob to arrive on Azure Blob Storage. :param container_name: Name of the container. :param blob_name: Name of the blob. :param wasb_conn_id: Reference to the :ref:`wasb connection <howto/connection:wasb>`. :param check_options: Optional keyword ar...
WasbBlobSensor
python
doocs__leetcode
solution/0300-0399/0324.Wiggle Sort II/Solution2.py
{ "start": 0, "end": 552 }
class ____: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ bucket = [0] * 5001 for v in nums: bucket[v] += 1 n = len(nums) j = 5000 for i in range(1, n, 2): while buc...
Solution
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 8327, "end": 9215 }
class ____(BaseStringType): @classmethod def convert_from_xml( # pyright: ignore[reportIncompatibleMethodOverride] cls, str_value: str ) -> RGBColor | str: if str_value == "auto": return ST_HexColorAuto.AUTO return RGBColor.from_string(str_value) @classmethod de...
ST_HexColor
python
google__pytype
pytype/overlays/overlay.py
{ "start": 418, "end": 3663 }
class ____(abstract.Module): """A layer between pytype and a module's pytd definition. An overlay pretends to be a module, but provides members that generate extra typing information that cannot be expressed in a pytd file. For example, collections.namedtuple is a factory method that generates class definition...
Overlay
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 844012, "end": 845008 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "created_at", "email", "invitation_type", "invitee", "inviter", "organization", "role", ) created_at = sgqlc.typ...
OrganizationInvitation
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/extra/_array_helpers.py
{ "start": 1333, "end": 9855 }
class ____(NamedTuple): input_shapes: tuple[Shape, ...] result_shape: Shape @check_function def check_argument(condition, fail_message, *f_args, **f_kwargs): if not condition: raise InvalidArgument(fail_message.format(*f_args, **f_kwargs)) @check_function def order_check(name, floor, min_, max_)...
BroadcastableShapes
python
joerick__pyinstrument
pyinstrument/frame.py
{ "start": 11409, "end": 12625 }
class ____: _frames: list[Frame] _exit_frames: list[Frame] | None def __init__(self, root: Frame): self.root = root self.id = str(uuid.uuid4()) self._frames = [] self._exit_frames = None self.add_frame(root) @property def frames(self) -> Sequence[Frame]: ...
FrameGroup
python
kamyu104__LeetCode-Solutions
Python/minimum-difficulty-of-a-job-schedule.py
{ "start": 39, "end": 845 }
class ____(object): def minDifficulty(self, jobDifficulty, d): """ :type jobDifficulty: List[int] :type d: int :rtype: int """ if len(jobDifficulty) < d: return -1 dp = [[float("inf")]*len(jobDifficulty) for _ in xrange(d)] dp[0][0...
Solution
python
langchain-ai__langchain
libs/standard-tests/langchain_tests/conftest.py
{ "start": 329, "end": 1673 }
class ____: """Custom serializer for VCR cassettes using YAML and gzip. We're using a custom serializer to avoid the default yaml serializer used by VCR, which is not designed to be safe for untrusted input. This step is an extra precaution necessary because the cassette files are in compressed YA...
CustomSerializer
python
langchain-ai__langchain
libs/core/langchain_core/outputs/chat_result.py
{ "start": 127, "end": 1324 }
class ____(BaseModel): """Use to represent the result of a chat model call with a single prompt. This container is used internally by some implementations of chat model, it will eventually be mapped to a more general `LLMResult` object, and then projected into an `AIMessage` object. LangChain user...
ChatResult
python
conda__conda
conda/gateways/repodata/__init__.py
{ "start": 11234, "end": 15517 }
class ____(UserDict): """Load/save info file that accompanies cached `repodata.json`.""" # Accept old keys for new serialization _aliased = { "_mod": LAST_MODIFIED_KEY, "_etag": ETAG_KEY, "_cache_control": CACHE_CONTROL_KEY, "_url": URL_KEY, } # Enforce string type ...
RepodataState
python
pytorch__pytorch
test/fx/test_fx_param_shape_control_flow.py
{ "start": 1567, "end": 1809 }
class ____(MyModuleBase): def __init__(self, in_channels): super().__init__() self.param = torch.nn.Parameter(torch.randn(in_channels, 3)) def no_relu(self): return self.param.numel() < 10 * 3
MyModuleParamNumEl
python
doocs__leetcode
solution/0000-0099/0036.Valid Sudoku/Solution.py
{ "start": 0, "end": 656 }
class ____: def isValidSudoku(self, board: List[List[str]]) -> bool: row = [[False] * 9 for _ in range(9)] col = [[False] * 9 for _ in range(9)] sub = [[False] * 9 for _ in range(9)] for i in range(9): for j in range(9): c = board[i][j] if ...
Solution
python
ray-project__ray
release/llm_tests/benchmark/load_test.py
{ "start": 10910, "end": 13600 }
class ____(BaseProvider): DEFAULT_MODEL_NAME = "ensemble" def get_url(self): assert not self.parsed_options.chat, "Chat is not supported" assert not self.parsed_options.stream, "Stream is not supported" assert self.parsed_options.n == 1, "n > 1 is not supported" return f"/v2/mod...
TritonInferProvider
python
PyCQA__pylint
pylint/checkers/base/basic_error_checker.py
{ "start": 4963, "end": 24225 }
class ____(_BasicChecker): msgs = { "E0100": ( "__init__ method is a generator", "init-is-generator", "Used when the special class method __init__ is turned into a " "generator by a yield in its body.", ), "E0101": ( "Explicit retur...
BasicErrorChecker
python
bokeh__bokeh
src/bokeh/io/notebook.py
{ "start": 4853, "end": 4987 }
class ____(Protocol): def __call__(self, resources: Resources, verbose: bool, hide_banner: bool, load_timeout: int) -> None: ...
Load
python
scipy__scipy
scipy/_lib/tests/test_array_api.py
{ "start": 899, "end": 16566 }
class ____: def test_array_namespace(self): x, y = np.array([0, 1, 2]), np.array([0, 1, 2]) xp = array_namespace(x, y) assert 'array_api_compat.numpy' in xp.__name__ def test_asarray(self, xp): x, y = _asarray([0, 1, 2], xp=xp), _asarray(np.arange(3), xp=xp) ref = xp.as...
TestArrayAPI
python
getsentry__sentry
src/sentry/sentry_metrics/client/kafka.py
{ "start": 1776, "end": 3626 }
class ____(GenericMetricsBackend): def __init__(self) -> None: logical_topic = Topic.INGEST_PERFORMANCE_METRICS topic_defn = get_topic_definition(logical_topic) self.kafka_topic = ArroyoTopic(topic_defn["real_topic_name"]) self.producer: Producer = get_arroyo_producer( n...
KafkaMetricsBackend
python
pydantic__pydantic
tests/test_json_schema.py
{ "start": 204022, "end": 204072 }
class ____(TypedDict): name: str
TypedDictParent
python
pytorch__pytorch
test/jit/test_dataclasses.py
{ "start": 390, "end": 584 }
class ____: x: float y: float norm: Optional[torch.Tensor] = None def __post_init__(self): self.norm = (torch.tensor(self.x) ** 2 + torch.tensor(self.y) ** 2) ** 0.5
Point
python
pyinstaller__pyinstaller
bootloader/waflib/Build.py
{ "start": 27400, "end": 30013 }
class ____(BuildContext): '''executes tasks in a step-by-step fashion, for debugging''' cmd = 'step' def __init__(self, **kw): super(StepContext, self).__init__(**kw) self.files = Options.options.files def compile(self): if not self.files: Logs.warn('Add a pattern f...
StepContext
python
PyCQA__pylint
tests/functional/a/arguments_renamed.py
{ "start": 715, "end": 1023 }
class ____(Fruit): def brew(self, fruit_name: bool): # No warning here print(f"Brewing a banana named {fruit_name}") def eat_with_condiment(self, fruit_name: str, condiment: Condiment, error: str): # [arguments-differ] print(f"Eating a fruit named {fruit_name} with {condiment}")
Banana
python
mlflow__mlflow
mlflow/sklearn/utils.py
{ "start": 1101, "end": 1414 }
class ____(NamedTuple): name: str function: Callable[..., Any] arguments: dict[str, Any] title: str # _SklearnMetric represents a metric (e.g, precision_score) that will be computed and # logged during the autologging routine for a particular model type (eg, classifier, regressor).
_SklearnArtifact
python
getsentry__sentry
tests/sentry/api/helpers/test_error_upsampling.py
{ "start": 573, "end": 3999 }
class ____(TestCase): def setUp(self) -> None: self.organization = Organization.objects.create(name="test-org") self.projects = [ self.create_project(organization=self.organization, name="Project 1"), self.create_project(organization=self.organization, name="Project 2"), ...
ErrorUpsamplingTest
python
google__pytype
pytype/constant_folding_test.py
{ "start": 8081, "end": 13086 }
class ____(TypeBuilderTestBase): """Test preservation of concrete values.""" def _process(self, src): src = fmt(src) _, defs = self.ctx.vm.run_program(src, "", maximum_depth=4) return defs def test_simple_list(self): defs = self._process(""" a = [1, '2', 3] b = a[1] """) a = ...
PyvalTest
python
huggingface__transformers
src/transformers/models/depth_pro/modeling_depth_pro.py
{ "start": 35094, "end": 36051 }
class ____(nn.Module): def __init__(self, config: DepthProConfig): super().__init__() self.config = config self.fusion_hidden_size = config.fusion_hidden_size self.fov_encoder = DepthProFovEncoder(config) self.conv = nn.Conv2d( self.fusion_hidden_size, self.fusio...
DepthProFovModel
python
rapidsai__cudf
python/cudf/cudf/options.py
{ "start": 367, "end": 9483 }
class ____: default: Any value: Any description: str validator: Callable _OPTIONS: dict[str, Option] = {} def _env_get_int(name, default): try: return int(os.getenv(name, default)) except (ValueError, TypeError): return default def _env_get_bool(name, default): env = os...
Option
python
walkccc__LeetCode
solutions/2101. Detonate the Maximum Bombs/2101.py
{ "start": 0, "end": 619 }
class ____: def maximumDetonation(self, bombs: list[list[int]]) -> int: n = len(bombs) ans = 0 graph = [[] for _ in range(n)] for i, (xi, yi, ri) in enumerate(bombs): for j, (xj, yj, rj) in enumerate(bombs): if i == j: continue if ri**2 >= (xi - xj)**2 + (yi - yj)**2: ...
Solution
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_kernel.py
{ "start": 15144, "end": 15502 }
class ____(enum.IntEnum): HEAD_DIM_MINOR = enum.auto() # [..., seq_len, head_dim] SEQ_MINOR = enum.auto() # [..., head_dim, seq_len] def from_head_minor(vals: tuple[Any, ...], layout: QKVLayout): if layout == QKVLayout.HEAD_DIM_MINOR: return vals return (*vals[:-2], vals[-1], vals[-2]) @dataclasses.da...
QKVLayout
python
django__django
tests/forms_tests/views.py
{ "start": 360, "end": 698 }
class ____(UpdateView): model = Article success_url = "/" form_class = ArticleForm def form_view(request): class Form(forms.Form): number = forms.FloatField() template = Template("<html>{{ form }}</html>") context = Context({"form": Form()}) return HttpResponse(template.render(con...
ArticleFormView
python
kamyu104__LeetCode-Solutions
Python/k-diff-pairs-in-an-array.py
{ "start": 29, "end": 458 }
class ____(object): def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k < 0: return 0 result, lookup = set(), set() for num in nums: if num-k in lookup: result.add(num-k) if ...
Solution
python
django__django
tests/csrf_tests/tests.py
{ "start": 41714, "end": 52862 }
class ____(CsrfViewMiddlewareTestMixin, SimpleTestCase): def _set_csrf_cookie(self, req, cookie): req.COOKIES[settings.CSRF_COOKIE_NAME] = cookie def _read_csrf_cookie(self, req, resp): """ Return the CSRF cookie as a string, or False if no cookie is present. """ if sett...
CsrfViewMiddlewareTests
python
PrefectHQ__prefect
src/integrations/prefect-redis/prefect_redis/ordering.py
{ "start": 1078, "end": 1371 }
class ____(Exception): """Indicates that an event is currently being processed and should not be processed until it is finished. This may happen due to Redis Streams redelivering a message.""" def __init__(self, event: ReceivedEvent): self.event = event
EventBeingProcessed
python
getsentry__sentry
src/sentry/issues/endpoints/bases/group_search_view.py
{ "start": 316, "end": 1430 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read", "org:write", "org:admin"], "POST": ["org:read", "org:write", "org:admin"], "PUT": ["org:read", "org:write", "org:admin"], "DELETE": ["org:read", "org:write", "org:admin"], } def has_object_permission(self,...
GroupSearchViewPermission
python
PrefectHQ__prefect
src/integrations/prefect-azure/prefect_azure/blob_storage.py
{ "start": 6781, "end": 28055 }
class ____( ObjectStorageBlock, WritableFileSystem, WritableDeploymentStorage ): """ Represents a container in Azure Blob Storage. This class provides methods for downloading and uploading files and folders to and from the Azure Blob Storage container. Attributes: container_name: The n...
AzureBlobStorageContainer
python
Pylons__pyramid
tests/test_config/test_assets.py
{ "start": 33976, "end": 34658 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.config.assets import DirectoryOverride return DirectoryOverride def _makeOne(self, path, source): klass = self._getTargetClass() return klass(path, source) def test_it_match(self): source = Dumm...
TestDirectoryOverride
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py
{ "start": 355, "end": 1135 }
class ____: hidden_mutable_default: list[int] = default_function() class_variable: typing.ClassVar[list[int]] = default_function() another_class_var: ClassVar[list[int]] = default_function() fine_path: Path = Path() fine_date: datetime.date = datetime.date(2042, 1, 1) fine_timedelta: datetime.t...
A
python
readthedocs__readthedocs.org
readthedocs/core/forms.py
{ "start": 2376, "end": 4983 }
class ____(forms.Form): """ Form class that allows raising form errors before form submission. The base ``Form`` does not support validation errors while the form is unbound (does not have ``data`` defined). There are cases in our UI where we want to show errors and/or disabled the form before the ...
PrevalidatedForm
python
pytorch__pytorch
torch/distributed/algorithms/_optimizer_overlap/optimizer_overlap.py
{ "start": 1220, "end": 2130 }
class ____(ABC): def __init__(self, optim_cls: type) -> None: """ Initialize the OverlappedOptimizer. Overlappedoptimizer is a base class that child classes can implement to specify how different optimizers will register themselves with DDP. """ self.optim_cls = opti...
OverlappedOptimizer
python
wandb__wandb
wandb/vendor/pygments/lexers/matlab.py
{ "start": 586, "end": 5816 }
class ____(RegexLexer): """ For Matlab source code. .. versionadded:: 0.10 """ name = 'Matlab' aliases = ['matlab'] filenames = ['*.m'] mimetypes = ['text/matlab'] # # These lists are generated automatically. # Run the following in bash shell: # # for f in elfun spe...
MatlabLexer
python
doocs__leetcode
solution/3300-3399/3365.Rearrange K Substrings to Form Target String/Solution.py
{ "start": 0, "end": 299 }
class ____: def isPossibleToRearrange(self, s: str, t: str, k: int) -> bool: cnt = Counter() n = len(s) m = n // k for i in range(0, n, m): cnt[s[i : i + m]] += 1 cnt[t[i : i + m]] -= 1 return all(v == 0 for v in cnt.values())
Solution
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/len_test.py
{ "start": 982, "end": 2117 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.eager_only_combinations()) def testKnown(self): num_elements = 10 ds = dataset_ops.Dataset.range(num_elements) self.assertLen(ds, 10) @combinations.generate(test_base.eager_only_combinations()) def test...
LenTest
python
walkccc__LeetCode
solutions/2031. Count Subarrays With More Ones Than Zeros/2031.py
{ "start": 414, "end": 755 }
class ____: def subarraysWithMoreZerosThanOnes(self, nums: list[int]) -> int: MOD = 1_000_000_007 ans = 0 prefix = 0 tree = FenwichTree(len(nums)) tree.add(0, 1) for num in nums: prefix += -1 if num == 0 else 1 ans += tree.get(prefix - 1) ans %= MOD tree.add(prefix, 1)...
Solution
python
joke2k__faker
faker/providers/internet/ko_KR/__init__.py
{ "start": 46, "end": 344 }
class ____(InternetProvider): free_email_domains = ( "gmail.com", "daum.net", "hotmail.com", "hanmail.net", "naver.com", "nate.com", "live.com", "dreamwiz.com", ) tlds = ("com", "com", "com", "kr", "kr", "net", "org")
Provider
python
dagster-io__dagster
python_modules/libraries/dagster-tableau/dagster_tableau/components/translation.py
{ "start": 1068, "end": 3929 }
class ____(AssetSpecUpdateKwargs, Resolvable): for_sheet: Optional[ResolvedTargetedTableauTranslationFn] = None for_dashboard: Optional[ResolvedTargetedTableauTranslationFn] = None for_data_source: Optional[ResolvedTargetedTableauTranslationFn] = None def resolve_multilayer_translation(context: Resolution...
TableauAssetArgs
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 4406, "end": 9063 }
class ____(test_util.TensorFlowTestCase): def _SparseTensorValue_3x50(self, indices_dtype, values_dtype): # NOTE: This input is intentionally not sorted to validate the # already_sorted flag below. ind = np.array([[0, 0], [1, 0], [1, 2], [2, 0], [2, 1], [1, 1]]) # NB: these are not sorted indices...
SparseMergeTest
python
agronholm__apscheduler
src/apscheduler/triggers/date.py
{ "start": 273, "end": 1246 }
class ____(Trigger): """ Triggers once on the given date/time. :param run_time: the date/time to run the job at """ run_time: datetime = attrs.field( converter=as_aware_datetime, validator=instance_of(datetime) ) _completed: bool = attrs.field(init=False, eq=False, default=False) ...
DateTrigger
python
getsentry__sentry
src/sentry/dashboards/endpoints/organization_dashboards.py
{ "start": 2123, "end": 2249 }
class ____(IntEnum): FRONTEND_SESSION_HEALTH = 1 BACKEND_QUERIES = 2 BACKEND_QUERIES_SUMMARY = 3
PrebuiltDashboardId
python
ray-project__ray
python/ray/tune/search/variant_generator.py
{ "start": 16739, "end": 17305 }
class ____(dict): def __init__(self, *args, **kwds): super(_UnresolvedAccessGuard, self).__init__(*args, **kwds) self.__dict__ = self def __getattribute__(self, item): value = dict.__getattribute__(self, item) if not _is_resolved(value): raise RecursiveDependencyErro...
_UnresolvedAccessGuard
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 138940, "end": 139298 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) widgets: Optional[SqlDashboardWidgetOutput] = Field( None, description=( "Widgets executed in the run. Only SQL query based widgets are list...
SqlDashboardOutput
python
pytorch__pytorch
torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py
{ "start": 468, "end": 28044 }
class ____(LearnedHeuristicDecision): def __init__(self) -> None: self.choices: list[Choice] = [] self.fill_choices() def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: return ( metadata.name == self.get_name() and metadata.shared_m...
MMRankingA100
python
pypa__setuptools
setuptools/_vendor/more_itertools/recipes.py
{ "start": 7740, "end": 28591 }
class ____(ValueError): def __init__(self, details=None): msg = 'Iterables have different lengths' if details is not None: msg += (': index 0 has length {}; index {} has length {}').format( *details ) super().__init__(msg) def _zip_equal_generator(i...
UnequalIterablesError
python
ray-project__ray
python/ray/data/_internal/metadata_exporter.py
{ "start": 1527, "end": 2997 }
class ____: """Represents a data processing operator in the DAG. Attributes: name: The name of the operator. id: The unique identifier of the operator within the DAG structure, typically incorporating a position or index (e.g., "ReadParquet_0"). This is used for referenc...
Operator
python
google__jax
jax/experimental/array_serialization/pytree_serialization_utils.py
{ "start": 1652, "end": 2798 }
class ____(Future[Any]): """A wrapper around a Future that makes it look like an async function.""" def __init__(self, future: Future[Any]): self._future, self.pytree = future, None def done(self): return self._future.done() def result(self, *args, **kw): return self._future.result(*args, **kw) ...
PyTreeFuture
python
crytic__slither
slither/detectors/reentrancy/reentrancy_eth.py
{ "start": 562, "end": 8599 }
class ____(Reentrancy): ARGUMENT = "reentrancy-eth" HELP = "Reentrancy vulnerabilities (theft of ethers)" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.MEDIUM WIKI = ( "https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities" )...
ReentrancyEth
python
readthedocs__readthedocs.org
readthedocs/projects/views/public.py
{ "start": 13672, "end": 15678 }
class ____(SettingsOverrideObject): _default_class = ProjectDownloadMediaBase def project_versions(request, project_slug): """ Project version list view. Shows the available versions and lets the user choose which ones to build. """ max_inactive_versions = 100 project = get_object_or_404...
ProjectDownloadMedia
python
Lightning-AI__lightning
examples/fabric/build_your_own_trainer/run.py
{ "start": 143, "end": 2790 }
class ____(L.LightningModule): def __init__(self) -> None: super().__init__() self.model = torch.nn.Sequential( torch.nn.Conv2d( in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2, ...
MNISTModule
python
ansible__ansible
lib/ansible/plugins/doc_fragments/url.py
{ "start": 212, "end": 3341 }
class ____(object): # Standard files documentation fragment DOCUMENTATION = r""" options: url: description: - HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path type: str force: description: - If V(yes) do not get a cached copy. type: bo...
ModuleDocFragment
python
pola-rs__polars
py-polars/src/polars/interchange/dataframe.py
{ "start": 448, "end": 7661 }
class ____(InterchangeDataFrame): """ A dataframe object backed by a Polars DataFrame. Parameters ---------- df The Polars DataFrame backing the dataframe object. allow_copy Allow data to be copied during operations on this column. If set to `False`, a RuntimeError is ra...
PolarsDataFrame
python
getsentry__sentry
src/sentry/integrations/slack/message_builder/notifications/daily_summary.py
{ "start": 908, "end": 8765 }
class ____(SlackNotificationsMessageBuilder): def __init__( self, notification: BaseNotification, context: Mapping[str, Any], recipient: Actor, ) -> None: super().__init__(notification, context, recipient) self.notification = notification self.context = co...
SlackDailySummaryMessageBuilder
python
viewflow__viewflow
tests/json/test_json__basics.py
{ "start": 2747, "end": 2866 }
class ____(Person): birthdate = jsonstore.DateField() business_phone = jsonstore.CharField(max_length=250)
Client
python
scipy__scipy
scipy/io/matlab/_mio5_params.py
{ "start": 7448, "end": 7781 }
class ____(np.ndarray): """Subclass for a MATLAB function. This is a simple subclass of :class:`numpy.ndarray` meant to be used by :func:`scipy.io.loadmat` and should not be directly instantiated. """ def __new__(cls, input_array): obj = np.asarray(input_array).view(cls) return obj...
MatlabFunction
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/rnn_test.py
{ "start": 2722, "end": 3287 }
class ____(rnn_cell_impl.RNNCell): """RNN Cell generating (output, new_state) = (input + 1, state + 1).""" @property def output_size(self): return tensor_shape.TensorShape(1), tensor_shape.TensorShape((2)) @property def state_size(self): return tensor_shape.TensorShape([]) def zero_state(self, b...
UnbalancedOutputRNNCell
python
scipy__scipy
scipy/linalg/tests/test_special_matrices.py
{ "start": 22181, "end": 24843 }
class ____: """ Test convolution_matrix vs. numpy.convolve for various parameters. """ def create_vector(self, n, cpx): """Make a complex or real test vector of length n.""" x = np.linspace(-2.5, 2.2, n) if cpx: x = x + 1j*np.linspace(-1.5, 3.1, n) return x ...
TestConvolutionMatrix
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_data.py
{ "start": 8498, "end": 14132 }
class ____: """A single tensor dumped by TensorFlow Debugger (tfdbg). Contains metadata about the dumped tensor, including `timestamp`, `node_name`, `output_slot`, `debug_op`, and path to the dump file (`file_path`). This type does not hold the generally space-expensive tensor value (numpy array). Instead...
DebugTensorDatum
python
getsentry__sentry
tests/sentry/api/test_base.py
{ "start": 1949, "end": 2656 }
class ____(Endpoint): permission_classes = () # `as_view` requires that any init args passed to it match attributes already on the # class, so even though they're really meant to be instance attributes, we have to # add them here as class attributes first error: Exception = NotImplementedError() ...
DummyErroringEndpoint
python
astropy__astropy
astropy/table/__init__.py
{ "start": 872, "end": 3410 }
class ____(_config.ConfigNamespace): """ Configuration parameters for `astropy.table`. """ auto_colname = _config.ConfigItem( "col{0}", "The template that determines the name of a column if it cannot be " "determined. Uses new-style (format method) string formatting.", a...
Conf
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/sample_from_datasets_test.py
{ "start": 1771, "end": 12599 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def _normalize(self, vec): return vec / vec.sum() def _chi2(self, expected, actual): actual = np.asarray(actual) expected = np.asarray(expected) diff = actual - expected chi2 = np.sum(diff * diff / expected, axis=0) return chi2...
SampleFromDatasetsTest
python
google__pytype
pytype/directors/parser.py
{ "start": 847, "end": 948 }
class ____(LineRange): """Tag to identify function calls.""" @dataclasses.dataclass(frozen=True)
Call
python
huggingface__transformers
src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py
{ "start": 1726, "end": 17570 }
class ____(PreTrainedModel): config: VisionTextDualEncoderConfig base_model_prefix = "vision_text_dual_encoder" input_modalities = ("image", "text") _supports_flash_attn = True _supports_sdpa = True def __init__( self, config: Optional[VisionTextDualEncoderConfig] = None, ...
VisionTextDualEncoderModel
python
doocs__leetcode
solution/0500-0599/0501.Find Mode in Binary Search Tree/Solution.py
{ "start": 192, "end": 756 }
class ____: def findMode(self, root: TreeNode) -> List[int]: def dfs(root): if root is None: return nonlocal mx, prev, ans, cnt dfs(root.left) cnt = cnt + 1 if prev == root.val else 1 if cnt > mx: ans = [root.val] ...
Solution
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 296173, "end": 297204 }
class ____(FallbackKernel): """ Custom kernel for memory checking that generates direct function calls TODO - the custom op was erroring with str inputs. should be able to custom op directly. """ def codegen(self, wrapper: PythonWrapperCodegen) -> None: """Override codegen to write direct ...
MemoryCheckKernel
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 11561, "end": 11704 }
class ____(desc_sig_element, _sig_element=True): """Node for a string literal in a signature.""" classes = ['s']
desc_sig_literal_string
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 393440, "end": 394430 }
class ____(sgqlc.types.Interface): """Represents a Git object.""" __schema__ = github_schema __field_names__ = ("abbreviated_oid", "commit_resource_path", "commit_url", "id", "oid", "repository") abbreviated_oid = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="abbreviatedOid") """An ...
GitObject
python
pytorch__pytorch
torch/distributions/constraints.py
{ "start": 18539, "end": 19758 }
class ____(Constraint): """ Constraint functor that applies a sequence of constraints `cseq` at the submatrices at dimension `dim`, each of size `lengths[dim]`, in a way compatible with :func:`torch.cat`. """ def __init__(self, cseq, dim=0, lengths=None): assert all(isinstance(c, Constr...
_Cat
python
pydata__xarray
xarray/tests/test_indexing.py
{ "start": 35968, "end": 36058 }
class ____: def __array_namespace__(self, version=None): pass
ArrayWithNamespace
python
ray-project__ray
python/ray/train/tests/test_iter_torch_batches_gpu.py
{ "start": 1165, "end": 1559 }
class ____(ArrowBatchCollateFn): """Collate function that returns only the id column as a tensor.""" def __call__(self, batch: pa.Table) -> torch.Tensor: """Return only the id column as a tensor.""" assert isinstance(batch, pa.Table) tensor_dict = arrow_batch_to_tensors(batch, combine_c...
SingleTensorArrowBatchCollateFn
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/projection_queries/snippets.py
{ "start": 1652, "end": 1871 }
class ____(ndb.Model): A = ndb.IntegerProperty(repeated=True) B = ndb.StringProperty(repeated=True) def declare_multiple_valued_property(): entity = Foo(A=[1, 1, 2, 3], B=["x", "y", "x"]) return entity
Foo
python
great-expectations__great_expectations
tests/scripts/test_public_api_report.py
{ "start": 12835, "end": 20959 }
class ____: def example_method(): pass @staticmethod def example_public_staticmethod(): pass @classmethod def example_public_classmethod(cls): pass @some_other_decorator @another_decorator def example_multiple_decorator_public_method(self): pass """ ...
ExampleClass
python
getsentry__sentry
tests/sentry/flags/endpoints/test_logs.py
{ "start": 13192, "end": 14964 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-flag-log" def setUp(self) -> None: super().setUp() self.flag = FlagAuditLogModel( action=0, created_at=datetime.now(timezone.utc), created_by="a@b.com", created_by_type=0, ...
OrganizationFlagLogDetailsEndpointTestCase
python
dask__distributed
distributed/utils_test.py
{ "start": 55353, "end": 55815 }
class ____(WorkerPlugin): """WorkPlugin to populate TaskState.metadata""" def setup(self, worker): self.tasks = worker.state.tasks def transition(self, key, start, finish, **kwargs): ts = self.tasks[key] if start == "ready" and finish == "executing": ts.metadata["start...
TaskStateMetadataPlugin
python
pytorch__pytorch
test/distributed/_composable/test_replicate_training.py
{ "start": 9658, "end": 24823 }
class ____(FSDPTest): @property def world_size(self) -> int: return min(8, torch.get_device_module(device_type).device_count()) @skip_if_lt_x_gpu(2) def test_train_parity_single_group(self): """ Tests train parity with DDP for a single FSDP group when sharding parameters...
TestReplicate1DTrainingCore
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/proxied_state.py
{ "start": 122, "end": 991 }
class ____(NamedTuple): """A class to store the proxied state of a task. Args: task_id (str): The id of the task. proxied (bool): A boolean indicating whether the task is proxied. """ task_id: str proxied: bool @staticmethod def from_dict(task_dict: dict[str, Any]) -> "Tas...
TaskProxiedState
python
Textualize__textual
src/textual/_parser.py
{ "start": 323, "end": 387 }
class ____(ParseError): """Read has timed out."""
ParseTimeout
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 14149, "end": 14798 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 1]"): l_x_ = L_x_ wrap_body_0 = self.wrap_body_0 wrap = torch.ops.higher_order.wrap(wrap_body_0, l_x_); wrap_body_0 = l_x_ = None getitem: "f32[3]" = wrap[0]; wrap = None return (getitem,) class wrap_body_0(...
GraphModule
python
mwaskom__seaborn
tests/test_distributions.py
{ "start": 1776, "end": 4278 }
class ____: rs = np.random.RandomState(0) x = rs.randn(100) def test_hist_bins(self): fd_edges = np.histogram_bin_edges(self.x, "fd") with pytest.warns(UserWarning): ax = distplot(self.x) for edge, bar in zip(fd_edges, ax.patches): assert pytest.approx(edge...
TestDistPlot
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/v1_compat_tests/stack_op_test.py
{ "start": 1065, "end": 3249 }
class ____(test.TestCase): @test_util.run_deprecated_v1 # Tests symbolic tensor semantics def testVariable(self): with self.session(): v = variables.Variable(17) result = ops.convert_to_tensor([[0, 0, 0], [0, v, 0], [0, 0, 0]]) self.evaluate(v.initializer) self.assertAllEqual([[0, 0, ...
AutomaticStackingTest
python
django-haystack__django-haystack
test_haystack/elasticsearch5_tests/test_backend.py
{ "start": 2950, "end": 3356 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) name = indexes.CharField(model_attr="author") pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return AnotherMockModel def prepare_text(self, obj): return "You mi...
Elasticsearch5AnotherMockModelSearchIndex
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/collaborators/base.py
{ "start": 1261, "end": 5946 }
class ____(BaseReader): """ GitHub repository collaborators reader. Retrieves the list of collaborators of a GitHub repository and returns a list of documents. Examples: >>> reader = GitHubRepositoryCollaboratorsReader("owner", "repo") >>> colabs = reader.load_data() >>> print(...
GitHubRepositoryCollaboratorsReader
python
google__pytype
pytype/rewrite/abstract/base.py
{ "start": 4029, "end": 4740 }
class ____(BaseValue): """Union of values.""" def __init__(self, ctx: ContextType, options: Sequence[BaseValue]): super().__init__(ctx) assert len(options) > 1 flattened_options = [] for o in options: if isinstance(o, Union): flattened_options.extend(o.options) else: fla...
Union
python
Netflix__metaflow
metaflow/plugins/catch_decorator.py
{ "start": 196, "end": 629 }
class ____(MetaflowException): headline = "Task execution failed but @catch handled it" def __init__(self, retry_count): msg = ( "Task execution kept failing over %d attempts. " "Your code did not raise an exception. Something " "in the execution environment caused t...
FailureHandledByCatch
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table04.py
{ "start": 315, "end": 1144 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
pytorch__pytorch
torch/_inductor/codegen/cpp.py
{ "start": 224527, "end": 225765 }
class ____: def __init__(self, code): self.code = code self.in_parallel = False self.num_threads = None self.stack = contextlib.ExitStack() def parallel(self, threads): if self.in_parallel and threads != self.num_threads: # wrong number of threads ...
WorkSharing
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-athena/llama_index/readers/athena/base.py
{ "start": 179, "end": 2692 }
class ____(BaseReader): """ Athena reader. Follow AWS best practices for security. AWS discourages hardcoding credentials in code. We recommend that you use IAM roles instead of IAM user credentials. If you must use credentials, do not embed them in your code. Instead, store them in environ...
AthenaReader
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/isinstance3.py
{ "start": 477, "end": 926 }
class ____(Generic[_T]): pass a = A() if isinstance(a, A): pass # This should generate an error because generic types with # subscripts are not allowed. if isinstance(a, A[str]): pass # This should generate an error in Python 3.9 and older because # unions are not allowed, but this error isn't currentl...
A
python
sympy__sympy
sympy/series/limits.py
{ "start": 4365, "end": 13227 }
class ____(Expr): """Represents an unevaluated limit. Examples ======== >>> from sympy import Limit, sin >>> from sympy.abc import x >>> Limit(sin(x)/x, x, 0) Limit(sin(x)/x, x, 0, dir='+') >>> Limit(1/x, x, 0, dir="-") Limit(1/x, x, 0, dir='-') """ def __new__(cls, e, z,...
Limit