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_parallel_backend.py
{ "start": 4658, "end": 5593 }
class ____(object): def __init__(self, method): self._method = method def __call__(self, *args, **kwargs): ctx = multiprocessing.get_context(self._method) return ctx.Process(*args, **kwargs) def _get_mp_classes(method): if method == 'default': method = None ctx = mult...
_proc_class_impl
python
allegroai__clearml
clearml/debugging/log.py
{ "start": 12473, "end": 12551 }
class ____(logging.NullHandler, ClearmlLoggerHandler): pass
ClearmlNullHandler
python
pytorch__pytorch
torch/_library/autograd.py
{ "start": 261, "end": 395 }
class ____(Protocol): _backward_fn: Optional[Callable] _setup_context_fn: Optional[Callable] @dataclasses.dataclass
InfoProtocol
python
sympy__sympy
sympy/stats/rv.py
{ "start": 3494, "end": 4343 }
class ____(RandomDomain): """ A RandomDomain with an attached condition. See Also ======== sympy.stats.crv.ConditionalContinuousDomain sympy.stats.frv.ConditionalFiniteDomain """ def __new__(cls, fulldomain, condition): condition = condition.xreplace({rs: rs.symbol ...
ConditionalDomain
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 4251, "end": 4295 }
class ____(BaseStringType): pass
XsdString
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 138022, "end": 140146 }
class ____(GroupedElement, ColumnElement[_T]): """Represent a grouping within a column expression""" _traverse_internals: _TraverseInternalsType = [ ("element", InternalTraversal.dp_clauseelement), ("type", InternalTraversal.dp_type), ] _cache_key_traversal = [ ("element", Inte...
Grouping
python
networkx__networkx
networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality.py
{ "start": 8144, "end": 10072 }
class ____: def test_K4(self): """Edge flow betweenness centrality: K4""" G = nx.complete_graph(4) b = edge_current_flow(G, normalized=True) b_answer = dict.fromkeys(G.edges(), 0.25) for (s, t), v1 in b_answer.items(): v2 = b.get((s, t), b.get((t, s))) ...
TestEdgeFlowBetweennessCentrality
python
scipy__scipy
scipy/signal/tests/test_windows.py
{ "start": 3650, "end": 4825 }
class ____: def test_basic(self, xp): xp_assert_close(windows.blackmanharris(6, False, xp=xp), xp.asarray([6.0e-05, 0.055645, 0.520575, 1.0, 0.520575, 0.055645], dtype=xp.float64)) xp_assert_close(windows.blackmanharris(7, sym=False, xp=xp...
TestBlackmanHarris
python
spyder-ide__spyder
spyder/api/plugins/new_api.py
{ "start": 1412, "end": 32327 }
class ____(QObject, SpyderActionMixin, SpyderConfigurationObserver, SpyderPluginObserver): """ A Spyder plugin to extend functionality without a dockable widget. If you want to create a plugin that adds a new pane, please use SpyderDockablePlugin. """ # --- API: Mandatory ...
SpyderPluginV2
python
doocs__leetcode
solution/2500-2599/2547.Minimum Cost to Split an Array/Solution.py
{ "start": 0, "end": 561 }
class ____: def minCost(self, nums: List[int], k: int) -> int: @cache def dfs(i): if i >= n: return 0 cnt = Counter() one = 0 ans = inf for j in range(i, n): cnt[nums[j]] += 1 if cnt[nums[j]] ...
Solution
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-wordlift/llama_index/readers/wordlift/base.py
{ "start": 389, "end": 596 }
class ____(WordLiftLoaderError): """Exception raised for errors in API calls.""" def __init__(self, message) -> None: self.message = message super().__init__(self.message)
APICallError
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_early_stopping.py
{ "start": 19680, "end": 20012 }
class ____(BoringModel): def __init__(self): super().__init__() self.epoch_losses = [1.0, 2.0, 5.0, 10.0] def on_validation_epoch_end(self): loss = self.epoch_losses[self.current_epoch] if self.current_epoch < len(self.epoch_losses) else 15.0 self.log("val_loss", loss)
ModelWithIncreasingLoss
python
bokeh__bokeh
src/bokeh/models/filters.py
{ "start": 1811, "end": 2640 }
class ____(Model): ''' A Filter model represents a filtering operation that returns a row-wise subset of data when applied to a ``ColumnDataSource``. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ...
Filter
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 263050, "end": 263776 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("CreatedPullRequestReviewContributionEdge"), graphql_name=...
CreatedPullRequestReviewContributionConnection
python
tensorflow__tensorflow
tensorflow/python/framework/device_spec.py
{ "start": 13870, "end": 15863 }
class ____(DeviceSpecV2): __doc__ = DeviceSpecV2.__doc__ __slots__ = DeviceSpecV2.__slots__ @DeviceSpecV2.job.setter def job(self, job): self._job = _as_str_or_none(job) self._as_string, self._hash = None, None @DeviceSpecV2.replica.setter def replica(self, replica): self._replica = _as_int_or...
DeviceSpecV1
python
catalyst-team__catalyst
catalyst/callbacks/metrics/confusion_matrix.py
{ "start": 429, "end": 5284 }
class ____(Callback): """Callback to plot your confusion matrix to the loggers. Args: input_key: key to use from ``runner.batch``, specifies our ``y_pred`` target_key: key to use from ``runner.batch``, specifies our ``y_true`` prefix: plot name for monitoring tools class_names: ...
ConfusionMatrixCallback
python
pydata__xarray
xarray/core/dataarray.py
{ "start": 8159, "end": 292484 }
class ____( AbstractArray, DataWithCoords, DataArrayArithmetic, DataArrayAggregations, ): """N-dimensional array with labeled coordinates and dimensions. DataArray provides a wrapper around numpy ndarrays that uses labeled dimensions and coordinates to support metadata aware operations....
DataArray
python
dask__dask
dask/array/_array_expr/_rechunk.py
{ "start": 442, "end": 2605 }
class ____(ArrayExpr): _parameters = [ "array", "_chunks", "threshold", "block_size_limit", "balance", "method", ] _defaults = { "_chunks": "auto", "threshold": None, "block_size_limit": None, "balance": None, "method":...
Rechunk
python
psf__black
gallery/gallery.py
{ "start": 781, "end": 9065 }
class ____(NamedTuple): version: str config: str | None = None def get_pypi_download_url(package: str, version: str | None) -> str: with urlopen(PYPI_INSTANCE + f"/{package}/json") as page: metadata = json.load(page) if version is None: sources = metadata["urls"] else: if ...
BlackVersion
python
PrefectHQ__prefect
src/prefect/server/events/schemas/events.py
{ "start": 11561, "end": 12137 }
class ____(PrefectBaseModel): """The count of events with the given filter value""" value: str = Field(..., description="The value to use for filtering") label: str = Field(..., description="The value to display for this count") count: int = Field(..., description="The count of matching events") st...
EventCount
python
django__django
tests/forms_tests/tests/test_forms.py
{ "start": 232853, "end": 233051 }
class ____(DjangoTemplates): bound_field_class = BoundFieldWithoutColon @override_settings( FORM_RENDERER="forms_tests.tests.test_forms.BoundFieldOverrideRenderer" )
BoundFieldOverrideRenderer
python
getsentry__sentry
tests/sentry/integrations/slack/webhooks/commands/test_link_team.py
{ "start": 5161, "end": 8118 }
class ____(SlackCommandsLinkTeamTestBase): def setUp(self) -> None: super().setUp() self.link_team() @responses.activate @patch("sentry.integrations.utils.metrics.EventLifecycle.record_event") def test_unlink_team(self, mock_record: MagicMock) -> None: data = self.send_slack_mes...
SlackCommandsUnlinkTeamTest
python
davidhalter__jedi
jedi/api/completion.py
{ "start": 1003, "end": 4385 }
class ____(ParamNameWrapper): def get_public_name(self): return self.string_name + '=' def _get_signature_param_names(signatures, positional_count, used_kwargs): # Add named params for call_sig in signatures: for i, p in enumerate(call_sig.params): kind = p.kind if ...
ParamNameWithEquals
python
ansible__ansible
test/lib/ansible_test/_internal/host_profiles.py
{ "start": 7536, "end": 13858 }
class ____[THostConfig: HostConfig](HostProfile[THostConfig], DebuggerProfile, metaclass=abc.ABCMeta): """Base class for profiles remote debugging.""" __DEBUGGING_PORT_KEY = 'debugging_port' __DEBUGGING_FORWARDER_KEY = 'debugging_forwarder' @property def debugger(self) -> DebuggerSettings | None: ...
DebuggableProfile
python
gevent__gevent
src/greentest/3.13/test_queue.py
{ "start": 22138, "end": 22224 }
class ____(QueueTest, unittest.TestCase): queue = py_queue @need_c_queue
PyQueueTest
python
Pylons__pyramid
tests/test_view.py
{ "start": 16218, "end": 25523 }
class ____(unittest.TestCase): def setUp(self): testing.setUp() def tearDown(self): testing.tearDown() def _getTargetClass(self): from pyramid.view import view_config return view_config def _makeOne(self, *arg, **kw): return self._getTargetClass()(*arg, **kw) ...
TestViewConfigDecorator
python
davidhalter__jedi
jedi/inference/value/iterable.py
{ "start": 8521, "end": 8597 }
class ____(_BaseComprehension, GeneratorBase): pass
GeneratorComprehension
python
numba__numba
numba/core/codegen.py
{ "start": 2393, "end": 22372 }
class ____(object): """ Wraps the CFG graph for different display method. Instance of the class can be stringified (``__repr__`` is defined) to get the graph in DOT format. The ``.display()`` method plots the graph in PDF. If in IPython notebook, the returned image can be inlined. """ def...
_CFG
python
xlwings__xlwings
xlwings/constants.py
{ "start": 63353, "end": 63838 }
class ____: xlButtonControl = 0 # from enum XlFormControl xlCheckBox = 1 # from enum XlFormControl xlDropDown = 2 # from enum XlFormControl xlEditBox = 3 # from enum XlFormControl xlGroupBox = 4 # from enum XlFormControl xlLabel = 5 # from enum XlFormControl xlListBox = 6 # from enum ...
FormControl
python
numpy__numpy
numpy/f2py/tests/test_string.py
{ "start": 518, "end": 979 }
class ____(util.F2PyTest): sources = [util.getpath("tests", "src", "string", "string.f")] def test_example(self): a = np.array(b"123\0\0") b = np.array(b"123\0\0") c = np.array(b"123") d = np.array(b"123") self.module.foo(a, b, c, d) assert a.tobytes() == b"123...
TestDocStringArguments
python
sympy__sympy
sympy/polys/matrices/exceptions.py
{ "start": 725, "end": 818 }
class ____(DMError): """The matrix in not invertible""" pass
DMNonInvertibleMatrixError
python
realpython__materials
python-tic-tac-toe-game-tkinter/source_code_final/tic_tac_toe.py
{ "start": 163, "end": 221 }
class ____(NamedTuple): label: str color: str
Player
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 3992, "end": 4198 }
class ____(graphene.ObjectType): assetKey = graphene.NonNull(GrapheneAssetKey) class Meta: interfaces = (GrapheneMetadataEntry,) name = "AssetMetadataEntry"
GrapheneAssetMetadataEntry
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py
{ "start": 3036, "end": 5319 }
class ____(transformer.Base): """AST visitor that annotates each symbol name with its reaching definitions. Simultaneously, the visitor runs the dataflow analysis on each function node, accounting for the effect of closures. For example: def foo(): def f(): pass def g(): # `def f...
TreeAnnotator
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 15819, "end": 17404 }
class ____(AliasedConfigModel): endpoints: list[EndpointConfig] routes: list[TrafficRouteConfig] | None = None def _load_gateway_config(path: str | Path) -> GatewayConfig: """ Reads the gateway configuration yaml file from the storage location and returns an instance of the configuration RouteConf...
GatewayConfig
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_frozen.py
{ "start": 825, "end": 11095 }
class ____(FSDPTest): @property def world_size(self) -> int: return min(4, torch.get_device_module(device_type).device_count()) @skip_if_lt_x_gpu(2) def test_train_mixed_requires_grad_per_group(self): """ Tests training parity with DDP when mixing frozen and non-frozen p...
TestFullyShardFrozen
python
huggingface__transformers
tests/models/dac/test_modeling_dac.py
{ "start": 1340, "end": 4292 }
class ____: # Ignore copy def __init__( self, parent, batch_size=3, num_channels=1, is_training=False, intermediate_size=1024, encoder_hidden_size=16, downsampling_ratios=[2, 4, 4], decoder_hidden_size=16, n_codebooks=6, cod...
DacModelTester
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 41275, "end": 46046 }
class ____(NonStrictDataModel): """ :param cls: Augmentation class (see global definitions) :type cls: str :param type: Augmentation type (see global definitions) :type type: str :param trans_mat: Transform matrix (list of lists). Required for affine transforms. :type trans_mat: Sequ...
Augmentation
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/preview.py
{ "start": 441, "end": 1682 }
class ____: """Black's `Preview.no_blank_line_before_class_docstring`""" def f(): """Black's `Preview.prefer_splitting_right_hand_side_of_assignments`""" aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[ bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb ] = cccccccc.ccccccccccccc.cccccccc aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
RemoveNewlineBeforeClassDocstring
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 37661, "end": 40727 }
class ____: @pytest.mark.parametrize("persist_result", [True, False]) def test_persist_result_set_to_bool(self, persist_result): @task(persist_result=persist_result) def my_task(): pass @task def base(): pass new_task = base.with_options(persist_...
TestResultPersistence
python
networkx__networkx
networkx/readwrite/json_graph/tests/test_adjacency.py
{ "start": 178, "end": 2456 }
class ____: def test_graph(self): G = nx.path_graph(4) H = adjacency_graph(adjacency_data(G)) assert graphs_equal(G, H) def test_graph_attributes(self): G = nx.path_graph(4) G.add_node(1, color="red") G.add_edge(1, 2, width=7) G.graph["foo"] = "bar" ...
TestAdjacency
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 156955, "end": 177818 }
class ____(_RangeTests): def _step_value_up(self, value): """given a value, return a step up this is a value that given the lower end of the sample range, would be less than the upper value of the range """ raise NotImplementedError() def _step_value_down(self, value):...
_RangeComparisonFixtures
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 300967, "end": 301714 }
class ____: def test_sf_tail(self): # Expected value computed with mpmath: # import mpmath # mpmath.mp.dps = 80 # x = mpmath.mpf(800.0) # c = mpmath.mpf(2.5) # s = float(1 - mpmath.ncdf(1/c * (mpmath.sqrt(x) # ...
TestFatigueLife
python
walkccc__LeetCode
solutions/443. String Compression/443.py
{ "start": 0, "end": 387 }
class ____: def compress(self, chars: list[str]) -> int: ans = 0 i = 0 while i < len(chars): letter = chars[i] count = 0 while i < len(chars) and chars[i] == letter: count += 1 i += 1 chars[ans] = letter ans += 1 if count > 1: for c in str(count...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-deepset/destination_deepset/models.py
{ "start": 2403, "end": 3711 }
class ____(BaseModel): name: str = Field(title="Name", description="File Name") content: bytes | str = Field(title="Content", description="File Content") meta: dict[str, Any] = Field(default_factory={}, title="Meta Data", description="File Meta Data") @property def meta_as_string(self) -> str: ...
DeepsetCloudFile
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 10241, "end": 10667 }
class ____(resource.Resource): """Return a response with a Set-Cookie header for each request url parameter""" def render(self, request): for cookie_name, cookie_values in request.args.items(): for cookie_value in cookie_values: cookie = (cookie_name.decode() + "=" + cookie_...
SetCookie
python
pytorch__pytorch
torch/nn/utils/_named_member_accessor.py
{ "start": 3796, "end": 14210 }
class ____: """ A class that provides a way to access the submodules and parameters/buffers of a module. It provides caching mechanism to speed up submodule lookups. This is useful for functional programming to manipulate the module state. """ def __init__(self, module: "torch.nn.Module") -> N...
NamedMemberAccessor
python
lazyprogrammer__machine_learning_examples
ab_testing/server_starter.py
{ "start": 605, "end": 1306 }
class ____: def __init__(self, name): self.name = name def sample(self): # TODO return 1 # TODO - what else does the Bandit need to do? # initialize bandits banditA = Bandit('A') banditB = Bandit('B') @app.route('/get_ad') def get_ad(): # TODO return jsonify({'advertisement_id': 'A'}) @ap...
Bandit
python
weaviate__weaviate-python-client
weaviate/client.py
{ "start": 957, "end": 4689 }
class ____(_WeaviateClientExecutor[ConnectionAsync]): """The v4 Python-native Weaviate Client class that encapsulates Weaviate functionalities in one object. WARNING: This client is only compatible with Weaviate v1.23.6 and higher! A Client instance creates all the needed objects to interact with Weaviate...
WeaviateAsyncClient
python
django-mptt__django-mptt
tests/myapp/models.py
{ "start": 298, "end": 378 }
class ____(QuerySet): def custom_method(self): pass
CustomTreeQueryset
python
doocs__leetcode
solution/1700-1799/1718.Construct the Lexicographically Largest Valid Sequence/Solution.py
{ "start": 0, "end": 846 }
class ____: def constructDistancedSequence(self, n: int) -> List[int]: def dfs(u): if u == n * 2: return True if path[u]: return dfs(u + 1) for i in range(n, 1, -1): if cnt[i] and u + i < n * 2 and path[u + i] == 0: ...
Solution
python
altair-viz__altair
tools/generate_schema_wrapper.py
{ "start": 15323, "end": 15714 }
class ____(SchemaGenerator): schema_class_template = textwrap.dedent( ''' @with_property_setters class {classname}(ValueChannelMixin, core.{basename}): """{docstring}""" _class_is_valid_at_instantiation = False _encoding_name = "{encodingname}" {method_code} ...
ValueSchemaGenerator
python
pennersr__django-allauth
allauth/socialaccount/providers/openid_connect/provider.py
{ "start": 894, "end": 1047 }
class ____(ProviderAccount): def get_user_data(self) -> Optional[Dict]: return _pick_data(self.account.extra_data)
OpenIDConnectProviderAccount
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/newType1.py
{ "start": 1277, "end": 1982 }
class ____(TypedDict): x: int # This should generate an error because type cannot be a TypedDict. NewTypeBad7 = NewType("NewTypeBad7", TD1) NewTypeGood8 = NewType("NewTypeGood8", MyString) # This should generate an error because the name doesn't match. NewTypeBad9 = NewType("NewTypeBad9Not", int) def func2(x:...
TD1
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/static_methods.py
{ "start": 228, "end": 415 }
class ____: @staticmethod def sink(oops): _test_sink(oops) def test(source): return StaticClass.sink(source) def run_test(source): test(_test_source())
StaticClass
python
aimacode__aima-python
learning4e.py
{ "start": 29412, "end": 30538 }
class ____: """Given a list of learning algorithms, have them vote.""" def __init__(self, learners): self.learners = learners def train(self, dataset): self.predictors = [learner(dataset) for learner in self.learners] def predict(self, example): return mode(predictor.predict(e...
EnsembleLearner
python
google__pytype
pytype/test_data/pytree.py
{ "start": 1295, "end": 8429 }
class ____: """Abstract base class for Node and Leaf. This provides some default functionality and boilerplate using the template pattern. A node may be a subnode of at most one parent. Each subclass of Base must provide a __str__ implementation that returns exactly the input that was used to create the ...
Base
python
pandas-dev__pandas
pandas/tests/series/indexing/test_setitem.py
{ "start": 42844, "end": 43216 }
class ____(CoercionTest): @pytest.fixture def obj(self): return Series(["a", "b", "c", "d"], dtype=StringDtype(na_value=np.nan)) @pytest.mark.parametrize( "val,exp_dtype,raises", [ (1, np.complex128, False), (1.1, np.complex128, False), (1 + 1j, np.complex128, False), ...
TestCoercionString
python
PrefectHQ__prefect
src/integrations/prefect-aws/prefect_aws/observers/ecs.py
{ "start": 4628, "end": 8664 }
class ____: def __init__(self, queue_name: str, queue_region: str | None = None): self.queue_name = queue_name self.queue_region = queue_region async def stream_messages( self, ) -> AsyncGenerator["MessageTypeDef", None]: session = aiobotocore.session.get_session() a...
SqsSubscriber
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/cloud/credentials.py
{ "start": 330, "end": 6315 }
class ____(CredentialsBlock): """ Credentials block for credential use across dbt Cloud tasks and flows. Attributes: api_key (SecretStr): API key to authenticate with the dbt Cloud administrative API. Refer to the [Authentication docs]( https://docs.getdbt.com/dbt-cloud/api-...
DbtCloudCredentials
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 87817, "end": 88258 }
class ____(sgqlc.types.Enum): """Possible directions in which to order a list of repository migrations when provided an `orderBy` argument. Enumeration Choices: * `ASC`: Specifies an ascending order for a given `orderBy` argument. * `DESC`: Specifies a descending order for a given `orderBy` ...
RepositoryMigrationOrderDirection
python
protocolbuffers__protobuf
python/google/protobuf/descriptor.py
{ "start": 36600, "end": 39594 }
class ____(_NestedDescriptorBase): """Descriptor for a service. Attributes: name (str): Name of the service. full_name (str): Full name of the service, including package name. index (int): 0-indexed index giving the order that this services definition appears within the .proto file. methods (...
ServiceDescriptor
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 3824, "end": 3989 }
class ____(graphene.ObjectType): class Meta: interfaces = (GrapheneMessageEvent, GrapheneRunEvent) name = "RunSuccessEvent"
GrapheneRunSuccessEvent
python
readthedocs__readthedocs.org
readthedocs/core/models.py
{ "start": 394, "end": 1554 }
class ____(TimeStampedModel): """Additional information about a User.""" user = AutoOneToOneField( User, verbose_name=_("User"), related_name="profile", on_delete=models.CASCADE, ) # Shown on the users profile homepage = models.CharField(_("Homepage"), max_length=100...
UserProfile
python
doocs__leetcode
solution/1100-1199/1150.Check If a Number Is Majority Element in a Sorted Array/Solution.py
{ "start": 0, "end": 216 }
class ____: def isMajorityElement(self, nums: List[int], target: int) -> bool: left = bisect_left(nums, target) right = bisect_right(nums, target) return right - left > len(nums) // 2
Solution
python
django__django
django/urls/resolvers.py
{ "start": 4130, "end": 5199 }
class ____: def __get__(self, instance, cls=None): """ Return a compiled regular expression based on the active language. """ if instance is None: return self # As a performance optimization, if the given regex string is a regular # string (not a lazily-tr...
LocaleRegexDescriptor
python
huggingface__transformers
src/transformers/models/bert_generation/modeling_bert_generation.py
{ "start": 25988, "end": 26468 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.decoder = nn.Linear(config.hidden_size, config.vocab_size) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) def forward(self, hidden_states): logits = self.decoder(hidden_states) return lo...
BertGenerationOnlyLMHead
python
anthropics__anthropic-sdk-python
src/anthropic/types/web_search_result_block_param.py
{ "start": 253, "end": 476 }
class ____(TypedDict, total=False): encrypted_content: Required[str] title: Required[str] type: Required[Literal["web_search_result"]] url: Required[str] page_age: Optional[str]
WebSearchResultBlockParam
python
joke2k__faker
faker/providers/phone_number/el_GR/__init__.py
{ "start": 49, "end": 523 }
class ____(PhoneNumberProvider): formats = ( "69########", "69## ######", "69## ### ###", "210#######", "210 #######", "210 ### ####", "2##0######", "2##0 ######", "2##0 ### ###", "2###0#####", "2###0 ## ###", "(+30) 69#...
Provider
python
huggingface__transformers
src/transformers/models/xlm_roberta/modular_xlm_roberta.py
{ "start": 1652, "end": 1830 }
class ____(RobertaModel): pass @auto_docstring( custom_intro=""" XLM-RoBERTa Model with a `language modeling` head on top for CLM fine-tuning. """ )
XLMRobertaModel
python
PyCQA__pydocstyle
src/pydocstyle/parser.py
{ "start": 599, "end": 976 }
class ____(ParseError): def __init__(self, token, expected_kind): self.token = token self.expected_kind = expected_kind def __str__(self): return "Unexpected token {}, expected {}".format( self.token, self.expected_kind ) def humanize(string): return re(r'(.)([...
UnexpectedTokenError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/single_string_slots.py
{ "start": 390, "end": 547 }
class ____: __slots__: tuple[str, ...] = ("bar",) def __init__(self, bar): self.bar = bar # This is a type error, out of scope for the rule
Foo
python
MongoEngine__mongoengine
tests/fixtures.py
{ "start": 1465, "end": 1505 }
class ____: name = StringField()
Mixin
python
wandb__wandb
wandb/sdk/artifacts/_generated/fetch_linked_artifacts.py
{ "start": 284, "end": 378 }
class ____(GQLResult): artifact: Optional[FetchLinkedArtifactsArtifact]
FetchLinkedArtifacts
python
google__jax
docs/autodidax.py
{ "start": 32311, "end": 32434 }
class ____(NamedTuple): primitive: Primitive inputs: list[Atom] params: dict[str, Any] out_binders: list[Var]
JaxprEqn
python
tox-dev__tox
src/tox/tox_env/python/virtual_env/package/pyproject.py
{ "start": 17281, "end": 17506 }
class ____(Pep517VenvPackager, VirtualEnv): """local file system python virtual environment via the virtualenv package.""" @staticmethod def id() -> str: return "virtualenv-pep-517"
Pep517VirtualEnvPackager
python
realpython__materials
python-isinstance/balls_v2.py
{ "start": 208, "end": 481 }
class ____(Ball): def __init__(self, color, number): super().__init__(color, shape="sphere") self.number = number def get_state(self): print( f"Color = {self.color}, Number = {self.number}, Shape = {self.shape}" )
PoolBall
python
matplotlib__matplotlib
lib/matplotlib/colors.py
{ "start": 97231, "end": 108376 }
class ____(Normalize): def __init__(self, vcenter=0, halfrange=None, clip=False): """ Normalize symmetrical data around a center (0 by default). Unlike `TwoSlopeNorm`, `CenteredNorm` applies an equal rate of change around the center. Useful when mapping symmetrical data aro...
CenteredNorm
python
ray-project__ray
python/ray/tune/tests/test_trial_scheduler.py
{ "start": 8370, "end": 10403 }
class ____: def __init__(self, scheduler): self._scheduler_alg = scheduler self.search_alg = None self.trials = [] def process_action(self, trial, action): if action == TrialScheduler.CONTINUE: pass elif action == TrialScheduler.PAUSE: self.pause_...
_MockTrialRunner
python
django__django
tests/template_tests/filter_tests/test_truncatechars_html.py
{ "start": 103, "end": 1495 }
class ____(SimpleTestCase): def test_truncate_zero(self): self.assertEqual( truncatechars_html( '<p>one <a href="#">two - three <br>four</a> five</p>', 0 ), "", ) def test_truncate(self): self.assertEqual( truncatechars_htm...
FunctionTests
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py
{ "start": 507, "end": 582 }
class ____: for _ in ...: def __eq__(self, other): ...
MaybeEqFor
python
huggingface__transformers
src/transformers/models/xlm/modeling_xlm.py
{ "start": 8918, "end": 11712 }
class ____(nn.Module): """ Compute SQuAD 2.0 answer class from classification and start tokens hidden states. Args: config ([`XLMConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model. """ def __init__(self, config: XLMConfig): supe...
XLMPoolerAnswerClass
python
mamba-org__mamba
docs/source/tools/mermaid_inheritance.py
{ "start": 1657, "end": 4464 }
class ____(InheritanceGraph): """ Given a list of classes, determines the set of classes that they inherit from all the way to the root "object", and then is able to generate a mermaid graph from them. """ # These are the default attrs default_graph_attrs = {} # 'rankdir': 'LR', ...
MermaidGraph
python
PyCQA__pylint
tests/functional/u/used/used_before_assignment_typing.py
{ "start": 3781, "end": 4237 }
class ____: # pylint: disable=too-few-public-methods """Class to test conditional imports guarded by TYPE_CHECKING two levels up then used in function annotation. See https://github.com/pylint-dev/pylint/issues/7539""" def is_close(self, comparator: math.isclose, first, second): # <3.14:[used-before-assi...
MyFourthClass
python
openai__openai-python
src/openai/types/eval_create_params.py
{ "start": 6242, "end": 6371 }
class ____(PythonGraderParam, total=False): pass_threshold: float """The threshold for the score."""
TestingCriterionPython
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/descriptor_props.py
{ "start": 32181, "end": 32648 }
class ____(CompositeProperty[_T], _DeclarativeMapped[_T]): """Declarative-compatible front-end for the :class:`.CompositeProperty` class. Public constructor is the :func:`_orm.composite` function. .. versionchanged:: 2.0 Added :class:`_orm.Composite` as a Declarative compatible subclass of :cla...
Composite
python
pytorch__pytorch
torch/_dynamo/variables/dicts.py
{ "start": 40341, "end": 43573 }
class ____(ConstDictVariable): def __init__( self, items: dict[VariableTracker, VariableTracker], user_cls: type, default_factory: Optional[VariableTracker] = None, **kwargs: Any, ) -> None: super().__init__(items, user_cls, **kwargs) assert user_cls is co...
DefaultDictVariable
python
ray-project__ray
python/ray/serve/_private/router.py
{ "start": 2028, "end": 20301 }
class ____: """Manages metrics for the router.""" PUSH_METRICS_TO_CONTROLLER_TASK_NAME = "push_metrics_to_controller" RECORD_METRICS_TASK_NAME = "record_metrics" def __init__( self, deployment_id: DeploymentID, handle_id: str, self_actor_id: str, handle_source: ...
RouterMetricsManager
python
scipy__scipy
scipy/linalg/tests/test_blas.py
{ "start": 26635, "end": 27054 }
class ____: @parametrize_blas(fblas, "gemm", "sdcz") def test_gemm(self, f, dtype): assert_array_almost_equal(f(3, [3], [-4]), [[-36]]) assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21]) if dtype in COMPLEX_DTYPES: assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-3...
TestFBLAS3Simple
python
ray-project__ray
python/ray/autoscaler/v2/instance_manager/cloud_providers/kuberay/cloud_provider.py
{ "start": 1025, "end": 23378 }
class ____(ICloudInstanceProvider): """ This class is a thin wrapper around the Kubernetes API client. It modifies the RayCluster resource spec on the Kubernetes API server to scale the cluster: It launches new instances/nodes by submitting patches to the Kubernetes API to update the RayCluster CRD...
KubeRayProvider
python
pytorch__pytorch
torch/fx/passes/utils/source_matcher_utils.py
{ "start": 940, "end": 5781 }
class ____: # Nodes in a particular partition nodes: list[Node] # The source these nodes decomposed from source: Any # Nodes in the graph that are needed as inputs to the partition # These do not include the params of the partition input_nodes: list[Node] = field(default_factory=list) ...
SourcePartition
python
huggingface__transformers
src/transformers/models/vits/modeling_vits.py
{ "start": 54073, "end": 61536 }
class ____(VitsPreTrainedModel): def __init__(self, config: VitsConfig): super().__init__(config) self.config = config self.text_encoder = VitsTextEncoder(config) self.flow = VitsResidualCouplingBlock(config) self.decoder = VitsHifiGan(config) if config.use_stochasti...
VitsModel
python
scikit-image__scikit-image
tests/skimage/morphology/test_extrema.py
{ "start": 11380, "end": 26972 }
class ____(unittest.TestCase): """Some tests for local_minima are included as well.""" supported_dtypes = [ np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64, np.float32, np.float64, ] image =...
TestLocalMaxima
python
getsentry__sentry
src/sentry/uptime/migrations/0045_backfill_detector_thresholds.py
{ "start": 1686, "end": 2253 }
class ____(CheckedMigration): # This is a data migration that can take a while on large deployments # and should be run manually after code deployment is_post_deployment = True dependencies = [ ("uptime", "0044_remove_project_uptime_subscription"), ("workflow_engine", "0085_crons_link_d...
Migration
python
facebookresearch__faiss
tests/test_graph_based.py
{ "start": 372, "end": 6926 }
class ____(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) d = 32 nt = 0 nb = 1500 nq = 500 (_, self.xb, self.xq) = get_dataset_2(d, nt, nb, nq) index = faiss.IndexFlatL2(d) index.add(self.xb...
TestHNSW
python
numba__numba
numba/core/pythonapi.py
{ "start": 3084, "end": 4971 }
class ____(object): def __init__(self, pyapi, env, env_body, env_ptr): assert isinstance(env, lowering.Environment) self.pyapi = pyapi self.env = env self.env_body = env_body self.env_ptr = env_ptr def add_const(self, const): """ Add a constant to the en...
EnvironmentManager
python
Textualize__textual
docs/examples/guide/dom2.py
{ "start": 88, "end": 263 }
class ____(App): def compose(self) -> ComposeResult: yield Header() yield Footer() if __name__ == "__main__": app = ExampleApp() app.run()
ExampleApp
python
walkccc__LeetCode
solutions/3210. Find the Encrypted String/3210.py
{ "start": 0, "end": 113 }
class ____: def getEncryptedString(self, s: str, k: int) -> str: k %= len(s) return s[k:] + s[0:k]
Solution
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 98357, "end": 99976 }
class ____(Mean): """Computes root mean squared error metric between `y_true` and `y_pred`. Standalone usage: >>> m = tf.keras.metrics.RootMeanSquaredError() >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) >>> m.result().numpy() 0.5 >>> m.reset_state() >>> m.update_state([[0, 1], [0, 0]], [[1,...
RootMeanSquaredError
python
google__pytype
pytype/tests/test_test_code.py
{ "start": 3349, "end": 4350 }
class ____(test_base.BaseTest): """Tests for unittest.mock.""" def test_patch(self): self.Check(""" import unittest from unittest import mock foo = __any_object__ bar = __any_object__ class Foo(unittest.TestCase): def setUp(self): super().setUp() self.s...
MockTest