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
kamyu104__LeetCode-Solutions
Python/find-the-length-of-the-longest-common-prefix.py
{ "start": 725, "end": 1246 }
class ____(object): def longestCommonPrefix(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: int """ lookup = {0} for x in arr1: while x not in lookup: lookup.add(x) x //= 10 result ...
Solution2
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 375071, "end": 478991 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "abort_queued_migrations", "accept_enterprise_administrator_invitation", "accept_topic_suggestion", "add_assignees_to_assignable", "add_commen...
Mutation
python
PrefectHQ__prefect
src/prefect/settings/models/server/services.py
{ "start": 1563, "end": 3787 }
class ____(ServicesBaseSetting): """ Settings for controlling the event persister service """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "services", "event_persister") ) enabled: bool = Field( default=True, description="Whether or not...
ServerServicesEventPersisterSettings
python
hynek__structlog
tests/test_threadlocal.py
{ "start": 11271, "end": 13821 }
class ____: def test_cleanup(self): """ Bindings are cleaned up """ with pytest.deprecated_call(), bound_threadlocal(x=42, y="foo"): assert {"x": 42, "y": "foo"} == get_threadlocal() with pytest.deprecated_call(): assert {} == get_threadlocal() d...
TestBoundThreadlocal
python
pytorch__pytorch
torch/__init__.py
{ "start": 71423, "end": 71643 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.int
IntStorage
python
django__django
tests/admin_widgets/tests.py
{ "start": 1671, "end": 9991 }
class ____(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned ...
AdminFormfieldForDBFieldTests
python
getsentry__sentry
src/sentry/tasks/check_am2_compatibility.py
{ "start": 9214, "end": 26963 }
class ____: @classmethod def get_widget_url(cls, org_slug, dashboard_id, widget_id) -> str: return f"https://{org_slug}.sentry.io/organizations/{org_slug}/dashboard/{dashboard_id}/widget/{widget_id}/" @classmethod def get_alert_url(cls, org_slug, alert_id) -> str: return f"https://{org_...
CheckAM2Compatibility
python
getsentry__sentry-python
tests/integrations/django/myapp/views.py
{ "start": 2444, "end": 3279 }
class ____: def __call__(self, request): return HttpResponse("ok") @csrf_exempt def read_body_and_view_exc(request): request.read() 1 / 0 @csrf_exempt def message(request): sentry_sdk.capture_message("hi") return HttpResponse("ok") @csrf_exempt def nomessage(request): return HttpRe...
SentryClassBasedViewWithCsrf
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/styles/base.py
{ "start": 352, "end": 2833 }
class ____(NamedTuple): color: str | None bgcolor: str | None bold: bool | None underline: bool | None strike: bool | None italic: bool | None blink: bool | None reverse: bool | None hidden: bool | None dim: bool | None """ :param color: Hexadecimal string. E.g. '000000' or Ans...
Attrs
python
wandb__wandb
wandb/vendor/pygments/filter.py
{ "start": 1069, "end": 1351 }
class ____(object): """ Default filter. Subclass this class or use the `simplefilter` decorator to create own filters. """ def __init__(self, **options): self.options = options def filter(self, lexer, stream): raise NotImplementedError
Filter
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-divide-array-into-subarrays.py
{ "start": 180, "end": 339 }
class ____(object): def __init__(self, level=0, val=None): self.val = val self.nexts = [None]*level self.prevs = [None]*level
SkipNode
python
psf__black
tests/util.py
{ "start": 2676, "end": 6344 }
class ____(Exception): """Used to wrap failures when assert_format() runs in an extra mode.""" def assert_format( source: str, expected: str, mode: black.Mode = DEFAULT_MODE, *, fast: bool = False, minimum_version: tuple[int, int] | None = None, lines: Collection[tuple[int, int]] = (),...
FormatFailure
python
huggingface__transformers
src/transformers/models/glm4v/modular_glm4v.py
{ "start": 70726, "end": 71013 }
class ____(Qwen2VLProcessorKwargs): _defaults = { "text_kwargs": { "padding": False, "return_token_type_ids": False, "return_mm_token_type_ids": False, }, "videos_kwargs": {"return_metadata": True}, }
Glm4vProcessorKwargs
python
kubernetes-client__python
kubernetes/client/models/v1_self_subject_review_status.py
{ "start": 383, "end": 3492 }
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...
V1SelfSubjectReviewStatus
python
sympy__sympy
sympy/physics/mechanics/wrapping_geometry.py
{ "start": 17936, "end": 30055 }
class ____(WrappingGeometryBase): """A solid (infinite) conical object. Explanation =========== A wrapping geometry that allows for circular arcs to be defined between pairs of points on the surface of a cone. These paths are always geodetic (the shortest possible) in the sense that they becom...
WrappingCone
python
instagram__MonkeyType
monkeytype/stubs.py
{ "start": 26251, "end": 33070 }
class ____: _KIND_WITH_SELF = { FunctionKind.CLASS, FunctionKind.INSTANCE, FunctionKind.PROPERTY, FunctionKind.DJANGO_CACHED_PROPERTY, } def __init__( self, module: str, qualname: str, kind: FunctionKind, sig: inspect.Signature, ...
FunctionDefinition
python
django__django
tests/transactions/tests.py
{ "start": 17465, "end": 19135 }
class ____(TransactionTestCase): available_apps = ["transactions"] @skipIf(threading is None, "Test requires threading") def test_implicit_savepoint_rollback(self): """ MySQL implicitly rolls back savepoints when it deadlocks (#22291). """ Reporter.objects.create(id=1) ...
AtomicMySQLTests
python
getsentry__sentry
tests/sentry/integrations/vsts/test_integration.py
{ "start": 1305, "end": 8271 }
class ____(VstsIntegrationTestCase): # Test regular install still works @with_feature("organizations:migrate-azure-devops-integration") @patch( "sentry.integrations.vsts.VstsIntegrationProvider.get_scopes", return_value=VstsIntegrationProvider.NEW_SCOPES, ) @patch( "sentry.i...
VstsIntegrationMigrationTest
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py
{ "start": 18153, "end": 18236 }
class ____(GroundingDinoMLPPredictionHead): pass
MMGroundingDinoMLPPredictionHead
python
django-extensions__django-extensions
django_extensions/management/commands/delete_squashed_migrations.py
{ "start": 410, "end": 7731 }
class ____(BaseCommand): help = ( "Deletes left over migrations that have been replaced by a " "squashed migration and converts squashed migration into a normal " "migration. Modifies your source tree! Use with care!" ) def add_arguments(self, parser): parser.add_argument( ...
Command
python
faif__python-patterns
patterns/dependency_injection.py
{ "start": 1444, "end": 1805 }
class ____: def __init__(self) -> None: pass def get_current_time_as_html_fragment(self, time_provider: Callable) -> str: current_time = time_provider() current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format( current_time ) return curre...
ParameterInjection
python
redis__redis-py
redis/asyncio/multidb/healthcheck.py
{ "start": 5753, "end": 6308 }
class ____(HealthCheck): """ Health check based on PING command. """ async def check_health(self, database) -> bool: if isinstance(database.client, Redis): return await database.client.execute_command("PING") else: # For a cluster checks if all nodes are healthy....
PingHealthCheck
python
ray-project__ray
python/ray/data/expressions.py
{ "start": 3782, "end": 6544 }
class ____(_ExprVisitor["pyarrow.compute.Expression"]): """Visitor that converts Ray Data expressions to PyArrow compute expressions.""" def visit_column(self, expr: "ColumnExpr") -> "pyarrow.compute.Expression": return pc.field(expr.name) def visit_literal(self, expr: "LiteralExpr") -> "pyarrow....
_PyArrowExpressionVisitor
python
huggingface__transformers
src/transformers/models/deit/modeling_deit.py
{ "start": 11642, "end": 12298 }
class ____(nn.Module): def __init__(self, config: DeiTConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.interm...
DeiTIntermediate
python
walkccc__LeetCode
solutions/3048. Earliest Second to Mark Indices I/3048.py
{ "start": 0, "end": 1093 }
class ____: def earliestSecondToMarkIndices( self, nums: list[int], changeIndices: list[int], ) -> int: def canMark(second: int) -> bool: """ Returns True if all indices of `nums` can be marked within `second`. """ numMarked = 0 decrement = 0 indexToLastSeco...
Solution
python
getsentry__sentry
src/sentry/sdk_updates.py
{ "start": 330, "end": 1328 }
class ____: def __init__(self, sdk_name, sdk_version, modules, integrations): self.sdk_name = sdk_name self.sdk_version = sdk_version self.modules = dict(modules or ()) self.integrations = list(integrations or ()) def copy(self): return type(self)( sdk_name=s...
SdkSetupState
python
doocs__leetcode
solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py
{ "start": 677, "end": 1018 }
class ____: def findNumberOfLIS(self, nums: List[int]) -> int: arr = sorted(set(nums)) m = len(arr) tree = BinaryIndexedTree(m) for x in nums: i = bisect_left(arr, x) + 1 v, cnt = tree.query(i - 1) tree.update(i, v + 1, max(cnt, 1)) return ...
Solution
python
marshmallow-code__marshmallow
src/marshmallow/fields.py
{ "start": 36829, "end": 40169 }
class ____(Number[decimal.Decimal]): """A field that (de)serializes to the Python ``decimal.Decimal`` type. It's safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical. .. warning:: This field serializes to a `decimal.Decimal` object by def...
Decimal
python
wireservice__csvkit
csvkit/utilities/csvformat.py
{ "start": 143, "end": 4308 }
class ____(CSVKitUtility): description = 'Convert a CSV file to a custom output format.' override_flags = ['I'] def add_arguments(self): self.argparser.add_argument( '-E', '--skip-header', dest='skip_header', action='store_true', help='Do not output a header row.') s...
CSVFormat
python
PrefectHQ__prefect
tests/server/schemas/test_schedules.py
{ "start": 15993, "end": 21306 }
class ____: async def test_interval_schedule_always_has_the_right_offset(self): """ Tests the situation where a long duration has passed since the start date that crosses a DST boundary; for very short intervals this occasionally could result in "next" scheduled times that are in the past by...
TestIntervalScheduleDaylightSavingsTime
python
pytorch__pytorch
test/torch_np/test_basic.py
{ "start": 2381, "end": 3209 }
class ____(TestCase): @parametrize("func", one_arg_axis_funcs) @parametrize("axis", [0, 1, -1, None]) def test_andaxis_tensor(self, func, axis): t = torch.Tensor([[1.0, 2, 3], [4, 5, 6]]) ta = func(t, axis=axis) assert isinstance(ta, w.ndarray) @parametrize("func", one_arg_axis_...
TestOneArrAndAxis
python
spyder-ide__spyder
spyder/plugins/run/tests/test_run.py
{ "start": 6265, "end": 7957 }
class ____(RunExecutorConfigurationGroup): def __init__(self, parent: QWidget, context: Context, input_extension: str, input_metadata: RunConfigurationMetadata): super().__init__(parent, context, input_extension, input_metadata) default_conf = self.get_default_configuration() ...
GenExampleRunExecutorConf
python
scikit-learn__scikit-learn
sklearn/multiclass.py
{ "start": 3917, "end": 5919 }
class ____(BaseEstimator): """Helper predictor to be used when only one class is present.""" def fit(self, X, y): check_params = dict( ensure_all_finite=False, dtype=None, ensure_2d=False, accept_sparse=True ) validate_data( self, X, y, reset=True, validate_separ...
_ConstantPredictor
python
ray-project__ray
doc/external/pytorch_tutorials_hyperparameter_tuning_tutorial.py
{ "start": 3077, "end": 19391 }
class ____(nn.Module): def __init__(self, l1=120, l2=84): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, l1) self.fc2 = nn.Linear(l1, l2) self.fc3 = n...
Net
python
PrefectHQ__prefect
tests/client/test_collections_metadata_client.py
{ "start": 231, "end": 2076 }
class ____: async def test_returns_cloud_client_when_server_type_is_cloud(self, monkeypatch): mock_get_client = MagicMock() mock_get_cloud_client = MagicMock() monkeypatch.setattr("prefect.client.collections.get_client", mock_get_client) monkeypatch.setattr( "prefect.clie...
TestGetCollectionsMetadataClient
python
pytorch__pytorch
torch/nn/modules/container.py
{ "start": 27819, "end": 37672 }
class ____(Module): r"""Holds parameters in a dictionary. ParameterDict can be indexed like a regular Python dictionary, but Parameters it contains are properly registered, and will be visible by all Module methods. Other objects are treated as would be done by a regular Python dictionary :class:`...
ParameterDict
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_search_query_performance_report.py
{ "start": 23456, "end": 30934 }
class ____(TestBaseProductSearchQueryPerformanceReport): stream_name = "product_search_query_performance_report_monthly" report_file = "product_search_query_performance_report_monthly" records_number = 6 incremental_report_file = "product_search_query_performance_report_monthly_incremental" incremen...
TestProductSearchQueryPerformanceReportMonthlyStream
python
getsentry__sentry
src/sentry/utils/kvstore/memory.py
{ "start": 217, "end": 297 }
class ____(Generic[V]): value: V expires_at: datetime | None = None
Record
python
oauthlib__oauthlib
tests/openid/connect/core/grant_types/test_base.py
{ "start": 210, "end": 391 }
class ____(GrantTypeBase): """Class to test GrantTypeBase""" def __init__(self, request_validator=None, **kwargs): self.request_validator = request_validator
GrantBase
python
joke2k__faker
tests/providers/test_address.py
{ "start": 56924, "end": 58736 }
class ____: """Test zh_TW address provider methods""" def test_postcode(self, faker, num_samples): for _ in range(num_samples): postcode = faker.postcode() assert isinstance(postcode, str) assert re.fullmatch(r"[1-9]\d{2}(?:\d{2})?", postcode) def test_city_name...
TestZhTw
python
tensorflow__tensorflow
tensorflow/python/training/server_lib_test.py
{ "start": 16029, "end": 19418 }
class ____(test.TestCase): def testLocalServer(self): cluster_def = server_lib.ClusterSpec( {"local": ["localhost:2222"]} ).as_cluster_def() server_def = tensorflow_server_pb2.ServerDef( cluster=cluster_def, job_name="local", task_index=0, protocol="grpc" ) self.assertProtoEquals...
ServerDefTest
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 59961, "end": 60460 }
class ____(CBaseTypeNode): # base_type CBaseTypeNode # is_const boolean # is_volatile boolean child_attrs = ["base_type"] def analyse(self, env, could_be_name=False): base = self.base_type.analyse(env, could_be_name) if base.is_pyobject: error(self.pos, ...
CConstOrVolatileTypeNode
python
google__jax
jax/_src/core.py
{ "start": 140691, "end": 151295 }
class ____: var_names: defaultdict[Var, str] # Shared jaxprs are those that are used multiple times and are printed # first. shared_jaxprs: MutableMapping[Jaxpr, str] # maps shared jaxpr to its name shared_jaxpr_names: MutableSet[str] def __init__(self) -> None: self.shared_jaxprs = {} self.shared...
JaxprPpContext
python
numba__numba
numba/cuda/tests/cudadrv/test_emm_plugins.py
{ "start": 6683, "end": 7094 }
class ____(CUDATestCase): """ Ensure that Numba rejects EMM Plugins with incompatible version numbers. """ def test_bad_plugin_version(self): with self.assertRaises(RuntimeError) as raises: cuda.set_memory_manager(BadVersionEMMPlugin) self.assertIn('version 1 required', ...
TestBadEMMPluginVersion
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue_crawler.py
{ "start": 1103, "end": 2372 }
class ____(AwsBaseWaiterTrigger): """ Watches for a glue crawl, triggers when it finishes. :param crawler_name: name of the crawler to watch :param aws_conn_id: The Airflow connection used for AWS credentials. """ def __init__( self, crawler_name: str, aws_conn_id: str ...
GlueCrawlerCompleteTrigger
python
ipython__ipython
tests/test_pretty.py
{ "start": 972, "end": 1034 }
class ____(object): def somemethod(self): pass
MyObj
python
sphinx-doc__sphinx
sphinx/directives/admonitions.py
{ "start": 1750, "end": 1808 }
class ____(SphinxAdmonition): node_class = nodes.tip
Tip
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/logging_/test_logger_connector.py
{ "start": 5338, "end": 6080 }
class ____(Callback): def __init__(self, not_supported): def call(hook, trainer=None, model=None, *_, **__): if trainer is None: # `state_dict`, `load_state_dict` do not have the `Trainer` available assert hook in ("state_dict", "load_state_dict") ...
HookedCallback
python
openai__openai-python
src/openai/types/beta/assistant_tool_choice_function.py
{ "start": 165, "end": 269 }
class ____(BaseModel): name: str """The name of the function to call."""
AssistantToolChoiceFunction
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 61310, "end": 61718 }
class ____(torch.nn.Module): def __init__(self, mod_type): super().__init__() self.qconfig = default_dynamic_qconfig if mod_type == "GRU": self.mod = torch.nn.GRU(2, 2).to(dtype=torch.float) if mod_type == "LSTM": self.mod = torch.nn.LSTM(2, 2).to(dtype=torch....
RNNDynamicModel
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 28488, "end": 61637 }
class ____(TestFeedExportBase): async def run_and_export( self, spider_cls: type[Spider], settings: dict[str, Any] ) -> dict[str, Any]: """Run spider with specified settings; return exported data.""" FEEDS = settings.get("FEEDS") or {} settings["FEEDS"] = { printf_es...
TestFeedExport
python
python__mypy
mypy/fastparse.py
{ "start": 84921, "end": 86233 }
class ____(TraverserVisitor): """Check if an AST contains attribute assignments (e.g. self.x = 0).""" def __init__(self) -> None: self.lvalue = False self.found = False def visit_assignment_stmt(self, s: AssignmentStmt) -> None: self.lvalue = True for lv in s.lvalues: ...
FindAttributeAssign
python
great-expectations__great_expectations
contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_average_to_be_within_range_of_given_point.py
{ "start": 1337, "end": 2632 }
class ____(ColumnAggregateMetricProvider): # This is the id string that will be used to reference your Metric. metric_name = "column.coordinates.distance" value_keys = ("center_point",) # This method implements the core logic for the PandasExecutionEngine @column_aggregate_value(engine=PandasExecut...
ColumnCoordinatesDistance
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 14430, "end": 14504 }
class ____: __slots__ = () _resolve_literal_only = True
_StringOnly
python
kamyu104__LeetCode-Solutions
Python/subarrays-distinct-element-sum-of-squares-ii.py
{ "start": 2015, "end": 6244 }
class ____(object): def sumCounts(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 # Template: # https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/longest-substring-of-one-repeating-character.py class SegmentTree(obj...
Solution2
python
huggingface__transformers
src/transformers/models/splinter/modeling_splinter.py
{ "start": 12919, "end": 13090 }
class ____(PreTrainedModel): config: SplinterConfig base_model_prefix = "splinter" supports_gradient_checkpointing = True @auto_docstring
SplinterPreTrainedModel
python
django__django
tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
{ "start": 26535, "end": 26638 }
class ____(TranslationBlockTranslateTagTests): tag_name = "blocktrans"
TranslationBlockTransnTagTests
python
numba__numba
numba/tests/test_numpy_support.py
{ "start": 8426, "end": 9647 }
class ____(object): __slots__ = ('nin', 'nout', 'types', 'ntypes') __name__ = "fake ufunc" def __init__(self, types): self.types = types in_, out = self.types[0].split('->') self.nin = len(in_) self.nout = len(out) self.ntypes = len(types) for tp in types: ...
FakeUFunc
python
run-llama__llama_index
llama-index-integrations/voice_agents/llama-index-voice-agents-elevenlabs/llama_index/voice_agents/elevenlabs/events.py
{ "start": 390, "end": 508 }
class ____(BaseVoiceAgentEvent): model_config = ConfigDict(extra="allow") agent_response: str
AgentResponseEvent
python
pyqtgraph__pyqtgraph
pyqtgraph/multiprocess/remoteproxy.py
{ "start": 208, "end": 384 }
class ____(Exception): """Raised when an event handler receives a request to close the connection or discovers that the connection has been closed.""" pass
ClosedError
python
kamyu104__LeetCode-Solutions
Python/longest-even-odd-subarray-with-threshold.py
{ "start": 37, "end": 506 }
class ____(object): def longestAlternatingSubarray(self, nums, threshold): """ :type nums: List[int] :type threshold: int :rtype: int """ result = l = 0 for x in nums: if x > threshold: l = 0 continue if ...
Solution
python
ansible__ansible
test/lib/ansible_test/_internal/commands/integration/coverage.py
{ "start": 12681, "end": 15601 }
class ____: """Manager for code coverage configuration and state.""" def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None: self.args = args self.host_state = host_state self.inventory_path = inventory_path if self.args.coverage: ...
CoverageManager
python
spack__spack
lib/spack/spack/fetch_strategy.py
{ "start": 66106, "end": 66220 }
class ____(spack.error.FetchError): """Raised after attempt to checksum when URL has no digest."""
NoDigestError
python
kamyu104__LeetCode-Solutions
Python/rectangle-area-ii.py
{ "start": 1002, "end": 1797 }
class ____(object): def rectangleArea(self, rectangles): """ :type rectangles: List[List[int]] :rtype: int """ OPEN, CLOSE = 1, -1 events = [] X = set() for x1, y1, x2, y2 in rectangles: events.append((y1, OPEN, x1, x2)) events....
Solution
python
TheAlgorithms__Python
data_structures/heap/binomial_heap.py
{ "start": 73, "end": 1268 }
class ____: """ Node in a doubly-linked binomial tree, containing: - value - size of left subtree - link to left, right and parent nodes """ def __init__(self, val): self.val = val # Number of nodes in left subtree self.left_tree_size = 0 self.lef...
Node
python
neetcode-gh__leetcode
python/0513-find-bottom-left-tree-value.py
{ "start": 204, "end": 734 }
class ____: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: res = [] q = deque() q.append(root) while q: qlen = len(q) level = [] for i in range(qlen): node = q.popleft() if node: ...
Solution
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 393452, "end": 395261 }
class ____(ExprNode): # An inlined generator expression for which the result is calculated # inside of the loop and returned as a single, first and only Generator # return value. # This will only be created by transforms when replacing safe builtin # calls on generator expressions. # # gen ...
InlinedGeneratorExpressionNode
python
numba__numba
numba/parfors/parfor_lowering_utils.py
{ "start": 170, "end": 5638 }
class ____: """Helper class for building Numba-IR and lowering for Parfor. """ def __init__(self, lowerer, scope, loc): self._lowerer = lowerer self._scope = scope self._loc = loc @property def _context(self): return self._lowerer.context @property def _typi...
ParforLoweringBuilder
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/pygments_highlighter.py
{ "start": 3208, "end": 3744 }
class ____(QtGui.QTextBlockUserData): """ Storage for the user data associated with each line. """ syntax_stack = ('root',) def __init__(self, **kwds): for key, value in kwds.items(): setattr(self, key, value) QtGui.QTextBlockUserData.__init__(self) def __repr__(self):...
PygmentsBlockUserData
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_with_default_factory.py
{ "start": 552, "end": 1118 }
class ____: """Test dataclass that uses a renamed import of dataclasses""" int_prop: int = dc.field(default=10) list_prop: list = dc.field(default_factory=list) dict_prop: dict = dc.field(default_factory=dict) TEST2 = Test2() for _ in TEST2.list_prop: # This is okay pass TEST2.dict_prop["key"] ...
Test2
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 5891, "end": 6196 }
class ____(HTTPException): """*400* `Bad Request` Raise if the browser sends something to the application the application or server cannot handle. """ code = 400 description = ( "The browser (or proxy) sent a request that this server could not understand." )
BadRequest
python
huggingface__transformers
src/transformers/models/omdet_turbo/modeling_omdet_turbo.py
{ "start": 43394, "end": 51209 }
class ____(PreTrainedModel): config: OmDetTurboConfig base_model_prefix = "model" main_input_name = "pixel_values" input_modalities = ("image", "text") @torch.no_grad() def _init_weights(self, module): def linear_init_(module_to_init): bound = 1 / math.sqrt(module_to_init.we...
OmDetTurboPreTrainedModel
python
pytorch__pytorch
test/dynamo/test_repros.py
{ "start": 29300, "end": 29368 }
class ____: def __init__(self, x): self.x = x + 1
IncByOne
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 21837, "end": 22845 }
class ____(HTTPException): """*500* `Internal Server Error` Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher. .. versionchanged:: 1.0.0 Added the :attr:`original_exception` attribute. """ code = 500 description = (...
InternalServerError
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/junkdrawer.py
{ "start": 5671, "end": 9013 }
class ____(Generic[T]): """A "copy" of a sequence that works by inserting a mask in front of the underlying sequence, so that you can mutate it without changing the underlying sequence. Effectively behaves as if you could do list(x) in O(1) time. The full list API is not supported yet but there's no rea...
LazySequenceCopy
python
google__pytype
pytype/tests/test_dataclass_transform.py
{ "start": 97, "end": 997 }
class ____(test_base.BaseTest): """Tests for the @dataclass_transform decorator.""" def test_invalid_target(self): self.CheckWithErrors(""" from typing_extensions import dataclass_transform x = 10 dataclass_transform()(x) # dataclass-error """) def test_args(self): self.CheckWithEr...
TestDecorator
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/cardinality.py
{ "start": 3824, "end": 4578 }
class ____(dataset_ops.UnaryUnchangedStructureDataset): """A `Dataset` that assert the cardinality of its input.""" def __init__(self, input_dataset, expected_cardinality): self._input_dataset = input_dataset self._expected_cardinality = ops.convert_to_tensor( expected_cardinality, dtype=dtypes.int...
_AssertCardinalityDataset
python
pypa__warehouse
tests/unit/test_tasks.py
{ "start": 12034, "end": 17320 }
class ____: def test_gets_task(self): task_func = pretend.stub(__name__="task_func", __module__="tests.foo") task_obj = pretend.stub() celery_app = pretend.stub( gen_task_name=lambda func, module: module + "." + func, tasks={"tests.foo.task_func": task_obj}, )...
TestCeleryTaskGetter
python
joke2k__faker
tests/test_generator.py
{ "start": 487, "end": 5224 }
class ____: """Test Generator class""" def test_get_formatter_returns_correct_formatter(self, generator): foo_provider = generator.providers[0] formatter = generator.get_formatter("foo_formatter") assert callable(formatter) and formatter == foo_provider.foo_formatter def test_get_f...
TestGenerator
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/client.py
{ "start": 2856, "end": 8627 }
class ____(ApiClient): # Forked from ApiClient implementation to pass configuration object down into created model # objects, avoiding lock contention issues. See https://github.com/kubernetes-client/python/issues/2284 # Intentionally circumventing private name mangling # (https://docs.python.org/3/refe...
PatchedApiClient
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 70971, "end": 75982 }
class ____(BaseField): """Provides a sequential counter see: https://www.mongodb.com/docs/manual/reference/method/ObjectId/#ObjectIDs-SequenceNumbers .. note:: Although traditional databases often use increasing sequence numbers for primary keys. In MongoDB, the preferred approa...
SequenceField
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/message_count_tokens_params.py
{ "start": 2364, "end": 10063 }
class ____(TypedDict, total=False): messages: Required[Iterable[BetaMessageParam]] """Input messages. Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter...
MessageCountTokensParams
python
doocs__leetcode
solution/1500-1599/1544.Make The String Great/Solution.py
{ "start": 0, "end": 254 }
class ____: def makeGood(self, s: str) -> str: stk = [] for c in s: if not stk or abs(ord(stk[-1]) - ord(c)) != 32: stk.append(c) else: stk.pop() return "".join(stk)
Solution
python
python-markdown__markdown
tests/test_syntax/inline/test_autolinks.py
{ "start": 781, "end": 2689 }
class ____(TestCase): def test_email_address(self): self.assertMarkdownRenders( 'asdfasdfadsfasd <yuri@freewisdom.org> or you can say ', '<p>asdfasdfadsfasd <a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#121;&#117;&#114;' '&#105;&#64;&#102;&#114;&#101;&#101;&#119;&#1...
TestAutomaticLinks
python
viewflow__viewflow
viewflow/workflow/flow/viewset.py
{ "start": 423, "end": 5495 }
class ____(metaclass=ViewsetMeta): """Common Views for Flow and FlowApp viewsets""" def __init__(self, flow_class, **kwargs): super().__init__(**kwargs) self._flow_class = flow_class def filter_kwargs(self, view_class, **kwargs): return super().filter_kwargs( view_class...
BaseFlowViewsMixin
python
doocs__leetcode
solution/0700-0799/0766.Toeplitz Matrix/Solution.py
{ "start": 0, "end": 298 }
class ____: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: m, n = len(matrix), len(matrix[0]) for i in range(1, m): for j in range(1, n): if matrix[i][j] != matrix[i - 1][j - 1]: return False return True
Solution
python
walkccc__LeetCode
solutions/3330. Find the Original Typed String I/3330.py
{ "start": 0, "end": 150 }
class ____: def possibleStringCount(self, word: str) -> int: return 1 + sum(a == b for a, b in itertools.pairwise(word))
Solution
python
tiangolo__fastapi
tests/test_response_by_alias.py
{ "start": 267, "end": 11379 }
class ____(BaseModel): name: str if PYDANTIC_V2: model_config = ConfigDict( json_schema_extra={ "description": ( "response_model_by_alias=False is basically a quick hack, to support " "proper OpenAPI use another model with the correct ...
ModelNoAlias
python
explosion__spaCy
spacy/util.py
{ "start": 10280, "end": 11119 }
class ____(dict): """Simplified implementation of a frozen dict, mainly used as default function or method argument (for arguments that should default to empty dictionary). Will raise an error if user or spaCy attempts to add to dict. """ def __init__(self, *args, error: str = Errors.E095, **kwargs...
SimpleFrozenDict
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 200588, "end": 202144 }
class ____(Operation): def __init__(self, repeats, *, name=None): super().__init__(name=name) self.repeats = repeats def call(self, x): return backend.numpy.tile(x, self.repeats) def compute_output_spec(self, x): x_shape = list(x.shape) repeats = self.repeats ...
Tile
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0083_init_generic_webhooks.py
{ "start": 214, "end": 3904 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0082_add_extra_history_fields"), ] operations = [ migrations.CreateModel( name="WebHookEvent", fields=[ ( "id", mod...
Migration
python
tiangolo__fastapi
tests/test_include_router_defaults_overrides.py
{ "start": 176, "end": 255 }
class ____(JSONResponse): media_type = "application/x-level-0"
ResponseLevel0
python
Netflix__metaflow
test/unit/inheritance/flows/mutator_with_base_config_base.py
{ "start": 216, "end": 1854 }
class ____(FlowMutator): """ Mutator that uses config values from base class to inject parameters. This mutator looks for a 'mutator_config' and injects parameters based on its values. """ def init(self, config_name): self.config_name = config_name def pre_mutate(self, mutable_flow): ...
ConfigBasedMutator
python
ipython__ipython
docs/autogen_shortcuts.py
{ "start": 542, "end": 710 }
class ____: #: a sequence of keys (each element on the list corresponds to pressing one or more keys) keys_sequence: List[str] filter: str @dataclass
Shortcut
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 86021, "end": 86412 }
class ____(WebTestCase): def get_handlers(self): return [("/foo", RequestHandler)] def get_app_kwargs(self): return dict( default_handler_class=ErrorHandler, default_handler_args=dict(status_code=403), ) def test_403(self): response = self.fetch("/")...
DefaultHandlerArgumentsTest
python
allegroai__clearml
clearml/backend_api/services/v2_20/queues.py
{ "start": 82618, "end": 83517 }
class ____(Request): """ Peek the next task from a given queue :param queue: ID of the queue :type queue: str """ _service = "queues" _action = "peek_task" _version = "2.20" _schema = { "definitions": {}, "properties": {"queue": {"description": "ID of the queue", "t...
PeekTaskRequest
python
mlflow__mlflow
mlflow/utils/proto_json_utils.py
{ "start": 10690, "end": 27044 }
class ____(MlflowInvalidInputException): def __init__(self, col_name, col_type, ex): super().__init__( message=f"Data is not compatible with model signature. " f"Failed to convert column {col_name} to type '{col_type}'. Error: '{ex!r}'" ) def cast_df_types_according_to_sche...
MlflowFailedTypeConversion
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_class.py
{ "start": 1075, "end": 2138 }
class ____: def test_empty(self): assert get_random_dict_combos({}, 1) == [{}] def test_basic(self): d = {"a": 1, "b": 2, "c": 3} combos = get_random_dict_combos(d, 8) # Sort combos for comparison (sort by length, break ties by value sum) combos.sort(key=lambda d: len(d...
TestGetDictCombos
python
facebookresearch__faiss
demos/index_pq_flat_separate_codes_from_codebook.py
{ "start": 5253, "end": 8362 }
class ____: type_: str index: faiss.Index args: tuple recall: float results = [] for m, nbits in pq_m_nbits: print("pq", m, nbits) index = faiss.index_factory(d, f"IDMap2,PQ{m}x{nbits}") index.train(training_data) index.add_with_ids(database_vector_float32s, database_vector_ids) _...
Record
python
python-visualization__folium
folium/plugins/side_by_side.py
{ "start": 119, "end": 1574 }
class ____(JSCSSMixin, MacroElement): """ Creates a SideBySideLayers that takes two Layers and adds a sliding control with the leaflet-side-by-side plugin. Uses the Leaflet leaflet-side-by-side plugin https://github.com/digidem/leaflet-side-by-side Parameters ---------- layer_left: Layer. ...
SideBySideLayers