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
Textualize__textual
src/textual/dom.py
{ "start": 3503, "end": 4187 }
class ____: """A descriptor to manage the `classes` property.""" def __get__( self, obj: DOMNode, objtype: type[DOMNode] | None = None ) -> frozenset[str]: """A frozenset of the current classes on the widget.""" return frozenset(obj._classes) def __set__(self, obj: DOMNode, cla...
_ClassesDescriptor
python
pytorch__pytorch
torch/ao/quantization/quantizer/embedding_quantizer.py
{ "start": 1178, "end": 3397 }
class ____(Quantizer): @classmethod def get_supported_quantization_configs(cls) -> list[QuantizationConfig]: op_configs: set[QuantizationConfig] = { spec for spec, _ in cls.get_supported_operators() } return list(op_configs) @classmethod def get_supported_operator_fo...
EmbeddingQuantizer
python
numba__numba
numba/core/dispatcher.py
{ "start": 6015, "end": 6462 }
class ____(object): """ A simple counter that increment in __enter__ and decrement in __exit__. """ def __init__(self): self.counter = 0 def __enter__(self): assert self.counter >= 0 self.counter += 1 def __exit__(self, *args, **kwargs): self.counter -= 1 ...
CompilingCounter
python
django__django
tests/forms_tests/tests/test_forms.py
{ "start": 233051, "end": 237908 }
class ____(SimpleTestCase): def test_renderer_custom_bound_field(self): t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div><label for="id_first_name">First name</label> <input type="text" name="first_name" required ...
CustomBoundFieldTest
python
django-debug-toolbar__django-debug-toolbar
tests/models.py
{ "start": 281, "end": 589 }
class ____(models.Model): field = JSONField() def __str__(self): return "" if settings.USE_GIS: from django.contrib.gis.db import models as gismodels class Location(gismodels.Model): point = gismodels.PointField() def __str__(self): return ""
PostgresJSON
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 15303, "end": 15819 }
class ____(ConfigModel): name: str route_type: str model: EndpointModelInfo route_url: str limit: Limit | None = None model_config = ConfigDict(json_schema_extra=_ROUTE_EXTRA_SCHEMA) def to_endpoint(self): from mlflow.deployments.server.config import Endpoint return Endpoi...
_LegacyRoute
python
PrefectHQ__prefect
src/prefect/server/events/filters.py
{ "start": 1002, "end": 1469 }
class ____(PrefectFilterBaseModel): """Filter by `Automation.created`.""" before_: Optional[DateTime] = Field( default=None, description="Only include automations created before this datetime", ) def _get_filter_list( self, db: PrefectDBInterface ) -> Iterable[sa.ColumnElem...
AutomationFilterCreated
python
pydata__xarray
xarray/core/indexes.py
{ "start": 36641, "end": 54523 }
class ____(PandasIndex): """Wrap a pandas.MultiIndex as an xarray compatible index.""" index: pd.MultiIndex dim: Hashable coord_dtype: Any level_coords_dtype: dict[Hashable | None, Any] __slots__ = ("coord_dtype", "dim", "index", "level_coords_dtype") def __init__(self, array: Any, dim: H...
PandasMultiIndex
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0084_crons_dedupe_workflows.py
{ "start": 3835, "end": 5199 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
doocs__leetcode
solution/0900-0999/0908.Smallest Range I/Solution.py
{ "start": 0, "end": 155 }
class ____: def smallestRangeI(self, nums: List[int], k: int) -> int: mx, mi = max(nums), min(nums) return max(0, mx - mi - k * 2)
Solution
python
getsentry__sentry
tests/sentry/integrations/github/test_ticket_action.py
{ "start": 770, "end": 6719 }
class ____(RuleTestCase, BaseAPITestCase): rule_cls = GitHubCreateTicketAction repo = "foo/bar" assignee = "sentry_user" labels = ["bug", "invalid"] issue_num = 1 def setUp(self) -> None: super().setUp() self.integration = self.create_integration( organization=self.o...
GitHubTicketRulesTestCase
python
pypa__virtualenv
src/virtualenv/util/path/_sync.py
{ "start": 1778, "end": 2116 }
class ____: def __init__(self, src, dest) -> None: self.src = src self.dest = dest def __str__(self) -> str: return f"{'directory ' if self.src.is_dir() else ''}{self.src!s} to {self.dest!s}" __all__ = [ "copy", "copytree", "ensure_dir", "safe_delete", "symlink", ...
_Debug
python
run-llama__llama_index
llama-index-packs/llama-index-packs-panel-chatbot/llama_index/packs/panel_chatbot/app.py
{ "start": 2467, "end": 12024 }
class ____(pn.viewable.Viewer): """ The IndexLoader enables the user to interactively create a VectorStoreIndex from a github repository of choice. """ value: VectorStoreIndex = param.ClassSelector(class_=VectorStoreIndex) status = param.String(constant=True, doc="A status message") owner...
IndexLoader
python
PyCQA__pylint
tests/functional/u/unused/unused_import_class_def_keyword.py
{ "start": 476, "end": 558 }
class ____(Child, domain=DOMAIN_2): DOMAIN_2 = DOMAIN_2 # Alternative 2
Parent_2
python
Netflix__metaflow
test/core/tests/basic_config_parameters.py
{ "start": 72, "end": 4548 }
class ____(MetaflowTest): PRIORITY = 1 REQUIRED_FILES = ["basic_config_silly.txt"] SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursiv...
BasicConfigTest
python
getsentry__sentry
src/sentry/spans/consumers/process/factory.py
{ "start": 1327, "end": 9704 }
class ____(ProcessingStrategyFactory[KafkaPayload]): """ 1. Process spans and push them to redis 2. Commit offsets for processed spans 3. Reduce the messages to find the latest timestamp to process 4. Fetch all segments are two minutes or older and expire the keys so they aren't reprocessed ...
ProcessSpansStrategyFactory
python
doocs__leetcode
solution/1500-1599/1557.Minimum Number of Vertices to Reach All Nodes/Solution.py
{ "start": 0, "end": 197 }
class ____: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: cnt = Counter(t for _, t in edges) return [i for i in range(n) if cnt[i] == 0]
Solution
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 15158, "end": 15457 }
class ____(HTTPException): """*414* `Request URI Too Large` Like *413* but for too long URLs. """ code = 414 description = ( "The length of the requested URL exceeds the capacity limit for" " this server. The request cannot be processed." )
RequestURITooLarge
python
apache__airflow
airflow-core/src/airflow/utils/deprecation_tools.py
{ "start": 913, "end": 8226 }
class ____(FutureWarning): """ Warning class for deprecated imports in Airflow. This warning is raised when users import deprecated classes or functions from Airflow modules that have been moved to better locations. """ ... def getattr_with_deprecation( imports: dict[str, str], modul...
DeprecatedImportWarning
python
jazzband__django-simple-history
simple_history/registry_tests/migration_test_app/migrations/0004_history_date_indexing.py
{ "start": 108, "end": 704 }
class ____(migrations.Migration): dependencies = [ ( "migration_test_app", "0003_alter_historicalmodelwithcustomattrforeignkey_options_and_more", ), ] operations = [ migrations.AlterField( model_name="historicalmodelwithcustomattrforeignkey", ...
Migration
python
huggingface__transformers
tests/models/mobilenet_v2/test_modeling_mobilenet_v2.py
{ "start": 10190, "end": 13105 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( MobileNetV2ImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224") if is_vision_available() else None ) @slow def test_inference_image_classification_head(self): model =...
MobileNetV2ModelIntegrationTest
python
ApeWorX__ape
src/ape/logging.py
{ "start": 3676, "end": 11046 }
class ____: _mentioned_verbosity_option = False _extra_loggers: dict[str, logging.Logger] = {} DISABLE_LEVEL: int = 100_000 def __init__( self, _logger: logging.Logger, fmt: str, ): self.error = _logger.error self.warning = _logger.warning self.succes...
ApeLogger
python
getsentry__sentry
src/sentry/services/filestore/s3.py
{ "start": 3882, "end": 9060 }
class ____(File): """ The default file object used by the S3Boto3Storage backend. This file implements file streaming using boto's multipart uploading functionality. The file can be opened in read or write mode. This class extends Django's File class. However, the contained data is only th...
S3Boto3StorageFile
python
spyder-ide__spyder
spyder/plugins/run/tests/test_run.py
{ "start": 9133, "end": 11736 }
class ____(RunExecutor): sig_run_invocation = Signal(tuple) def __init__(self, parent, info, executor_name): self.executor_configuration = [] self.handlers = {} self.actions = {} self.executor_name = executor_name self.handlers['all'] = self.bind_execution_method('all')...
ExampleRunExecutorWrapper
python
pytorch__pytorch
test/export/test_passes.py
{ "start": 12684, "end": 58777 }
class ____(TestCase): def setUp(self): super().setUp() self.MIXED_AUTOCAST_SET_GRAD_TESTS = _with_mixed_autocast_set_grad_tests() self.SEQUENTIAL_SPLIT_INLINE_TESTS = _sequential_split_inline_tests() self.SET_GRAD_ENABLED_TESTS = _set_grad_enabled_tests() self.WITH_AUTOCAST_T...
TestPasses
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 40185, "end": 42096 }
class ____(nn.Module): """ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by subtracting from the mean and dividing by the standard deviation. """ def __init__(self, config: PatchTSTConfig): super().__init__() self.dim = co...
PatchTSTStdScaler
python
PrefectHQ__prefect
src/prefect/client/schemas/actions.py
{ "start": 24111, "end": 24681 }
class ____(ActionBaseModel): """Data used by the Prefect REST API to create a block schema.""" fields: dict[str, Any] = Field( default_factory=dict, description="The block schema's field schema" ) block_type_id: Optional[UUID] = Field(default=None) capabilities: list[str] = Field( d...
BlockSchemaCreate
python
numpy__numpy
benchmarks/benchmarks/bench_core.py
{ "start": 3638, "end": 4442 }
class ____(Benchmark): param_names = ['numaxes', 'size', 'dtype'] params = [ [1, 2, 3], [100, 10000, 1000000], [bool, np.int8, np.int16, np.int32, np.int64, np.float32, np.float64, str, object] ] def setup(self, numaxes, size, dtype): self.x = np.arange(numaxes ...
CountNonzero
python
python__mypy
mypy/nodes.py
{ "start": 55753, "end": 56252 }
class ____(Statement): __slots__ = ("expr", "body", "else_body") __match_args__ = ("expr", "body", "else_body") expr: Expression body: Block else_body: Block | None def __init__(self, expr: Expression, body: Block, else_body: Block | None) -> None: super().__init__() self.expr...
WhileStmt
python
cherrypy__cherrypy
cherrypy/lib/httputil.py
{ "start": 4629, "end": 6148 }
class ____(object): """An element (with parameters) from an HTTP header's element list.""" def __init__(self, value, params=None): """Initialize an HTTP header value representation.""" self.value = value if params is None: params = {} self.params = params def __...
HeaderElement
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 13319, "end": 13870 }
class ____(ASTLiteral): def __eq__(self, other: object) -> bool: return isinstance(other, ASTPointerLiteral) def __hash__(self) -> int: return hash('nullptr') def _stringify(self, transform: StringifyTransform) -> str: return 'nullptr' def get_id(self, version: int) -> str: ...
ASTPointerLiteral
python
TheAlgorithms__Python
data_structures/binary_tree/binary_search_tree_recursive.py
{ "start": 523, "end": 7400 }
class ____: def __init__(self) -> None: self.root: Node | None = None def empty(self) -> None: """ Empties the tree >>> t = BinarySearchTree() >>> assert t.root is None >>> t.put(8) >>> assert t.root is not None """ self.root = None ...
BinarySearchTree
python
huggingface__transformers
src/transformers/models/trocr/modeling_trocr.py
{ "start": 12941, "end": 17829 }
class ____(GradientCheckpointingLayer): def __init__(self, config: TrOCRConfig, layer_idx=None): super().__init__() self.embed_dim = config.hidden_size self.self_attn = TrOCRAttention( config, embed_dim=self.embed_dim, num_heads=config.decoder_attention_h...
TrOCRDecoderLayer
python
huggingface__transformers
tests/models/luke/test_modeling_luke.py
{ "start": 1414, "end": 21504 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, entity_length=3, mention_length=5, use_attention_mask=True, use_token_type_ids=True, use_entity_ids=True, use_entity_attention_mask=True, ...
LukeModelTester
python
fluentpython__example-code
07-closure-deco/strategy_best4.py
{ "start": 1558, "end": 3143 }
class ____: # the Context def __init__(self, customer, cart, promotion=None): self.customer = customer self.cart = list(cart) self.promotion = promotion def total(self): if not hasattr(self, '__total'): self.__total = sum(item.total() for item in self.cart) ...
Order
python
dagster-io__dagster
python_modules/dagster/dagster_tests/general_tests/utils_tests/log_tests/test_single_handler.py
{ "start": 158, "end": 1365 }
class ____(logging.Handler): def __init__(self, records): self.records = records super().__init__() def emit(self, record): self.records.append(record) def test_log_level_filtering(): records = [] critical_records = [] debug_logger_def = construct_single_handler_logger( ...
LogTestHandler
python
nmslib__hnswlib
tests/python/bindings_test.py
{ "start": 64, "end": 2239 }
class ____(unittest.TestCase): def testRandomSelf(self): dim = 16 num_elements = 10000 # Generating sample data data = np.float32(np.random.random((num_elements, dim))) # Declaring index p = hnswlib.Index(space='l2', dim=dim) # possible options are l2, cosine or i...
RandomSelfTestCase
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/when_directives_true/package.py
{ "start": 217, "end": 884 }
class ____(Package): """Package that tests True when specs on directives.""" homepage = "http://www.example.com" url = "http://www.example.com/example-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") patch( "https://example.com/foo.patch", sha256="abcd1234abcd123...
WhenDirectivesTrue
python
PyCQA__pylint
tests/functional/i/invalid/invalid_exceptions/invalid_exceptions_caught.py
{ "start": 2194, "end": 2270 }
class ____(six.with_metaclass(abc.ABCMeta, Exception)): pass
HasErrorInMRO
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/generator1.py
{ "start": 2619, "end": 2894 }
class ____(TypedDict): x: str def generator12() -> Generator[TD1, None, None]: yield {"x": "x"} def generator13() -> Generator[TD1, None, None]: # This should generate an error. yield {"y": "x"} def generator14() -> Iterator[TD1]: yield {"x": "x"}
TD1
python
pytorch__pytorch
torch/utils/data/datapipes/_typing.py
{ "start": 7252, "end": 8382 }
class ____: r"""Save type annotation in `param`.""" def __init__(self, param) -> None: self.param = param def __repr__(self) -> str: return _type_repr(self.param) def __eq__(self, other): if isinstance(other, _DataPipeType): return self.param == other.param ...
_DataPipeType
python
getsentry__sentry
src/sentry/api/endpoints/source_map_debug_blue_thunder_edition.py
{ "start": 2392, "end": 2644 }
class ____(TypedDict): source_file: None | (ScrapingResultSuccess | ScrapingResultNotAttempted | ScrapingResultFailure) source_map: None | (ScrapingResultSuccess | ScrapingResultNotAttempted | ScrapingResultFailure)
SourceMapScrapingProcessResult
python
django-mptt__django-mptt
tests/myapp/models.py
{ "start": 9833, "end": 10106 }
class ____(MPTTModel): name = models.CharField(max_length=50) custom_parent = TreeForeignKey( "self", null=True, blank=True, related_name="children", on_delete=models.CASCADE ) class MPTTMeta: parent_attr = "custom_parent"
CustomParentAttrModel
python
pandas-dev__pandas
pandas/tests/test_algos.py
{ "start": 34349, "end": 46254 }
class ____: def test_invalid(self): msg = ( r"only list-like objects are allowed to be passed to isin\(\), " r"you passed a `int`" ) with pytest.raises(TypeError, match=msg): algos.isin(1, 1) with pytest.raises(TypeError, match=msg): al...
TestIsin
python
lxml__lxml
src/lxml/html/__init__.py
{ "start": 53056, "end": 54291 }
class ____(SetMixin): """ Represents the values of the checked checkboxes in a group of checkboxes with the same name. """ def __init__(self, group): self.group = group def __iter__(self): return iter([ el.get('value') for el in self.group if...
CheckboxValues
python
fluentpython__example-code-2e
05-data-classes/dataclass/club_wrong.py
{ "start": 66, "end": 140 }
class ____: name: str guests: list = [] # end::CLUBMEMBER[]
ClubMember
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 377497, "end": 378623 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateTeamDiscussion""" __schema__ = github_schema __field_names__ = ("id", "title", "body", "body_version", "pinned", "client_mutation_id") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") """The Node ID of the discus...
UpdateTeamDiscussionInput
python
getsentry__sentry
tests/sentry/workflow_engine/migrations/test_0087_relink_crons_to_compatible_issue_workflows.py
{ "start": 318, "end": 20412 }
class ____(TestMigrations): migrate_from = "0086_fix_cron_to_cron_workflow_links" migrate_to = "0087_relink_crons_to_compatible_issue_workflows" app = "workflow_engine" def _create_issue_rule_with_workflow( self, project, condition_data, action_data=None, frequen...
RelinkCronsToCompatibleIssueWorkflowsTest
python
facelessuser__pymdown-extensions
tests/test_extensions/test_magiclink.py
{ "start": 3848, "end": 4940 }
class ____(util.MdCase): """Test cases for social link shortener.""" extension = [ 'pymdownx.magiclink' ] extension_configs = { 'pymdownx.magiclink': { 'social_url_shortener': True } } def test_user(self): """Test user shortening.""" # Test...
TestMagicLinkShortnerSocial
python
tiangolo__fastapi
tests/test_duplicate_models_openapi.py
{ "start": 120, "end": 155 }
class ____(BaseModel): pass
Model
python
django__django
tests/admin_views/tests.py
{ "start": 171209, "end": 172265 }
class ____(TestCase): """ Test behavior of a view protected by the staff_member_required decorator. """ def test_secure_view_shows_login_if_not_logged_in(self): secure_url = reverse("secure_view") response = self.client.get(secure_url) self.assertRedirects( response,...
SecureViewTests
python
walkccc__LeetCode
solutions/2819. Minimum Relative Loss After Buying Chocolates/2819.py
{ "start": 0, "end": 2337 }
class ____: def minimumRelativeLosses( self, prices: list[int], queries: list[list[int]], ) -> list[int]: ans = [] prices.sort() prefix = list(itertools.accumulate(prices, initial=0)) for k, m in queries: countFront = self._getCountFront(k, m, prices) countBack = m -...
Solution
python
ray-project__ray
release/ray_release/job_manager/kuberay_job_manager.py
{ "start": 605, "end": 7838 }
class ____: def __init__(self): self.cluster_startup_timeout = 600 self.job_id = None self._kuberay_service_token = None def run_and_wait( self, job_name: str, image: str, cmd_to_run: str, timeout: int, env_vars: Dict[str, Any], wo...
KubeRayJobManager
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 548031, "end": 548443 }
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("CreatedIssueContribution"...
CreatedIssueContributionEdge
python
pytorch__pytorch
test/dynamo/test_modes.py
{ "start": 3960, "end": 24181 }
class ____(torch._dynamo.test_case.TestCase): @classmethod def setUpClass(cls): cls.default_device_old = torch.get_default_device() super().setUpClass() @classmethod def tearDownClass(cls): torch.set_default_device(cls.default_device_old) super().tearDownClass() def...
TorchFunctionModeTests
python
django__django
django/db/models/aggregates.py
{ "start": 666, "end": 1358 }
class ____(Func): arity = 1 template = " FILTER (WHERE %(expressions)s)" def as_sql(self, compiler, connection, **extra_context): if not connection.features.supports_aggregate_filter_clause: raise NotSupportedError( "Aggregate filter clauses are not supported on this dat...
AggregateFilter
python
realpython__materials
arcade-platformer/arcade_platformer/arcade_platformer.py
{ "start": 7462, "end": 9435 }
class ____(arcade.View): """Shown when a level is completed""" def __init__( self, game_view: arcade.View, victory_sound: arcade.Sound ) -> None: super().__init__() # Store a reference to the underlying view self.game_view = game_view # Play the victory sound ...
VictoryView
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 24467, "end": 25990 }
class ____: def __init__(self, resource_group: Any) -> None: self._name = resource_group.name self._capacity = resource_group.capacity self._num_available_node = resource_group.num_available_node self._num_loaded_replica = resource_group.num_loaded_replica self._num_outgoing_...
ResourceGroupInfo
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 246438, "end": 265482 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): _FORWARD_COMPATIBILITY_HORIZONS = [ (2020, 1, 1), (2020, 7, 14), (2525, 1, 1), # future behavior ] def testBmpChannels(self): for horizon in self._FORWARD_COMPATIBILITY_HORIZONS: with compat.forward_compatibility_hori...
DecodeImageTest
python
jazzband__django-oauth-toolkit
oauth2_provider/exceptions.py
{ "start": 1418, "end": 1560 }
class ____(InvalidRequestFatalError): description = "The ID Token is expired, revoked, malformed, or otherwise invalid."
InvalidIDTokenError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 361135, "end": 362203 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "edges", "filtered_count", "nodes", "page_count", "page_info", "total_count", "updated_at", ) edges = sgql...
IssueTimelineItemsConnection
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 158935, "end": 162646 }
class ____(multi_rv_generic): r"""A matrix-valued U(N) random variable. Return a random unitary matrix. The `dim` keyword specifies the dimension N. Methods ------- rvs(dim=None, size=1, random_state=None) Draw random samples from U(N). Parameters ---------- dim : scalar ...
unitary_group_gen
python
Textualize__textual
src/textual/_parser.py
{ "start": 387, "end": 523 }
class ____(NamedTuple): """Reads a single character.""" timeout: float | None = None """Optional timeout in seconds."""
Read1
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_match_thai.py
{ "start": 451, "end": 2546 }
class ____(RegexBasedColumnMapExpectation): """Expect column values to contain Thai Language. Args: column (str): \ A integer column that consist of Thai language. """ # These values will be used to configure the metric created by your expectation regex_camel_name = "RegexName"...
ExpectColumnValuesToMatchThai
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 22270, "end": 27863 }
class ____(rv_discrete): r"""A negative hypergeometric discrete random variable. Consider a box containing :math:`M` balls:, :math:`n` red and :math:`M-n` blue. We randomly sample balls from the box, one at a time and *without* replacement, until we have picked :math:`r` blue balls. `nhypergeom` is...
nhypergeom_gen
python
pytorch__pytorch
test/functorch/test_control_flow.py
{ "start": 13070, "end": 13162 }
class ____: def __call__(self, *operands): return reduce_func(*operands)
ReduceObj
python
doocs__leetcode
lcof/面试题15. 二进制中1的个数/Solution2.py
{ "start": 0, "end": 159 }
class ____: def hammingWeight(self, n: int) -> int: ans = 0 while n: n -= n & (-n) ans += 1 return ans
Solution
python
doocs__leetcode
solution/1100-1199/1134.Armstrong Number/Solution.py
{ "start": 0, "end": 194 }
class ____: def isArmstrong(self, n: int) -> bool: k = len(str(n)) s, x = 0, n while x: s += (x % 10) ** k x //= 10 return s == n
Solution
python
ray-project__ray
release/train_tests/benchmark/config.py
{ "start": 809, "end": 883 }
class ____(TaskConfig): TASK_NAME: ClassVar[str] = "recsys"
RecsysConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol50.py
{ "start": 176, "end": 240 }
class ____(Protocol[V_co]): def f(self, /) -> V_co: ...
Proto1
python
pydata__xarray
xarray/tests/test_plot.py
{ "start": 95848, "end": 96380 }
class ____(PlotTestCase): @pytest.fixture(autouse=True) def setUp(self) -> None: self.darray = xr.tutorial.scatter_example_dataset() def test_legend_labels(self) -> None: fg = self.darray.A.plot.line(col="x", row="w", hue="z") all_legend_labels = [t.get_text() for t in fg.figlegend....
TestFacetedLinePlotsLegend
python
getsentry__sentry
src/sentry/identity/vsts/provider.py
{ "start": 5327, "end": 6285 }
class ____(OAuth2CallbackView): def get_access_token(self, pipeline: IdentityPipeline, code: str) -> Response: data = { "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion": self.client_secret, "grant_type": "urn:ietf:param...
VSTSOAuth2CallbackView
python
huggingface__transformers
tests/models/altclip/test_processing_altclip.py
{ "start": 804, "end": 942 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = AltCLIPProcessor model_id = "BAAI/AltCLIP"
AltClipProcessorTest
python
uqfoundation__dill
dill/tests/test_session.py
{ "start": 3228, "end": 3440 }
class ____(Calendar): def weekdays(self): return [day_name[i] for i in self.iterweekdays()] cal = CalendarSubclass() selfref = __main__ # Setup global namespace for session saving tests.
CalendarSubclass
python
google__jax
jax/_src/lax/control_flow/solves.py
{ "start": 6941, "end": 20383 }
class ____(collections.namedtuple( '_LinearSolveTuple', 'matvec, vecmat, solve, transpose_solve')): def transpose(self): return type(self)(self.vecmat, self.matvec, self.transpose_solve, self.solve) def _split_linear_solve_args(args, const_lengths): params_list = split_list(args, list(const_lengths)) r...
_LinearSolveTuple
python
doocs__leetcode
solution/2200-2299/2219.Maximum Sum Score of Array/Solution.py
{ "start": 0, "end": 231 }
class ____: def maximumSumScore(self, nums: List[int]) -> int: l, r = 0, sum(nums) ans = -inf for x in nums: l += x ans = max(ans, l, r) r -= x return ans
Solution
python
google__jax
docs/autodidax.py
{ "start": 2916, "end": 5458 }
class ____(NamedTuple): name: str add_p = Primitive('add') mul_p = Primitive('mul') neg_p = Primitive("neg") sin_p = Primitive("sin") cos_p = Primitive("cos") reduce_sum_p = Primitive("reduce_sum") greater_p = Primitive("greater") less_p = Primitive("less") transpose_p = Primitive("transpose") broadcast_p = Primitiv...
Primitive
python
ray-project__ray
rllib/utils/minibatch_utils.py
{ "start": 7960, "end": 8208 }
class ____(MiniBatchIteratorBase): def __init__(self, batch: MultiAgentBatch, **kwargs): super().__init__(batch, **kwargs) self._batch = batch def __iter__(self): yield self._batch @DeveloperAPI
MiniBatchDummyIterator
python
kamyu104__LeetCode-Solutions
Python/is-graph-bipartite.py
{ "start": 39, "end": 719 }
class ____(object): def isBipartite(self, graph): """ :type graph: List[List[int]] :rtype: bool """ color = {} for node in xrange(len(graph)): if node in color: continue stack = [node] color[node] = 0 whi...
Solution
python
kamyu104__LeetCode-Solutions
Python/last-stone-weight.py
{ "start": 48, "end": 445 }
class ____(object): def lastStoneWeight(self, stones): """ :type stones: List[int] :rtype: int """ max_heap = [-x for x in stones] heapq.heapify(max_heap) for i in xrange(len(stones)-1): x, y = -heapq.heappop(max_heap), -heapq.heappop(max_heap) ...
Solution
python
google__jax
jax/experimental/mosaic/gpu/fragmented_array.py
{ "start": 24811, "end": 34804 }
class ____: """Convert the array to 1D and then shard across threads.""" shape: tuple[int, ...] vec_size: int def __post_init__(self): if np.prod(self.shape) % (self.vec_size * WARPGROUP_SIZE) != 0: raise ValueError((self, WARPGROUP_SIZE)) @classmethod def from_shaped_type(cls, shaped_ty: ir.Ty...
WGStridedFragLayout
python
facebookresearch__faiss
tests/test_factory.py
{ "start": 7734, "end": 8028 }
class ____(unittest.TestCase): def test_clone(self): index = faiss.index_factory(16, 'IVF10,PQ4np') xb = faiss.rand((1000, 16)) index.train(xb) index.add(xb) index2 = faiss.clone_index(index) assert index2.ntotal == index.ntotal
TestCloneIVFPQ
python
readthedocs__readthedocs.org
readthedocs/proxito/tests/test_old_redirects.py
{ "start": 44567, "end": 55066 }
class ____(BaseDocServing): def test_redirect_exact_redirect_with_wildcard_crossdomain(self): """ Avoid redirecting to an external site unless the external site is in to_url. We also test by trying to bypass the protocol check with the special chars listed at https://github.com/pyth...
UserRedirectCrossdomainTest
python
apache__airflow
helm-tests/tests/helm_tests/security/test_rbac.py
{ "start": 4092, "end": 21821 }
class ____: """Tests RBAC.""" def _get_values_with_version(self, values, version): if version != "default": values["airflowVersion"] = version return values def _is_airflow_3_or_above(self, version): return version == "default" or (parse_version(version) >= parse_versio...
TestRBAC
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictClosed2.py
{ "start": 130, "end": 306 }
class ____(TypedDict, extra_items=int): name: str def func1(movie: Movie1) -> None: del movie["year"] # This should generate an error. del movie["name"]
Movie1
python
MongoEngine__mongoengine
docs/code/tumblelog.py
{ "start": 152, "end": 302 }
class ____(Document): email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50)
User
python
django__django
django/views/generic/dates.py
{ "start": 20079, "end": 20423 }
class ____(BaseDayArchiveView): """ Base view for a list of objects published today. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" return self._get_dated_items(datetime.date.tod...
BaseTodayArchiveView
python
django__django
tests/redirects_tests/tests.py
{ "start": 628, "end": 3315 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create( site=self.site, old_path="/initial", new_path="/new_target" ) self.assertEqual(str(r1), "/initial ---> ...
RedirectTests
python
aio-libs__aiohttp
aiohttp/http_writer.py
{ "start": 1343, "end": 12691 }
class ____(AbstractStreamWriter): length: int | None = None chunked: bool = False _eof: bool = False _compress: ZLibCompressor | None = None def __init__( self, protocol: BaseProtocol, loop: asyncio.AbstractEventLoop, on_chunk_sent: _T_OnChunkSent = None, on...
StreamWriter
python
keras-team__keras
keras/src/ops/operation_test.py
{ "start": 244, "end": 571 }
class ____(operation.Operation): def call(self, x, y, z=None): # `z` has to be put first due to the order of operations issue with # torch backend. return 3 * z + x + 2 * y def compute_output_spec(self, x, y, z=None): return keras_tensor.KerasTensor(x.shape, x.dtype)
OpWithMultipleInputs
python
doocs__leetcode
solution/2000-2099/2063.Vowels of All Substrings/Solution.py
{ "start": 0, "end": 165 }
class ____: def countVowels(self, word: str) -> int: n = len(word) return sum((i + 1) * (n - i) for i, c in enumerate(word) if c in 'aeiou')
Solution
python
mlflow__mlflow
mlflow/entities/logged_model_input.py
{ "start": 127, "end": 720 }
class ____(_MlflowObject): """ModelInput object associated with a Run.""" def __init__(self, model_id: str): self._model_id = model_id def __eq__(self, other: _MlflowObject) -> bool: if type(other) is type(self): return self.__dict__ == other.__dict__ return False ...
LoggedModelInput
python
ipython__ipython
IPython/core/magic.py
{ "start": 27631, "end": 29162 }
class ____: """An alias to another magic function. An alias is determined by its magic name and magic kind. Lookup is done at call time, so if the underlying magic changes the alias will call the new function. Use the :meth:`MagicsManager.register_alias` method or the `%alias_magic` magic func...
MagicAlias
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/source.py
{ "start": 18949, "end": 21636 }
class ____(Oauth2Authenticator): """Request example for API token extraction: curl --location --request POST https://oauth2.googleapis.com/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=signed_JWT """ def __init__(self, config: Mapping): self.credentials_json = json....
GoogleAnalyticsServiceOauth2Authenticator
python
huggingface__transformers
src/transformers/models/unispeech/modeling_unispeech.py
{ "start": 22974, "end": 26020 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_drop...
UniSpeechEncoderStableLayerNorm
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py
{ "start": 4336, "end": 4681 }
class ____: """Test EcsExecutorException class.""" def test_ecs_executor_exception_creation(self): """Test EcsExecutorException creation.""" exception = EcsExecutorException("Test error message") assert str(exception) == "Test error message" assert isinstance(exception, Exceptio...
TestEcsExecutorException
python
huggingface__transformers
src/transformers/models/glm4/modeling_glm4.py
{ "start": 19504, "end": 22953 }
class ____(Glm4PreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = Glm4Mode...
Glm4ForCausalLM
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/auto_tab_active.py
{ "start": 112, "end": 1361 }
class ____(App): BINDINGS = [("space", "focus_button_2_2", "Focus button 2.2")] def compose(self) -> ComposeResult: with TabbedContent(id="tabbed-root"): with TabPane("[ansi_red]Parent 1[/]"): with TabbedContent(): with TabPane("[ansi_red]Child 1.1[/]"): ...
ExampleApp
python
pennersr__django-allauth
allauth/socialaccount/providers/tumblr_oauth2/views.py
{ "start": 181, "end": 1154 }
class ____(OAuth2Adapter): provider_id = "tumblr_oauth2" access_token_url = "https://api.tumblr.com/v2/oauth2/token" # nosec: B105 authorize_url = "https://www.tumblr.com/oauth2/authorize" profile_url = "https://api.tumblr.com/v2/user/info" def complete_login(self, request, app, token, response): ...
TumblrOAuth2Adapter
python
kamyu104__LeetCode-Solutions
Python/random-pick-index.py
{ "start": 605, "end": 1102 }
class ____(object): def __init__(self, nums): """ :type nums: List[int] """ self.__nums = nums def pick(self, target): """ :type target: int :rtype: int """ reservoir = -1 n = 0 for i in xrange(len(self.__nums)): ...
Solution_TLE