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 | readthedocs__readthedocs.org | readthedocs/projects/migrations/0075_change_mkdocs_name.py | {
"start": 149,
"end": 1068
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0074_backport_indexes"),
]
operations = [
migrations.AlterField(
model_name="project",
name="documentation_type",
field=models.CharField(
choic... | Migration |
python | cookiecutter__cookiecutter | cookiecutter/prompt.py | {
"start": 1267,
"end": 5042
} | class ____(Confirm):
"""A prompt that returns a boolean for yes/no questions."""
yes_choices = ["1", "true", "t", "yes", "y", "on"]
no_choices = ["0", "false", "f", "no", "n", "off"]
def process_response(self, value: str) -> bool:
"""Convert choices to a bool."""
value = value.strip().... | YesNoPrompt |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 17414,
"end": 20240
} | class ____(BaseField):
"""Datetime field.
Uses the python-dateutil library if available alternatively use time.strptime
to parse the dates. Note: python-dateutil's parser is fully featured and when
installed you can utilise it to convert varying types of date formats into valid
python datetime obj... | DateTimeField |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 95959,
"end": 96931
} | class ____(system_info):
section = 'x11'
notfounderror = X11NotFoundError
_lib_names = ['X11']
def __init__(self):
system_info.__init__(self,
default_lib_dirs=default_x11_lib_dirs,
default_include_dirs=default_x11_include_dirs)
def ... | x11_info |
python | getsentry__sentry-python | sentry_sdk/integrations/argv.py | {
"start": 268,
"end": 911
} | class ____(Integration):
identifier = "argv"
@staticmethod
def setup_once():
# type: () -> None
@add_global_event_processor
def processor(event, hint):
# type: (Event, Optional[Hint]) -> Optional[Event]
if sentry_sdk.get_client().get_integration(ArgvIntegrati... | ArgvIntegration |
python | ijl__orjson | test/test_jsonchecker.py | {
"start": 1192,
"end": 6218
} | class ____:
def _run_fail_json(self, filename, exc=orjson.JSONDecodeError):
data = read_fixture_str(filename, "jsonchecker")
pytest.raises(exc, orjson.loads, data)
def _run_pass_json(self, filename, match=""):
data = read_fixture_str(filename, "jsonchecker")
assert orjson.dumps(... | TestJsonChecker |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_indexing.py | {
"start": 27107,
"end": 27899
} | class ____:
def test_asof_locs_mismatched_type(self):
dti = date_range("2016-01-01", periods=3)
pi = dti.to_period("D")
pi2 = dti.to_period("h")
mask = np.array([0, 1, 0], dtype=bool)
msg = "must be DatetimeIndex or PeriodIndex"
with pytest.raises(TypeError, match=m... | TestAsOfLocs |
python | pytorch__pytorch | test/test_sparse.py | {
"start": 189579,
"end": 192303
} | class ____(TestCase):
@unittest.skipIf(not TEST_CUDA, 'CUDA not available')
def test_cuda_from_cpu(self):
with self.assertRaisesRegex(
RuntimeError,
"Expected all tensors to be on the same device"):
torch.sparse_coo_tensor(torch.zeros(1, 4).long().cuda(),
... | TestSparseOneOff |
python | apache__airflow | providers/atlassian/jira/tests/unit/atlassian/jira/operators/test_jira.py | {
"start": 1607,
"end": 4447
} | class ____:
@pytest.fixture(autouse=True)
def setup_test_cases(self, monkeypatch):
monkeypatch.setenv(
"AIRFLOW_CONN_JIRA_DEFAULT",
connection_as_json(
Connection(
conn_id="jira_default",
conn_type="jira",
... | TestJiraOperator |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 40282,
"end": 43995
} | class ____(GPTJPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = GPTJModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
... | GPTJForQuestionAnswering |
python | qdrant__qdrant-client | tests/congruence_tests/test_sparse_idf_search.py | {
"start": 493,
"end": 3227
} | class ____:
__test__ = False
def __init__(self):
self.query_text = generate_random_sparse_vector(sparse_text_vector_size, density=0.1)
def simple_search_text(self, client: QdrantBase) -> list[models.ScoredPoint]:
return client.query_points(
collection_name=COLLECTION_NAME,
... | TestSimpleSparseSearcher |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_strategy.py | {
"start": 36742,
"end": 79888
} | class ____(distribute_lib.StrategyExtendedV1):
"""Implementation of TPUStrategy."""
def __init__(
self,
container_strategy,
tpu_cluster_resolver=None,
steps_per_run=None,
device_assignment=None,
use_spmd_for_xla_partitioning=False,
):
super().__init__(container_strategy)
... | TPUExtended |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py | {
"start": 2294,
"end": 2475
} | class ____:
def __init__(self, x): ...
def func9[T: H](x: type[T], y: H) -> T:
if type(y) == x:
reveal_type(y, expected_text="H*")
return y
return x(y)
| H |
python | kamyu104__LeetCode-Solutions | Python/maximum-total-reward-using-operations-i.py | {
"start": 896,
"end": 1395
} | class ____(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
mx = max(rewardValues)
dp = [False]*((mx-1)+1)
dp[0] = True
for v in sorted(set(rewardValues)):
for x in xrange(min(v, mx-v)):
... | Solution3 |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 17434,
"end": 23252
} | class ____(LatticeOp, BooleanFunction):
"""
Logical AND function.
It evaluates its arguments in order, returning false immediately
when an argument is false and true if they are all true.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import And
>>> x & y
x & ... | And |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_device.py | {
"start": 156,
"end": 1290
} | class ____(TestCase):
def test_device_count(self):
count = torch.accelerator.device_count()
self.assertEqual(count, 2)
def test_device_switch(self):
torch.accelerator.set_device_index(1)
self.assertEqual(torch.accelerator.current_device_index(), 1)
torch.accelerator.set... | TestDevice |
python | sqlalchemy__sqlalchemy | examples/asyncio/async_orm_writeonly.py | {
"start": 1099,
"end": 2906
} | class ____(Base):
__tablename__ = "b"
id: Mapped[int] = mapped_column(primary_key=True)
a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
data: Mapped[Optional[str]]
async def async_main():
"""Main program function."""
engine = create_async_engine(
"postgresql+asyncpg://scott:tige... | B |
python | tiangolo__fastapi | fastapi/params.py | {
"start": 7879,
"end": 10929
} | class ____(Param): # type: ignore[misc]
in_ = ParamTypes.query
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union... | Query |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP050.py | {
"start": 95,
"end": 142
} | class ____(
metaclass=type
#
):
...
| A |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 1317,
"end": 3956
} | class ____(
NamedTuple(
"_ExecutionPlanSnapshotArgs",
[
("job_origin", RemoteJobOrigin),
("op_selection", Sequence[str]),
("run_config", Mapping[str, object]),
("step_keys_to_execute", Optional[Sequence[str]]),
("job_snapshot_id", str),
... | ExecutionPlanSnapshotArgs |
python | scipy__scipy | scipy/stats/tests/test_sampling.py | {
"start": 23280,
"end": 27825
} | class ____:
# DAU fails on these probably because of large domains and small
# computation errors in PMF. Mean/SD match but chi-squared test fails.
basic_fail_dists = {
'nchypergeom_fisher', # numerical errors on tails
'nchypergeom_wallenius', # numerical errors on tails
'randint' ... | TestDiscreteAliasUrn |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/concrete_function_test.py | {
"start": 1370,
"end": 5501
} | class ____(test.TestCase, parameterized.TestCase):
def concrete_function_with_attrs(self, attrs):
func_graph = func_graph_module.FuncGraph("f")
return cf.ConcreteFunction.from_func_graph(func_graph, None, attrs=attrs)
@parameterized.parameters(
({"api_implements": True}, attr_value_pb2.AttrValue(b=T... | ConcreteFunctionTest |
python | great-expectations__great_expectations | great_expectations/render/renderer/microsoft_teams_renderer.py | {
"start": 616,
"end": 8518
} | class ____(Renderer):
"""
Responsible for formatting validation results and data docs links into a Microsoft Teams webhook
message payload.
Relevant links/documentation:
* Payload schema: https://adaptivecards.io/explorer/
* Interactive UI editor: https://adaptivecards.io/designer/
... | MicrosoftTeamsRenderer |
python | wandb__wandb | wandb/vendor/pygments/lexers/capnproto.py | {
"start": 413,
"end": 2188
} | class ____(RegexLexer):
"""
For `Cap'n Proto <https://capnproto.org>`_ source.
.. versionadded:: 2.2
"""
name = 'Cap\'n Proto'
filenames = ['*.capnp']
aliases = ['capnp']
flags = re.MULTILINE | re.UNICODE
tokens = {
'root': [
(r'#.*?$', Comment.Single),
... | CapnProtoLexer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance1.py | {
"start": 3976,
"end": 4327
} | class ____[T]:
def __init__(self, value: T) -> None:
pass
def set_value(self, value: T) -> None:
pass
# This should generate an error based on variance.
vcontra1_1: ShouldBeContravariant1[float] = ShouldBeContravariant1[int](1)
vcontra1_2: ShouldBeContravariant1[int] = ShouldBeContravariant1... | ShouldBeContravariant1 |
python | encode__django-rest-framework | rest_framework/exceptions.py | {
"start": 6087,
"end": 6449
} | class ____(APIException):
status_code = status.HTTP_406_NOT_ACCEPTABLE
default_detail = _('Could not satisfy the request Accept header.')
default_code = 'not_acceptable'
def __init__(self, detail=None, code=None, available_renderers=None):
self.available_renderers = available_renderers
... | NotAcceptable |
python | django__django | tests/test_runner_apps/tagged/tests.py | {
"start": 74,
"end": 276
} | class ____(TestCase):
@tag("fast")
def test_single_tag(self):
self.assertEqual(1, 1)
@tag("fast", "core")
def test_multiple_tags(self):
self.assertEqual(1, 1)
| TaggedTestCase |
python | ApeWorX__ape | src/ape/cli/choices.py | {
"start": 13273,
"end": 14175
} | class ____(Enum):
"""
An enum representing output formats, such as ``TREE`` or ``YAML``.
Use this to select a subset of common output formats to use
when creating a :meth:`~ape.cli.choices.output_format_choice`.
"""
TREE = "TREE"
"""A rich text tree view of the data."""
YAML = "YAML"
... | OutputFormat |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_log.py | {
"start": 1561,
"end": 18805
} | class ____:
DAG_ID = "dag_for_testing_log_endpoint"
RUN_ID = "dag_run_id_for_testing_log_endpoint"
TASK_ID = "task_for_testing_log_endpoint"
MAPPED_TASK_ID = "mapped_task_for_testing_log_endpoint"
TRY_NUMBER = 1
default_time = "2020-06-10T20:00:00+00:00"
@pytest.fixture(autouse=True)
d... | TestTaskInstancesLog |
python | gevent__gevent | src/gevent/testing/testrunner.py | {
"start": 3220,
"end": 8497
} | class ____(object):
TIME_WAIT_REAP = 0.1
TIME_WAIT_SPAWN = 0.05
def __init__(self,
tests,
*,
allowed_return_codes=(),
configured_failing_tests=(),
failfast=False,
quiet=False,
configured_... | Runner |
python | celery__celery | celery/app/task.py | {
"start": 2079,
"end": 5155
} | class ____:
"""Task request variables (Task.request)."""
_children = None # see property
_protected = 0
args = None
callbacks = None
called_directly = True
chain = None
chord = None
correlation_id = None
delivery_info = None
errbacks = None
eta = None
expires = Non... | Context |
python | apache__airflow | airflow-core/src/airflow/models/backfill.py | {
"start": 2186,
"end": 2346
} | class ____(AirflowException):
"""
Raised when attempting to create backfill for a DAG with no schedule.
:meta private:
"""
| DagNoScheduleException |
python | apache__airflow | airflow-core/src/airflow/models/dagbag.py | {
"start": 4432,
"end": 6686
} | class ____(Base):
"""Model to store the dag parsing requests that will be prioritized when parsing files."""
__tablename__ = "dag_priority_parsing_request"
# Adding a unique constraint to fileloc results in the creation of an index and we have a limitation
# on the size of the string we can use in the... | DagPriorityParsingRequest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 5496,
"end": 5682
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneMessageEvent, GrapheneStepEvent)
name = "ExecutionStepSkippedEvent"
| GrapheneExecutionStepSkippedEvent |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/ColorGradientPlots.py | {
"start": 220,
"end": 1622
} | class ____(object):
""" source of buffered demonstration data """
def __init__(self, sample_rate=200., signal_period=0.55, negative_period=None, max_length=300):
""" prepare, but don't start yet """
self.rate = sample_rate
self.period = signal_period
self.neg_period = negative_pe... | DataSource |
python | getsentry__sentry | tests/sentry/search/events/builder/test_span_metrics.py | {
"start": 12095,
"end": 12730
} | class ____(MetricsEnhancedPerformanceTestCase):
def test_split_granularity(self) -> None:
params: ParamsType = {
"organization_id": self.organization.id,
"project_id": [self.project.id],
"start": datetime.datetime(2015, 5, 18, 23, 3, 0, tzinfo=timezone.utc),
"... | TimeseriesMetricQueryBuilder |
python | milvus-io__pymilvus | pymilvus/exceptions.py | {
"start": 3629,
"end": 3729
} | class ____(MilvusException):
"""Raise when consistency level is invalid"""
| InvalidConsistencyLevel |
python | pytorch__pytorch | test/functorch/test_control_flow.py | {
"start": 366931,
"end": 370805
} | class ____(torch.nn.Module):
def forward(self, s17: "Sym(s17)", s94: "Sym(s94)", L_y_: "f32[s17, s94]", L_z_: "f32[s17, s94]", L_x_: "f32[s17, s94]"):
l_y_ = L_y_
l_z_ = L_z_
l_x_ = L_x_
sum_1: "f32[]" = l_x_.sum()
gt: "b8[]" = sum_1 > 0; sum_1 = None
cond_true_0 =... | GraphModule |
python | pytest-dev__pytest-cov | src/pytest_cov/__init__.py | {
"start": 719,
"end": 908
} | class ____(Exception):
"""
Raised when dynamic_context is set to test_function and xdist is also used.
See: https://github.com/pytest-dev/pytest-cov/issues/604
"""
| DistCovError |
python | joblib__joblib | joblib/externals/loky/backend/context.py | {
"start": 11447,
"end": 13200
} | class ____(BaseContext):
"""Context relying on the LokyProcess."""
_name = "loky"
Process = LokyProcess
cpu_count = staticmethod(cpu_count)
def Queue(self, maxsize=0, reducers=None):
"""Returns a queue object"""
from .queues import Queue
return Queue(maxsize, reducers=redu... | LokyContext |
python | kamyu104__LeetCode-Solutions | Python/find-the-winner-of-the-circular-game.py | {
"start": 315,
"end": 618
} | class ____(object):
def findTheWinner(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def f(idx, n, k):
if n == 1:
return 0
return (k+f((idx+k)%n, n-1, k))%n
return f(0, n, k)+1
| Solution2 |
python | Textualize__textual | docs/examples/app/question_title01.py | {
"start": 95,
"end": 645
} | class ____(App[str]):
CSS_PATH = "question02.tcss"
TITLE = "A Question App"
SUB_TITLE = "The most important question"
def compose(self) -> ComposeResult:
yield Header()
yield Label("Do you love Textual?", id="question")
yield Button("Yes", id="yes", variant="primary")
yi... | MyApp |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_filters.py | {
"start": 110,
"end": 2031
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-filters"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def get_filter_spec(
self, response_data: Iterable[dict[str, Any]], spec_id: str
) -> dict[str, Any]:
"""
looks in a success... | ProjectFiltersTest |
python | huggingface__transformers | src/transformers/models/ernie/modular_ernie.py | {
"start": 19297,
"end": 22063
} | class ____(BertForMaskedLM):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "ernie.embeddings.word_embeddings.weight",
}
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.T... | ErnieForMaskedLM |
python | dagster-io__dagster | python_modules/dagster/dagster/components/testing/test_cases.py | {
"start": 4751,
"end": 5812
} | class ____(TestTranslation):
"""This version of the TestTranslation class is used to test the translation of
asset attributes, applying all customizations in parallel to speed up tests for
components which might be expensive to construct.
"""
@pytest.fixture()
def translation_test_case(self, re... | TestTranslationBatched |
python | tensorflow__tensorflow | tensorflow/python/distribute/parallel_device/parallel_device_test.py | {
"start": 3399,
"end": 4538
} | class ____(test.TestCase):
def setUp(self):
super(_VirtualDeviceTestCase, self).setUp()
ctx = context.context()
if ctx.list_physical_devices("TPU"):
self.device_type = "TPU"
tpu_cluster_resolver.initialize_tpu_system()
elif ctx.list_physical_devices("GPU"):
self.device_type = "GPU"
... | _VirtualDeviceTestCase |
python | hyperopt__hyperopt | hyperopt/base.py | {
"start": 6945,
"end": 23275
} | class ____:
"""Database interface supporting data-driven model-based optimization.
The model-based optimization algorithms used by hyperopt's fmin function
work by analyzing samples of a response surface--a history of what points
in the search space were tested, and what was discovered by those tests.
... | Trials |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 13572,
"end": 16160
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'service_mgr']
valid_subsets = ['service_mgr']
fact_namespace = 'ansible_service_mgr'
collector_class = ServiceMgrFactCollector
# TODO: dedupe some of this test code
@patch('ansible.module_utils.facts.system.service_mgr.ge... | TestServiceMgrFacts |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol5.py | {
"start": 968,
"end": 1209
} | class ____(Protocol):
__name__: str
__module__: str
__qualname__: str
__annotations__: dict[str, Any]
__slots__ = ()
def __call__(self) -> None: ...
def func2() -> None: ...
v: CallbackProto2 = func2
| CallbackProto2 |
python | realpython__materials | python-callable-instances/serializing.py | {
"start": 208,
"end": 408
} | class ____:
def __init__(self, serializer_strategy):
self.serializer_strategy = serializer_strategy
def serialize(self, data):
return self.serializer_strategy(data)
| DataSerializer |
python | ethereum__web3.py | web3/_utils/module_testing/go_ethereum_txpool_module.py | {
"start": 760,
"end": 1223
} | class ____:
def test_geth_txpool_inspect(self, w3: "Web3") -> None:
test_data = w3.geth.txpool.inspect()
assert "pending" in test_data
def test_geth_txpool_content(self, w3: "Web3") -> None:
test_data = w3.geth.txpool.content()
assert "pending" in test_data
def test_geth_tx... | GoEthereumTxPoolModuleTest |
python | kamyu104__LeetCode-Solutions | Python/wiggle-sort.py | {
"start": 502,
"end": 804
} | class ____(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
med = (len(nums) - 1) // 2
nums[::2], nums[1::2] = nums[med::-1], nums[:med:-1]
| Solution2 |
python | hynek__structlog | tests/test_config.py | {
"start": 2032,
"end": 4561
} | class ____:
def test_get_config_is_configured(self):
"""
Return value of structlog.get_config() works as input for
structlog.configure(). is_configured() reflects the state of
configuration.
"""
assert False is structlog.is_configured()
structlog.configure(**... | TestConfigure |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 29455,
"end": 29591
} | class ____(BaseModel):
ti_id: UUID
type: Literal["ValidateInletsAndOutlets"] = "ValidateInletsAndOutlets"
| ValidateInletsAndOutlets |
python | numba__numba | numba/cuda/tests/nocuda/test_library_lookup.py | {
"start": 555,
"end": 2285
} | class ____(SerialMixin, unittest.TestCase):
def setUp(self):
ctx = mp.get_context('spawn')
qrecv = ctx.Queue()
qsend = ctx.Queue()
self.qsend = qsend
self.qrecv = qrecv
self.child_process = ctx.Process(
target=check_lib_lookup,
args=(qrecv, qs... | LibraryLookupBase |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/dagster/asset_versioning_and_caching/observable_source_asset_path_with_io_managers.py | {
"start": 248,
"end": 2080
} | class ____(dg.IOManager):
def __init__(self, root_dir: str):
self.root_dir = root_dir
@staticmethod
def with_directory(root_dir: str):
mkdir_p(root_dir)
return NumberTextFileIOManager(root_dir=root_dir)
def load_input(self, context: "dg.InputContext") -> int:
asset_key_... | NumberTextFileIOManager |
python | python-openxml__python-docx | src/docx/image/tiff.py | {
"start": 8196,
"end": 8663
} | class ____(_IfdEntry):
"""IFD entry having the form of a NULL-terminated ASCII string."""
@classmethod
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
"""Return the ASCII string parsed from `stream_rdr` at `value_offset`.
The length of the string, including a terminat... | _AsciiIfdEntry |
python | tornadoweb__tornado | tornado/routing.py | {
"start": 7247,
"end": 7788
} | class ____(Router):
"""Abstract router interface for routers that can handle named routes
and support reversing them to original urls.
"""
def reverse_url(self, name: str, *args: Any) -> Optional[str]:
"""Returns url string for a given route name and arguments
or ``None`` if no match is... | ReversibleRouter |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/buffer.py | {
"start": 9572,
"end": 20000
} | class ____(MutableMapping):
"""
AgentBuffer contains a dictionary of AgentBufferFields. Each agent has his own AgentBuffer.
The keys correspond to the name of the field. Example: state, action
"""
# Whether or not to validate the types of keys at runtime
# This should be off for training, but e... | AgentBuffer |
python | ray-project__ray | rllib/core/models/configs.py | {
"start": 16291,
"end": 27462
} | class ____(ModelConfig):
"""Configuration for a convolutional transpose head (decoder) network.
The configured Model transforms 1D-observations into an image space.
The stack of layers is composed of an initial Dense layer, followed by a sequence
of Conv2DTranspose layers.
`input_dims` describes th... | CNNTransposeHeadConfig |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 77908,
"end": 78052
} | class ____:
xlOLEControl = 2 # from enum XlOLEType
xlOLEEmbed = 1 # from enum XlOLEType
xlOLELink = 0 # from enum XlOLEType
| OLEType |
python | plotly__plotly.py | plotly/graph_objs/scatter/hoverlabel/_font.py | {
"start": 233,
"end": 17143
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.hoverlabel"
_path_str = "scatter.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"s... | Font |
python | doocs__leetcode | solution/2700-2799/2748.Number of Beautiful Pairs/Solution.py | {
"start": 0,
"end": 310
} | class ____:
def countBeautifulPairs(self, nums: List[int]) -> int:
cnt = [0] * 10
ans = 0
for x in nums:
for y in range(10):
if cnt[y] and gcd(x % 10, y) == 1:
ans += cnt[y]
cnt[int(str(x)[0])] += 1
return ans
| Solution |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 146717,
"end": 147701
} | class ____(nn.Module):
def __init__(self, ratio=2, kernel_size=None):
super().__init__()
cutoff = 0.5 / ratio
half_width = 0.6 / ratio
if cutoff < 0.0:
raise ValueError("Minimum cutoff must be larger than zero.")
if cutoff > 0.5:
raise ValueError("A c... | DownSample1d |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_match_xml_schema.py | {
"start": 2520,
"end": 8008
} | class ____(ColumnMapExpectation):
"""Expect column entries to be XML documents matching a given [XMLSchema](https://en.wikipedia.org/wiki/XML_schema).
expect_column_values_to_match_xml_schema is a \
[Column Map Expectation](https://docs.greatexpectations.io/docs/guides/expectations/creating_custom_expectat... | ExpectColumnValuesToMatchXmlSchema |
python | mlflow__mlflow | mlflow/gateway/providers/palm.py | {
"start": 369,
"end": 7990
} | class ____(BaseProvider):
NAME = "PaLM"
CONFIG_TYPE = PaLMConfig
def __init__(self, config: EndpointConfig) -> None:
super().__init__(config)
warnings.warn(
"PaLM provider is deprecated and will be removed in a future MLflow version.",
category=FutureWarning,
... | PaLMProvider |
python | automl__auto-sklearn | autosklearn/data/abstract_data_manager.py | {
"start": 189,
"end": 1974
} | class ____:
__metaclass__ = abc.ABCMeta
def __init__(self, name: str):
self._data = dict() # type: Dict
self._info = dict() # type: Dict
self._name = name
@property
def name(self) -> str:
return self._name
@property
def data(self) -> Dict[str, np.ndarray]:
... | AbstractDataManager |
python | pytorch__pytorch | test/inductor/test_config.py | {
"start": 500,
"end": 12187
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._saved_config = config.save_config()
def tearDown(self):
super().tearDown()
config.load_config(self._saved_config)
def test_set(self):
config.max_fusion_size = 13337
self.as... | TestInductorConfig |
python | celery__celery | celery/canvas.py | {
"start": 3743,
"end": 7653
} | class ____(metaclass=ABCMeta):
"""Stamping API. A class that provides a stamping API possibility for
canvas primitives. If you want to implement stamping behavior for
a canvas primitive override method that represents it.
"""
def on_group_start(self, group, **headers) -> dict:
"""Method th... | StampingVisitor |
python | bokeh__bokeh | src/bokeh/models/annotations/labels.py | {
"start": 9667,
"end": 11330
} | class ____(TextAnnotation):
''' Render a single title box as an annotation.
See :ref:`ug_basic_annotations_titles` for information on plotting titles.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs... | Title |
python | scipy__scipy | benchmarks/benchmarks/test_functions.py | {
"start": 8038,
"end": 8342
} | class ____:
target_E = 0.292579
solution = [0, 1.253131828927371]
xmin = np.array([-100., -100])
xmax = np.array([100., 100])
def fun(self, x):
num = cos(sin(abs(x[0]**2 - x[1]**2)))**2 - 0.5
den = (1+0.001*(x[0]**2 + x[1]**2))**2
return 0.5 + num / den
| Schaffer4 |
python | dask__dask | dask/dataframe/dask_expr/_collection.py | {
"start": 8656,
"end": 95143
} | class ____(DaskMethodsMixin):
"""Base class for Expr-backed Collections"""
__dask_scheduler__ = staticmethod(
named_schedulers.get("threads", named_schedulers["sync"])
)
__dask_optimize__ = staticmethod(lambda dsk, keys, **kwargs: dsk)
def __init__(self, expr):
global _WARN_ANNOTAT... | FrameBase |
python | coleifer__peewee | tests/keys.py | {
"start": 1143,
"end": 1312
} | class ____(TestModel):
f1 = CharField()
f2 = IntegerField()
f3 = FloatField()
class Meta:
primary_key = CompositeKey('f1', 'f2')
| CompositeKeyModel |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_facets_performance.py | {
"start": 2662,
"end": 5006
} | class ____(OrganizationEventsFacetsPerformanceEndpointBase):
def get(self, request: Request, organization: Organization) -> Response:
try:
snuba_params, aggregate_column, filter_query = self._setup(request, organization)
except NoProjects:
return Response([])
all_tag... | OrganizationEventsFacetsPerformanceEndpoint |
python | keras-team__keras | keras/src/models/model.py | {
"start": 1301,
"end": 36664
} | class ____(Trainer, base_trainer.Trainer, Layer):
"""A model grouping layers into an object with training/inference features.
There are three ways to instantiate a `Model`:
## With the "Functional API"
You start from `Input`,
you chain layer calls to specify the model's forward pass,
and fina... | Model |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 7986,
"end": 8074
} | class ____(VyperException):
"""Invalid event declaration."""
| EventDeclarationException |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 66930,
"end": 67026
} | class ____(spack.error.FetchError):
"""Raised when archive fails to checksum."""
| ChecksumError |
python | celery__celery | t/unit/worker/test_loops.py | {
"start": 4481,
"end": 15399
} | class ____:
def setup_method(self):
@self.app.task(shared=False)
def add(x, y):
return x + y
self.add = add
def test_drain_after_consume(self):
x, _ = get_task_callback(self.app, transport_driver_type='amqp')
assert _quick_drain in [p.fun for p in x.hub._rea... | test_asynloop |
python | walkccc__LeetCode | solutions/1800. Maximum Ascending Subarray Sum/1800.py | {
"start": 0,
"end": 277
} | class ____:
def maxAscendingSum(self, nums: list[int]) -> int:
ans = 0
sum = nums[0]
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
sum += nums[i]
else:
ans = max(ans, sum)
sum = nums[i]
return max(ans, sum)
| Solution |
python | arrow-py__arrow | arrow/locales.py | {
"start": 109003,
"end": 110564
} | class ____(Locale):
names = ["la", "la-va"]
past = "ante {0}"
future = "in {0}"
and_word = "et"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "nunc",
"second": "secundum",
"seconds": "{0} secundis",
"minute": "minutam",
... | LatinLocale |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 19328,
"end": 22105
} | class ____(BaseNode):
text_resource: MediaResource | None = Field(
default=None, description="Text content of the node."
)
image_resource: MediaResource | None = Field(
default=None, description="Image content of the node."
)
audio_resource: MediaResource | None = Field(
defa... | Node |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 457420,
"end": 457926
} | class ____(AtomicExprNode):
type = dict_type
is_temp = 1
def analyse_types(self, env):
env.use_utility_code(Builtin.globals_utility_code)
return self
gil_message = "Constructing globals dict"
def may_be_none(self):
return False
def generate_result_code(self, code):
... | GlobalsExprNode |
python | PrefectHQ__prefect | src/prefect/server/concurrency/lease_storage/__init__.py | {
"start": 433,
"end": 541
} | class ____(Protocol):
ConcurrencyLeaseStorage: type[ConcurrencyLeaseStorage]
| ConcurrencyLeaseStorageModule |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 9107,
"end": 10217
} | class ____:
tol = 0.0
def distance(self, a, b, p):
return minkowski_distance(a * 1.0, b * 1.0, p)
def test_in_ball(self):
x = np.atleast_2d(self.x)
d = np.broadcast_to(self.d, x.shape[:-1])
l = self.T.query_ball_point(x, self.d, p=self.p, eps=self.eps)
for i, ind in... | ball_consistency |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 2484,
"end": 2783
} | class ____(BaseStringType):
_members: Tuple[str, ...]
@classmethod
def validate(cls, value: Any) -> None:
cls.validate_string(value)
if value not in cls._members:
raise ValueError("must be one of %s, got '%s'" % (cls._members, value))
| BaseStringEnumerationType |
python | viewflow__viewflow | viewflow/contrib/plotly/views.py | {
"start": 911,
"end": 2557
} | class ____(TemplateView):
template_name = "viewflow/contrib/plotly.html"
viewset = None
def get_context_data(self, **kwargs):
return super().get_context_data(
dash_scripts_urls=_extract_urls(
self.viewset.dash_app._generate_scripts_html()
),
dash_... | DashboardView |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 45647,
"end": 46962
} | class ____(Fittable2DModel):
"""
Two dimensional Plane model.
Parameters
----------
slope_x : float
Slope of the plane in X
slope_y : float
Slope of the plane in Y
intercept : float
Z-intercept of the plane
Notes
-----
Model formula:
.. math::... | Planar2D |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/utils.py | {
"start": 1953,
"end": 2074
} | class ____:
EMAIL = "email"
NAME = "fullname"
SRegFields = [
SRegField.EMAIL,
SRegField.NAME,
]
| SRegField |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_set_value.py | {
"start": 138,
"end": 2492
} | class ____:
def test_set_value(self, float_frame):
for idx in float_frame.index:
for col in float_frame.columns:
float_frame._set_value(idx, col, 1)
assert float_frame[col][idx] == 1
def test_set_value_resize(self, float_frame, using_infer_string):
re... | TestSetValue |
python | kamyu104__LeetCode-Solutions | Python/the-k-strongest-values-in-an-array.py | {
"start": 915,
"end": 2353
} | class ____(object):
def getStrongest(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: List[int]
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def partition_around_pivot(left, right, pivot_idx, nums, compare):
new_piv... | Solution_TLE |
python | huggingface__transformers | src/transformers/models/blip_2/modeling_blip_2.py | {
"start": 11087,
"end": 13923
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim /... | Blip2Attention |
python | django__django | django/contrib/sessions/middleware.py | {
"start": 355,
"end": 3483
} | class ____(MiddlewareMixin):
def __init__(self, get_response):
super().__init__(get_response)
engine = import_module(settings.SESSION_ENGINE)
self.SessionStore = engine.SessionStore
def process_request(self, request):
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAM... | SessionMiddleware |
python | getsentry__sentry | src/sentry/workflow_engine/models/alertrule_workflow.py | {
"start": 280,
"end": 1422
} | class ____(DefaultFieldsModel):
"""
A lookup model for rules and workflows.
"""
__relocation_scope__ = RelocationScope.Organization
alert_rule_id = BoundedBigIntegerField(null=True, db_index=True)
rule_id = BoundedBigIntegerField(null=True, db_index=True)
workflow = FlexibleForeignKey("wor... | AlertRuleWorkflow |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_fetch_tool_result_error_block_param.py | {
"start": 321,
"end": 508
} | class ____(TypedDict, total=False):
error_code: Required[BetaWebFetchToolResultErrorCode]
type: Required[Literal["web_fetch_tool_result_error"]]
| BetaWebFetchToolResultErrorBlockParam |
python | gevent__gevent | src/greentest/3.13/test_threading.py | {
"start": 66185,
"end": 70382
} | class ____(BaseTestCase):
def setUp(self):
restore_default_excepthook(self)
super().setUp()
@force_not_colorized
def test_excepthook(self):
with support.captured_output("stderr") as stderr:
thread = ThreadRunFail(name="excepthook thread")
thread.start()
... | ExceptHookTests |
python | run-llama__llama_index | llama-index-finetuning/llama_index/finetuning/types.py | {
"start": 922,
"end": 1305
} | class ____(ABC):
"""Base Cross Encoder Finetuning Engine."""
@abstractmethod
def finetune(self) -> None:
"""Goes off and does stuff."""
@abstractmethod
def get_finetuned_model(
self, model_name: str, top_n: int = 3
) -> SentenceTransformerRerank:
"""Gets fine-tuned Cros... | BaseCrossEncoderFinetuningEngine |
python | spack__spack | lib/spack/spack/llnl/util/link_tree.py | {
"start": 20372,
"end": 20504
} | class ____(MergeConflictError):
def __init__(self, spec_1, spec_2):
super().__init__(spec_1, spec_2)
| ConflictingSpecsError |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/progress_bar/formatters.py | {
"start": 3370,
"end": 3857
} | class ____(Formatter):
"""
Display the progress as a percentage.
"""
template = HTML("<percentage>{percentage:>5}%</percentage>")
def format(
self,
progress_bar: ProgressBar,
progress: ProgressBarCounter[object],
width: int,
) -> AnyFormattedText:
return... | Percentage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 461023,
"end": 461472
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AcceptTopicSuggestion"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "topic")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | AcceptTopicSuggestionPayload |
python | openai__gym | gym/error.py | {
"start": 4929,
"end": 5269
} | class ____(Exception):
"""Raised when an asynchronous `reset`, or `step` is not running, but `reset_wait`, or `step_wait` (respectively) is called."""
def __init__(self, message: str, name: str):
"""Initialises the exception with name attributes."""
super().__init__(message)
self.name =... | NoAsyncCallError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.