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 | aio-libs__aiohttp | aiohttp/web_app.py | {
"start": 1841,
"end": 12458
} | class ____(MutableMapping[str | AppKey[Any], Any]):
__slots__ = (
"logger",
"_router",
"_loop",
"_handler_args",
"_middlewares",
"_middlewares_handlers",
"_run_middlewares",
"_state",
"_frozen",
"_pre_frozen",
"_subapps",
... | Application |
python | spack__spack | lib/spack/spack/error.py | {
"start": 3580,
"end": 3684
} | class ____(SpackError):
"""Superclass for all errors that occur while constructing specs."""
| SpecError |
python | spack__spack | lib/spack/spack/tokenize.py | {
"start": 433,
"end": 797
} | class ____(enum.Enum):
"""Base class for an enum type with a regex value"""
def __new__(cls, *args, **kwargs):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
def __init__(self, regex):
self.regex = regex
def __str__(se... | TokenBase |
python | huggingface__transformers | src/transformers/models/sam2/processing_sam2.py | {
"start": 1080,
"end": 23047
} | class ____(ProcessorMixin):
r"""
Constructs a SAM2 processor which wraps a SAM2 image processor and an 2D points & Bounding boxes processor into a
single processor.
[`Sam2Processor`] offers all the functionalities of [`Sam2ImageProcessorFast`] and [`Sam2VideoProcessor`]. See the docstring of
[`~Sam... | Sam2Processor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchLiteral2.py | {
"start": 171,
"end": 218
} | class ____:
tag: Literal["a"]
name: str
| A |
python | pdm-project__pdm | src/pdm/resolver/providers.py | {
"start": 16559,
"end": 19793
} | class ____(BaseProvider):
"""A provider that reuses preferred pins if possible.
This is used to implement "add", "remove", and "reuse upgrade",
where already-pinned candidates in lockfile should be preferred.
"""
def __init__(
self,
repository: BaseRepository,
allow_prerele... | ReusePinProvider |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 14419,
"end": 14833
} | class ____(ChainedSource):
member: str = "grad"
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen(self.base)
codegen.extend_output(codegen.create_load_attrs(self.member))
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
... | GradSource |
python | viewflow__viewflow | tests/json/test_json__char.py | {
"start": 95,
"end": 302
} | class ____(models.Model):
data = models.JSONField(default=dict)
char_field = jsonstore.CharField(max_length=250, blank=True)
required_char_field = jsonstore.CharField(max_length=250)
| CharFieldModel |
python | scikit-learn__scikit-learn | sklearn/tree/_export.py | {
"start": 20397,
"end": 40933
} | class ____(_BaseTreeExporter):
def __init__(
self,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
impurity=True,
node_ids=False,
proportion=False,
rounded=False,
precision=3,
fontsize=No... | _MPLTreeExporter |
python | ray-project__ray | python/ray/data/_internal/datasource/mongo_datasource.py | {
"start": 270,
"end": 4780
} | class ____(Datasource):
"""Datasource for reading from and writing to MongoDB."""
def __init__(
self,
uri: str,
database: str,
collection: str,
pipeline: Optional[List[Dict]] = None,
schema: Optional["pymongoarrow.api.Schema"] = None,
**mongo_args,
):... | MongoDatasource |
python | matplotlib__matplotlib | galleries/examples/text_labels_and_annotations/angle_annotation.py | {
"start": 3139,
"end": 13120
} | class ____(Arc):
"""
Draws an arc between two vectors which appears circular in display space.
"""
def __init__(self, xy, p1, p2, size=75, unit="points", ax=None,
text="", textposition="inside", text_kw=None, **kwargs):
"""
Parameters
----------
xy, p1, p... | AngleAnnotation |
python | numba__numba | numba/core/callconv.py | {
"start": 36473,
"end": 36635
} | class ____(ErrorModel):
"""
The Python error model. Any invalid FP input raises an exception.
"""
raise_on_fp_zero_division = True
| PythonErrorModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 11463,
"end": 13725
} | class ____(NamedTuple):
"""represents state to use when producing "expanded" and
"post compile" bound parameters for a statement.
"expanded" parameters are parameters that are generated at
statement execution time to suit a number of parameters passed, the most
prominent example being the individua... | ExpandedState |
python | getsentry__sentry | src/sentry/services/organization/model.py | {
"start": 256,
"end": 487
} | class ____(pydantic.BaseModel):
sentry_options: Any | None = None # Placeholder for any sentry post-provisioning data
getsentry_options: Any | None = None # Reserved for getsentry post-provisioning data
| PostProvisionOptions |
python | bokeh__bokeh | src/bokeh/core/property/singletons.py | {
"start": 1837,
"end": 2479
} | class ____:
""" Indicates usage of the intrinsic default value of a property. """
def __copy__(self) -> IntrinsicType:
return self
def __str__(self) -> str:
return "Intrinsic"
def __repr__(self) -> str:
return "Intrinsic"
Intrinsic = IntrinsicType()
#------------------------... | IntrinsicType |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-array-equal-to-target.py | {
"start": 46,
"end": 424
} | class ____(object):
def minimumOperations(self, nums, target):
"""
:type nums: List[int]
:type target: List[int]
:rtype: int
"""
for i in xrange(len(target)):
target[i] -= nums[i]
return sum(max((target[i] if i < len(target) else 0)-(target[i-1] if... | Solution |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/freebsd.py | {
"start": 978,
"end": 9910
} | class ____(Hardware):
"""
FreeBSD-specific subclass of Hardware. Defines memory and CPU facts:
- memfree_mb
- memtotal_mb
- swapfree_mb
- swaptotal_mb
- processor (a list)
- processor_cores
- processor_count
- devices
- uptime_seconds
"""
platform = 'FreeBSD'
DME... | FreeBSDHardware |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 22332,
"end": 23503
} | class ____:
def my_handler(self, message):
self.message = ["my handler", message]
def test_push_handler(self, r):
if is_resp2_connection(r):
return
p = r.pubsub(push_handler_func=self.my_handler)
p.subscribe("foo")
assert wait_for_message(p) is None
a... | TestPubSubRESP3Handler |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_index.py | {
"start": 5828,
"end": 14491
} | class ____(OrganizationIndexTest, HybridCloudTestMixin):
method = "post"
def test_missing_params(self) -> None:
self.get_error_response(status_code=400)
def test_valid_params(self) -> None:
data = {"name": "hello world", "slug": "foobar"}
response = self.get_success_response(**data... | OrganizationsCreateTest |
python | dask__distributed | distributed/comm/ws.py | {
"start": 14737,
"end": 14903
} | class ____(BaseTCPBackend):
_connector_class = WSSConnector
_listener_class = WSSListener
backends["ws"] = WSBackend()
backends["wss"] = WSSBackend()
| WSSBackend |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/external_data.py | {
"start": 24022,
"end": 24206
} | class ____:
name: str
ResourceValueSnap: TypeAlias = Union[str, ResourceConfigEnvVarSnap]
UNKNOWN_RESOURCE_TYPE = "Unknown"
@whitelist_for_serdes
@record
| ResourceConfigEnvVarSnap |
python | getsentry__sentry | tests/sentry/seer/endpoints/test_group_autofix_setup_check.py | {
"start": 638,
"end": 3304
} | class ____(TestCase):
def test_missing_integration(self) -> None:
result = get_autofix_integration_setup_problems(
organization=self.organization, project=self.project
)
assert result == "integration_missing"
def test_supported_github_integration(self) -> None:
self... | GetAutofixIntegrationSetupProblemsTestCase |
python | numba__numba | numba/np/ufunc/wrappers.py | {
"start": 21816,
"end": 24350
} | class ____(object):
def __init__(self, context, builder, args, steps, i, step_offset,
typ, syms, sym_dim):
self.context = context
self.builder = builder
offset = context.get_constant(types.intp, i)
data = builder.load(builder.gep(args, [offset], name="data.ptr"),
... | GUArrayArg |
python | python-openxml__python-docx | src/docx/opc/package.py | {
"start": 747,
"end": 6979
} | class ____:
"""Main API class for |python-opc|.
A new instance is constructed by calling the :meth:`open` class method with a path
to a package file or file-like object containing one.
"""
def after_unmarshal(self):
"""Entry point for any post-unmarshaling processing.
May be overr... | OpcPackage |
python | gevent__gevent | src/gevent/resolver/ares.py | {
"start": 967,
"end": 12965
} | class ____(AbstractResolver):
"""
Implementation of the resolver API using the `c-ares`_ library.
This implementation uses the c-ares library to handle name
resolution. c-ares is natively asynchronous at the socket level
and so integrates well into gevent's event loop.
In comparison to :class:... | Resolver |
python | matplotlib__matplotlib | lib/mpl_toolkits/mplot3d/axis3d.py | {
"start": 1084,
"end": 28516
} | class ____(maxis.XAxis):
"""An Axis class for the 3D plots."""
# These points from the unit cube make up the x, y and z-planes
_PLANES = (
(0, 3, 7, 4), (1, 2, 6, 5), # yz planes
(0, 1, 5, 4), (3, 2, 6, 7), # xz planes
(0, 1, 2, 3), (4, 5, 6, 7), # xy planes
)
# Some prop... | Axis |
python | pypa__virtualenv | src/virtualenv/app_data/via_tempdir.py | {
"start": 214,
"end": 811
} | class ____(AppDataDiskFolder):
transient = True
can_update = False
def __init__(self) -> None:
super().__init__(folder=mkdtemp())
LOGGER.debug("created temporary app data folder %s", self.lock.path)
def reset(self):
"""This is a temporary folder, is already empty to start with.... | TempAppData |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol7.py | {
"start": 419,
"end": 500
} | class ____(Protocol):
def __call__(self, x: int, /, *args: *tuple[int]): ...
| P3 |
python | kubernetes-client__python | kubernetes/client/models/v1_ip_block.py | {
"start": 383,
"end": 4726
} | 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... | V1IPBlock |
python | pytorch__pytorch | benchmarks/tensorexpr/conv.py | {
"start": 2487,
"end": 2651
} | class ____(ConvImplBench):
def __init__(self, *args):
super().__init__("conv", *args)
@staticmethod
def module():
return "conv"
| ConvBench |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_boolean_trap/FBT.py | {
"start": 3745,
"end": 3929
} | class ____:
def __or__(self, other: Self | bool) -> Self: ...
def __ror__(self, other: Self | bool) -> Self: ...
def __ior__(self, other: Self | bool) -> Self: ...
| BooleanArray |
python | realpython__materials | python-class/animals.py | {
"start": 460,
"end": 537
} | class ____(Bird):
def fly(self):
print("The eagle is flying")
| Eagle |
python | django__django | tests/composite_pk/models/tenant.py | {
"start": 1388,
"end": 1593
} | class ____(models.Model):
pk = models.CompositePrimaryKey("tenant_id", "id")
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, default=1)
id = models.UUIDField(default=uuid.uuid4)
| Post |
python | bokeh__bokeh | tests/unit/bokeh/core/property/_util_property.py | {
"start": 1921,
"end": 2259
} | class ____(HasProps):
x = Int(12)
y = String("hello")
z = List(Int, default=[1, 2, 3])
zz = Dict(String, Int)
s = Nullable(String, default=None)
#-----------------------------------------------------------------------------
# Code
#-------------------------------------------------------------------... | _TestModel2 |
python | pennersr__django-allauth | allauth/socialaccount/providers/saml/views.py | {
"start": 1436,
"end": 2002
} | class ____(SAMLViewMixin, View):
def dispatch(self, request, organization_slug):
url = reverse(
"saml_finish_acs",
kwargs={"organization_slug": organization_slug},
)
response = HttpResponseRedirect(url)
acs_session = LoginSession(request, "saml_acs_session", "... | ACSView |
python | plotly__plotly.py | plotly/graph_objs/heatmap/colorbar/_tickfont.py | {
"start": 233,
"end": 9918
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "heatmap.colorbar"
_path_str = "heatmap.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Tickfont |
python | django__django | django/core/checks/registry.py | {
"start": 613,
"end": 3880
} | class ____:
def __init__(self):
self.registered_checks = set()
self.deployment_checks = set()
def register(self, check=None, *tags, **kwargs):
"""
Can be used as a function or a decorator. Register given function
`f` labeled with given `tags`. The function should receive... | CheckRegistry |
python | ray-project__ray | doc/source/rllib/doc_code/replay_buffer_demo.py | {
"start": 2187,
"end": 5573
} | class ____(ReplayBuffer):
@override(ReplayBuffer)
def sample(
self, num_items: int, evict_sampled_more_then: int = 30, **kwargs
) -> Optional[SampleBatchType]:
"""Evicts experiences that have been sampled > evict_sampled_more_then times."""
idxes = [random.randint(0, len(self) - 1) f... | LessSampledReplayBuffer |
python | huggingface__transformers | src/transformers/models/swinv2/configuration_swinv2.py | {
"start": 895,
"end": 7547
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Swinv2Model`]. It is used to instantiate a Swin
Transformer v2 model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the def... | Swinv2Config |
python | django-haystack__django-haystack | test_haystack/solr_tests/test_solr_backend.py | {
"start": 1459,
"end": 1990
} | class ____(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(
model_attr="author", faceted=True, index_fieldname="name_s"
)
pub_date = indexes.DateField(model_attr="pub_date", index_fieldname="pub_date_dt")
today = in... | SolrMockOverriddenFieldNameSearchIndex |
python | keras-team__keras | keras/src/metrics/confusion_metrics.py | {
"start": 15874,
"end": 21548
} | class ____(Metric):
"""Computes the recall of the predictions with respect to the labels.
This metric creates two local variables, `true_positives` and
`false_negatives`, that are used to compute the recall. This value is
ultimately returned as `recall`, an idempotent operation that simply divides
... | Recall |
python | sqlalchemy__sqlalchemy | test/sql/test_insert_exec.py | {
"start": 1672,
"end": 15264
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"user_id", INT, primary_key=True, test_needs_autoincrement=True
),
Column("u... | InsertExecTest |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/types.py | {
"start": 4982,
"end": 5718
} | class ____:
"""User-defined Airbyte source bound to actual created Airbyte source."""
def __init__(self, source: AirbyteSource, source_id: str, source_definition_id: Optional[str]):
self.source = source
self.source_id = source_id
self.source_definition_id = source_definition_id
@cl... | InitializedAirbyteSource |
python | getsentry__sentry | tests/sentry/integrations/tasks/test_sync_status_outbound.py | {
"start": 989,
"end": 7409
} | class ____(TestCase):
def setUp(self) -> None:
self.example_integration = self.create_integration(
organization=self.group.organization,
external_id="123456",
provider="example",
oi_params={
"config": {
"sync_comments": True... | TestSyncStatusOutbound |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/function7.py | {
"start": 191,
"end": 279
} | class ____(Protocol):
def write(self, a: str, b: str) -> object:
pass
| _Writer1 |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/mirrored_strategy_test.py | {
"start": 22337,
"end": 30039
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout.Mesh(['batch'], global_ids, local_ids,
test_util.create_device_list((... | StrategyDatasetTest |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 9379,
"end": 52566
} | class ____(nn.Module):
def __init__(self, config, seed=None):
super().__init__()
self.max_seqlen = config.max_position_embeddings
self.seed = seed
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size {config.hidden... | BigBirdBlockSparseAttention |
python | ray-project__ray | rllib/offline/tests/test_dataset_reader.py | {
"start": 320,
"end": 5445
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
# TODO(Kourosh): Hitting S3 in CI is currently broken due to some AWS
# credentials issues, using a local file instead for now.
# cls.dset_path = "s3://air-example-data/rllib/cartpole/large.json... | TestDatasetReader |
python | fastai__fastai | fastai/data/core.py | {
"start": 14815,
"end": 19553
} | class ____(FilteredBase, L, GetAttr):
"A `Pipeline` of `tfms` applied to a collection of `items`"
_default='tfms'
def __init__(self,
items:list, # Items to apply `Transform`s to
tfms:MutableSequence|Pipeline, # `Transform`(s) or `Pipeline` to apply
use_list:bool=None, # Use `list` i... | TfmdLists |
python | apache__airflow | providers/databricks/tests/unit/databricks/utils/test_mixins.py | {
"start": 2184,
"end": 4952
} | class ____:
"""
We'll provide tests for each of the following methods:
- _handle_execution
- _handle_deferrable_execution
- execute_complete
- on_kill
"""
def test_handle_execution_success(self, databricks_sql_statements, terminal_success_state):
# Test an immediate success of ... | TestDatabricksSQLStatementsMixin |
python | pytorch__pytorch | torch/_dynamo/aot_compile.py | {
"start": 9995,
"end": 10427
} | class ____:
"""
WIP type: represents a single model input
Which consists of a tuple of arguments and a set of contexts in which to run the model.
For each ModelInput, we'll compile one full graph of the model, and then use the guards generated
to dispatch between the compiled graphs.
"""
... | ModelInput |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/reconciliation.py | {
"start": 24412,
"end": 26938
} | class ____(ManagedElementReconciler):
"""Reconciles Python-specified Airbyte connections with an Airbyte instance.
Passing the module containing an AirbyteManagedElementReconciler to the dagster-airbyte
CLI will allow you to check the state of your Python-code-specified Airbyte connections
against an A... | AirbyteManagedElementReconciler |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 8391,
"end": 8475
} | class ____(Exception):
"""An error in the Capture context manager."""
| CaptureError |
python | sqlalchemy__sqlalchemy | test/orm/test_options.py | {
"start": 50329,
"end": 63894
} | class ____(_fixtures.FixtureTest):
def test_synonym_options(self):
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
self.mapper_registry.map_imperatively(
User... | MapperOptionsTest |
python | pallets__werkzeug | tests/conftest.py | {
"start": 835,
"end": 7738
} | class ____:
"""Manage a live dev server process and make requests to it. Must be used
as a context manager.
If ``hostname`` starts with ``unix://``, the server listens to a unix socket
file instead of a TCP socket.
If ``port`` is not given, a random port is reserved for use by the server,
to a... | DevServerClient |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_drawing_image01.py | {
"start": 399,
"end": 6752
} | class ____(unittest.TestCase):
"""
Test assembling a complete Drawing file.
"""
def test_assemble_xml_file(self):
"""Test writing a drawing with no cell data."""
self.maxDiff = None
fh = StringIO()
drawing = Drawing()
drawing._set_filehandle(fh)
dimens... | TestAssembleDrawing |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_api_key_details.py | {
"start": 727,
"end": 1132
} | class ____(OrganizationApiKeyDetailsBase):
def test_api_key_no_exist(self) -> None:
self.get_error_response(self.organization.slug, 123456, status_code=404)
def test_get_api_details(self) -> None:
response = self.get_success_response(self.organization.slug, self.api_key.id)
assert respo... | OrganizationApiKeyDetails |
python | django__django | django/forms/utils.py | {
"start": 1420,
"end": 1923
} | class ____:
def get_context(self):
raise NotImplementedError(
"Subclasses of RenderableMixin must provide a get_context() method."
)
def render(self, template_name=None, context=None, renderer=None):
renderer = renderer or self.renderer
template = template_name or se... | RenderableMixin |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 16580,
"end": 16720
} | class ____(TokenStreamException):
def __init__(self, *args):
TokenStreamException.__init__(self, *args)
| TokenStreamRetryException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solverHigherOrder5.py | {
"start": 2291,
"end": 5143
} | class ____(Generic[A, B]):
left: A
right: B
def func1(f: Callable[[A], B]) -> Callable[[Pair[A, X]], Pair[B, X]]: ...
def test_3(pair: Pair[Pair[A, B], C]) -> Pair[Pair[A, B], C]:
val1 = func1(func1(identity))
reveal_type(
val1,
expected_text="(Pair[Pair[T@identity, X(1)@func1], X@fu... | Pair |
python | tiangolo__fastapi | docs_src/header_param_models/tutorial002_an.py | {
"start": 158,
"end": 486
} | class ____(BaseModel):
model_config = {"extra": "forbid"}
host: str
save_data: bool
if_modified_since: Union[str, None] = None
traceparent: Union[str, None] = None
x_tag: List[str] = []
@app.get("/items/")
async def read_items(headers: Annotated[CommonHeaders, Header()]):
return headers
| CommonHeaders |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 4663,
"end": 4813
} | class ____(SQLRole):
__slots__ = ()
_role_name = (
"IN expression list, SELECT construct, or bound parameter object"
)
| InElementRole |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_latex.py | {
"start": 7609,
"end": 10593
} | class ____:
def test_to_latex_no_header_with_index(self):
# GH 7124
df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
result = df.to_latex(header=False)
expected = _dedent(
r"""
\begin{tabular}{lrl}
\toprule
\midrule
0 & 1 & ... | TestToLatexHeader |
python | kamyu104__LeetCode-Solutions | Python/minimize-length-of-array-using-operations.py | {
"start": 38,
"end": 275
} | class ____(object):
def minimumArrayLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mn = min(nums)
return (nums.count(mn)+1)//2 if all(x%mn == 0 for x in nums) else 1
| Solution |
python | RaRe-Technologies__gensim | gensim/models/word2vec.py | {
"start": 95570,
"end": 97078
} | class ____:
def __init__(self, fname, max_sentence_length=MAX_WORDS_IN_BATCH):
"""Iterate over sentences from the "text8" corpus, unzipped from https://mattmahoney.net/dc/text8.zip."""
self.fname = fname
self.max_sentence_length = max_sentence_length
def __iter__(self):
# the en... | Text8Corpus |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 19442,
"end": 22434
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(
self, config: Data2VecVisionConfig, window_size: Optional[tuple] = None, drop_path_rate: float = 0.0
) -> None:
super().__init__()
self.chunk_size_feed_forward... | Data2VecVisionLayer |
python | prabhupant__python-ds | data_structures/array/transpose_matrix.py | {
"start": 0,
"end": 337
} | class ____:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
l=[]
i=0
while(i!=len(A[0])):
x=[]
j=0
while(j<len(A)):
x.append(A[j][i])
j+=1
if(x!=[]):
l.append(x)
i+=1
... | Solution |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/qcookiecutter.py | {
"start": 772,
"end": 2720
} | class ____(QtWidgets.QDialog):
"""
QDialog to display cookiecutter.json options.
cookiecutter_settings: dict
A cookiecutter.json settings content.
pre_gen_code: str
The code of the pregeneration script.
"""
sig_validated = QtCore.Signal(int, str)
"""
This signal is emit... | CookiecutterDialog |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 15177,
"end": 15284
} | class ____(Exception):
def __init__(self, message="default"):
super().__init__(message)
| CustomError |
python | lxml__lxml | src/lxml/html/__init__.py | {
"start": 24971,
"end": 25031
} | class ____(HtmlMixin, etree.CommentBase):
pass
| HtmlComment |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 92235,
"end": 94980
} | class ____(unittest.TestCase):
def test_empty_list(self):
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
one = factory.List([])
o = TestObjectFactory()
self.assertEqual([], o.one)
def test_naive_list(self):
class... | ListTestCase |
python | keon__algorithms | algorithms/graph/graph.py | {
"start": 1542,
"end": 2926
} | class ____:
"""
A directed graph.
Stores a set of nodes, edges and adjacency matrix.
"""
# pylint: disable=dangerous-default-value
def __init__(self, load_dict={}):
self.nodes = []
self.edges = []
self.adjacency_list = {}
if load_dict and isinstance(load_dict, d... | DirectedGraph |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 28697,
"end": 45163
} | class ____(BaseClient[httpx.Client, Stream[Any]]):
_client: httpx.Client
_default_stream_cls: type[Stream[Any]] | None = None
def __init__(
self,
*,
version: str,
base_url: str | URL,
max_retries: int = DEFAULT_MAX_RETRIES,
timeout: float | Timeout | None | N... | SyncAPIClient |
python | pypa__virtualenv | src/virtualenv/activation/nushell/__init__.py | {
"start": 106,
"end": 1464
} | class ____(ViaTemplateActivator):
def templates(self):
yield "activate.nu"
@staticmethod
def quote(string):
"""
Nushell supports raw strings like: r###'this is a string'###.
https://github.com/nushell/nushell.github.io/blob/main/book/working_with_strings.md
This me... | NushellActivator |
python | tensorflow__tensorflow | tensorflow/compiler/tests/dynamic_stitch_test.py | {
"start": 983,
"end": 3703
} | class ____(xla_test.XLATestCase):
def _AssertDynamicStitchResultIs(self, indices, data, expected):
with self.session() as session:
index_placeholders = [
array_ops.placeholder(dtypes.as_dtype(arg.dtype)) for arg in indices
]
data_placeholders = [
array_ops.placeholder(dtypes... | DynamicStitchTest |
python | astropy__astropy | astropy/io/votable/tests/test_vo.py | {
"start": 24727,
"end": 25927
} | class ____(TestParse):
def setup_class(self):
with np.errstate(over="ignore"):
# https://github.com/astropy/astropy/issues/13341
votable = parse(get_pkg_data_filename("data/regression.xml"))
self.xmlout = bio = io.BytesIO()
# W39: Bit values can not be masked
... | TestThroughTableData |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/store.py | {
"start": 4383,
"end": 7442
} | class ____(BaseStore):
@classmethod
def _cleanup_old_entries(cls):
"""
Enforce the cache size limit - keeping only the most recently used entries
up to RESULTS_CACHE_SIZE.
"""
# Determine which entries to keep
keep_ids = cls.request_ids()
# Delete all ent... | DatabaseStore |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/sensors/bigtable.py | {
"start": 1548,
"end": 5371
} | class ____(BaseSensorOperator, BigtableValidationMixin):
"""
Sensor that waits for Cloud Bigtable table to be fully replicated to its clusters.
No exception will be raised if the instance or the table does not exist.
For more details about cluster states for a table, have a look at the reference:
... | BigtableTableReplicationCompletedSensor |
python | ray-project__ray | release/llm_tests/benchmark/load_test.py | {
"start": 7142,
"end": 7562
} | class ____(abc.ABC):
DEFAULT_MODEL_NAME = None
def __init__(self, model, parsed_options):
self.model = model
self.parsed_options = parsed_options
@abc.abstractmethod
def get_url(self):
...
@abc.abstractmethod
def format_payload(self, prompt, max_tokens, images):
... | BaseProvider |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 26471,
"end": 26642
} | class ____(SanicException):
"""Exception raised when a websocket is closed."""
quiet = True
message = "Client has closed the websocket connection"
| WebsocketClosed |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_model_with_type_hints.py | {
"start": 1384,
"end": 1619
} | class ____(pydantic.BaseModel):
long_field: int
str_field: str
bool_field: bool
double_field: float
any_field: Any
optional_str: Optional[str] = None # noqa: UP045
str_or_none: str | None = None
| CustomExample |
python | modin-project__modin | modin/core/dataframe/pandas/partitioning/partition.py | {
"start": 1293,
"end": 14770
} | class ____(
ABC, ClassLogger, modin_layer="BLOCK-PARTITION", log_level=LogLevel.DEBUG
): # pragma: no cover
"""
An abstract class that is base for any partition class of ``pandas`` storage format.
The class providing an API that has to be overridden by child classes.
"""
_length_cache = None
... | PandasDataframePartition |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_dataplex.py | {
"start": 3815,
"end": 29413
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"),
new=mock_base_gcp_hook_default_project_id,
):
self.hook = DataplexHook(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_C... | TestDataplexHook |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_test.py | {
"start": 1996,
"end": 2297
} | class ____(rnn_cell_impl.RNNCell):
"""RNN Cell generating (output, new_state) = (input + 1, state + 1)."""
@property
def output_size(self):
return 5
@property
def state_size(self):
return 5
def call(self, input_, state, scope=None):
return (input_ + 1, state + 1)
| Plus1RNNCell |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-separate-sentence-into-rows.py | {
"start": 2247,
"end": 3364
} | class ____(object):
def minimumCost(self, sentence, k):
"""
:type sentence: str
:type k: int
:rtype: int
"""
word_lens = []
j = 0
for i in xrange(len(sentence)+1):
if i != len(sentence) and sentence[i] != ' ':
continue
... | Solution3 |
python | pytorch__pytorch | torchgen/_autoheuristic/mixed_mm/train_decision_mixedmm.py | {
"start": 252,
"end": 2098
} | class ____(AHTrainDecisionTree):
def __init__(self):
super().__init__()
def add_new_features(self, results):
ops = mixed_mm_operations()
added_categorical_features = []
for op in ops:
results[op.name] = results.apply(op.func, axis=1)
if op.is_categorical:... | AHTrainDecisionTreeMixedMM |
python | openai__openai-python | tests/api_resources/test_conversations.py | {
"start": 6733,
"end": 13586
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_create(self, async_client: AsyncOpenAI) -> None:
conversation = await async_client.convers... | TestAsyncConversations |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 18616,
"end": 18704
} | class ____(Sam2VideoVisionRotaryEmbedding):
pass
| Sam3TrackerVideoVisionRotaryEmbedding |
python | django__django | tests/null_queries/models.py | {
"start": 339,
"end": 412
} | class ____(models.Model):
data = models.CharField(max_length=10)
| OuterB |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 7662,
"end": 7784
} | class ____(PrefectException, ValueError):
"""
Raised when a profile name does not exist.
"""
| MissingProfileError |
python | pytorch__pytorch | test/jit/test_backend_nnapi.py | {
"start": 1411,
"end": 5236
} | class ____(TestNNAPI):
def setUp(self):
super().setUp()
# Save default dtype
module = torch.nn.PReLU()
self.default_dtype = module.weight.dtype
# Change dtype to float32 (since a different unit test changed dtype to float64,
# which is not supported by the Android NN... | TestNnapiBackend |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py | {
"start": 50217,
"end": 63973
} | class ____(KyutaiSpeechToTextPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
_keep_in_fp32_modules_strict = ["codec_model"]
output_modalities = ("audi... | KyutaiSpeechToTextForConditionalGeneration |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 15493,
"end": 16984
} | class ____:
"""Test el_GR address provider methods"""
def test_line_address(self, faker, num_samples):
for _ in range(num_samples):
address = faker.line_address()
assert isinstance(address, str)
def test_street_prefix_short(self, faker, num_samples):
for _ in range(... | TestElGr |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/cluster.py | {
"start": 1574,
"end": 2925
} | class ____(Predictor, Transformer, Estimator, Benchmark):
"""
Benchmarks for MiniBatchKMeans.
"""
param_names = ["representation", "init"]
params = (["dense", "sparse"], ["random", "k-means++"])
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
repr... | MiniBatchKMeansBenchmark |
python | ray-project__ray | python/ray/data/_internal/logical/operators/write_operator.py | {
"start": 293,
"end": 1215
} | class ____(AbstractMap):
"""Logical operator for write."""
def __init__(
self,
input_op: LogicalOperator,
datasink_or_legacy_datasource: Union[Datasink, Datasource],
ray_remote_args: Optional[Dict[str, Any]] = None,
concurrency: Optional[int] = None,
**write_args... | Write |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-faiss/llama_index/vector_stores/faiss/map_store.py | {
"start": 750,
"end": 9900
} | class ____(FaissVectorStore):
"""
Faiss Map Vector Store.
This wraps the base Faiss vector store and adds handling for
the Faiss IDMap and IDMap2 indexes. This allows for
update/delete functionality through node_id and faiss_id mapping.
Embeddings are stored within a Faiss index.
During q... | FaissMapVectorStore |
python | pytorch__pytorch | torchgen/dest/lazy_ir.py | {
"start": 14749,
"end": 26485
} | class ____:
class_method_name: str
backend_index: BackendIndex
tensor_class: str
gen_forced_fallback_code: bool
backend_namespace: str
get_tensorlist: str
get_tensor_or_wrap_number: str
try_get_tensor: str
metrics_counter: str
create_tensor: str
create_from_first_tensor: bool... | GenLazyNativeFuncDefinition |
python | tornadoweb__tornado | demos/file_upload/file_receiver.py | {
"start": 872,
"end": 1562
} | class ____(tornado.web.RequestHandler):
def initialize(self):
self.bytes_read = 0
def data_received(self, chunk):
self.bytes_read += len(chunk)
def put(self, filename):
filename = unquote(filename)
mtype = self.request.headers.get("Content-Type")
logging.info('PUT "... | PUTHandler |
python | numpy__numpy | numpy/lib/tests/test_twodim_base.py | {
"start": 5096,
"end": 5405
} | class ____:
def test_basic(self):
assert_raises(ValueError, fliplr, ones(4))
a = get_mat(4)
b = a[:, ::-1]
assert_equal(fliplr(a), b)
a = [[0, 1, 2],
[3, 4, 5]]
b = [[2, 1, 0],
[5, 4, 3]]
assert_equal(fliplr(a), b)
| TestFliplr |
python | huggingface__transformers | src/transformers/models/speech_to_text/modeling_speech_to_text.py | {
"start": 22890,
"end": 28844
} | class ____(Speech2TextPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`Speech2TextEncoderLayer`].
Args:
config: Speech2TextConfig
embed_tokens (nn.Embedding): output embedding
"""
_no_split_modules = ["Spee... | Speech2TextEncoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.