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 | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/asyncio/session.py | {
"start": 6413,
"end": 54315
} | class ____(ReversibleProxy[Session]):
"""Asyncio version of :class:`_orm.Session`.
The :class:`_asyncio.AsyncSession` is a proxy for a traditional
:class:`_orm.Session` instance.
The :class:`_asyncio.AsyncSession` is **not safe for use in concurrent
tasks.**. See :ref:`session_faq_threadsafe` for... | AsyncSession |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 15744,
"end": 16447
} | class ____(Expr):
"""Baseclass for all unary expressions."""
fields = ("node",)
node: Expr
operator: str
abstract = True
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded ... | UnaryExpr |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py | {
"start": 13005,
"end": 17953
} | class ____(quantize_model_test_base.QuantizedModelTest):
def test_preserving_input_output_tensor_names(self):
class MultiSignatureModel(module.Module):
@def_function.function(
input_signature=[
tensor_spec.TensorSpec(
name='input', shape=[32], dtype=dtypes.float32... | TensorNamePreservationTest |
python | huggingface__transformers | tests/models/seed_oss/test_modeling_seed_oss.py | {
"start": 1141,
"end": 1274
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = SeedOssModel
@require_torch
| SeedOssModelTester |
python | TheAlgorithms__Python | data_structures/binary_tree/floor_and_ceiling.py | {
"start": 406,
"end": 2110
} | class ____:
key: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield self.key
if self.right:
yield from self.right
def __len__(self) -> int:
return sum(1 for _ i... | Node |
python | allegroai__clearml | clearml/backend_api/session/response.py | {
"start": 158,
"end": 301
} | class ____(jsonmodels.fields.BaseField):
"""String field."""
types = (
float,
six.string_types,
)
| FloatOrStringField |
python | pypa__pip | src/pip/_vendor/distlib/__init__.py | {
"start": 223,
"end": 625
} | class ____(Exception):
pass
try:
from logging import NullHandler
except ImportError: # pragma: no cover
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.lock = None
... | DistlibException |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vision.py | {
"start": 16270,
"end": 18064
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.vision.CloudVisionHook")
def test_minimal_green_path(self, mock_hook):
op = CloudVisionDetectTextOperator(image=DETECT_TEST_IMAGE, task_id="id")
op.execute(context=None)
mock_hook.assert_called_once_with(
gcp_c... | TestCloudVisionDetectTextOperator |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/executors/batch/utils.py | {
"start": 1396,
"end": 1694
} | class ____:
"""Represents a Batch job that is queued. The job will be run in the next heartbeat."""
key: TaskInstanceKey
command: CommandType
queue: str
executor_config: ExecutorConfigType
attempt_number: int
next_attempt_time: datetime.datetime
@dataclass
| BatchQueuedJob |
python | wandb__wandb | wandb/vendor/pygments/lexers/typoscript.py | {
"start": 1965,
"end": 3208
} | class ____(RegexLexer):
"""
Lexer that highlights markers, constants and registers within html tags.
.. versionadded:: 2.2
"""
name = 'TypoScriptHtmlData'
aliases = ['typoscripthtmldata']
tokens = {
'root': [
# INCLUDE_TYPOSCRIPT
(r'(INCLUDE_TYPOSCRIPT)', N... | TypoScriptHtmlDataLexer |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 10257,
"end": 10507
} | class ____(object):
"""
'undef': a value for undefined values.
"""
def __new__(cls):
try:
return Undefined
except NameError:
return object.__new__(_Undefined)
Undefined = _Undefined()
| _Undefined |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/metadata.py | {
"start": 733,
"end": 855
} | class ____(DistlibException):
"""Attempt to read or write metadata fields that are conflictual."""
| MetadataConflictError |
python | huggingface__transformers | tests/models/mask2former/test_image_processing_mask2former.py | {
"start": 1520,
"end": 6289
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
min_resolution=30,
max_resolution=400,
size=None,
do_resize=True,
do_normalize=True,
image_mean=[0.5, 0.5, 0.5],
image_std=[0.5, 0.5, 0.5],
num_labels... | Mask2FormerImageProcessingTester |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/12_Proximal_Policy_Optimization/DPPO.py | {
"start": 1164,
"end": 4577
} | class ____(object):
def __init__(self):
self.sess = tf.Session()
self.tfs = tf.placeholder(tf.float32, [None, S_DIM], 'state')
# critic
l1 = tf.layers.dense(self.tfs, 100, tf.nn.relu)
self.v = tf.layers.dense(l1, 1)
self.tfdc_r = tf.placeholder(tf.float32, [None, 1],... | PPO |
python | geekcomputers__Python | brickout-game/brickout-game.py | {
"start": 3470,
"end": 5316
} | class ____(pygame.sprite.Sprite):
def __init__(self, screen, width, height, x, y):
self.__screen = screen
self._width = width
self._height = height
self._xLoc = x
self._yLoc = y
w, h = pygame.display.get_surface().get_size()
self.__W = w
self.__H = h
... | Brick |
python | getsentry__sentry | src/sentry/rules/actions/base.py | {
"start": 937,
"end": 1682
} | class ____(RuleBase, abc.ABC):
rule_type = "action/event"
@abc.abstractmethod
def after(
self, event: GroupEvent, notification_uuid: str | None = None
) -> Generator[CallbackFuture]:
"""
Executed after a Rule matches.
Should yield CallBackFuture instances which will the... | EventAction |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 2052,
"end": 2083
} | class ____[**P = []]: ...
| ClassP3 |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/properties.py | {
"start": 1968,
"end": 2261
} | class ____(DerivedTaintedSetter):
@property
def my_property(self) -> str:
return ""
@my_property.setter
def my_property(self, value) -> None:
return None
def sets_tainted_value(t: TaintedGetterAndSetter) -> None:
t.my_property = _test_source()
| GrandDerived |
python | doocs__leetcode | solution/2500-2599/2502.Design Memory Allocator/Solution2.py | {
"start": 0,
"end": 814
} | class ____:
def __init__(self, n: int):
self.sl = SortedList([(-1, -1), (n, n)])
self.d = defaultdict(list)
def allocate(self, size: int, mID: int) -> int:
for (_, s), (e, _) in pairwise(self.sl):
s, e = s + 1, e - 1
if e - s + 1 >= size:
self.sl.... | Allocator |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataplex.py | {
"start": 25516,
"end": 26489
} | class ____:
@mock.patch(HOOK_STR)
def test_execute(self, hook_mock):
op = DataplexCreateOrUpdateDataProfileScanOperator(
task_id=TASK_ID,
project_id=PROJECT_ID,
region=REGION,
data_scan_id=DATA_SCAN_ID,
body={},
api_version=API_VERS... | TestDataplexCreateDataProfileScanOperator |
python | PyCQA__pylint | tests/functional/u/unpacking/unpacking_non_sequence.py | {
"start": 2717,
"end": 3768
} | class ____(TestBase):
'child class that overrides `test` method'
def __init__(self):
# no error should be emitted here as `test` is overridden in this class
(self.aaa, self.bbb, self.ccc) = self.test(None)
@staticmethod
def test(data):
'overridden implementation'
return ... | Test |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/snowflake_datasource.py | {
"start": 9050,
"end": 9321
} | class ____(pydantic.UrlError):
"""
Custom Pydantic error for missing path in SnowflakeDsn.
"""
code = "url.path"
msg_template = "URL path missing database/schema"
def __init__(self, **ctx: Any) -> None:
super().__init__(**ctx)
| UrlPathError |
python | kamyu104__LeetCode-Solutions | Python/word-search.py | {
"start": 96,
"end": 1189
} | class ____(object):
# @param board, a list of lists of 1 length string
# @param word, a string
# @return a boolean
def exist(self, board, word):
visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))]
for i in xrange(len(board)):
for j in xrange(len(bo... | Solution |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/session.py | {
"start": 2087,
"end": 2277
} | class ____(SessionExemptMixin, SecureCookieSessionInterface):
"""Session interface that exempts some routes and stores session data in a signed cookie."""
| AirflowSecureCookieSessionInterface |
python | spyder-ide__spyder | spyder/plugins/application/container.py | {
"start": 1646,
"end": 1766
} | class ____:
SpyderLogSection = "spyder_log_section"
LSPLogsSection = "lsp_logs_section"
# Actions
| LogsMenuSections |
python | openai__openai-python | src/openai/resources/beta/chatkit/sessions.py | {
"start": 10527,
"end": 10853
} | class ____:
def __init__(self, sessions: Sessions) -> None:
self._sessions = sessions
self.create = _legacy_response.to_raw_response_wrapper(
sessions.create,
)
self.cancel = _legacy_response.to_raw_response_wrapper(
sessions.cancel,
)
| SessionsWithRawResponse |
python | doocs__leetcode | solution/2300-2399/2355.Maximum Number of Books You Can Take/Solution.py | {
"start": 0,
"end": 695
} | class ____:
def maximumBooks(self, books: List[int]) -> int:
nums = [v - i for i, v in enumerate(books)]
n = len(nums)
left = [-1] * n
stk = []
for i, v in enumerate(nums):
while stk and nums[stk[-1]] >= v:
stk.pop()
if stk:
... | Solution |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/visitors/query_expression.py | {
"start": 3094,
"end": 7194
} | class ____(QueryExpressionVisitor[QueryExpression]):
"""
Visitor that recursively validates the `QueryExpression` of the new endpoint.
"""
def __init__(self):
self._query_namespace = None
self._query_entity = None
self._query_group_bys = None
self._query_group_bys_stack:... | QueryValidationV2Visitor |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 14865,
"end": 15619
} | class ____(Expr):
"""Baseclass for all binary expressions."""
fields = ("left", "right")
left: Expr
right: Expr
operator: str
abstract = True
def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operato... | BinExpr |
python | ray-project__ray | rllib/env/tests/test_multi_agent_episode.py | {
"start": 324,
"end": 4928
} | class ____(MultiAgentEnv):
def __init__(self, truncate=True):
super().__init__()
self.t = 0
self._agent_ids = {"agent_" + str(i) for i in range(10)}
self.observation_space = gym.spaces.Dict(
{agent_id: gym.spaces.Discrete(201) for agent_id in self._agent_ids}
)
... | MultiAgentTestEnv |
python | django__django | tests/xor_lookups/tests.py | {
"start": 94,
"end": 2746
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.numbers = [Number.objects.create(num=i) for i in range(10)]
def test_filter(self):
self.assertCountEqual(
Number.objects.filter(num__lte=7) ^ Number.objects.filter(num__gte=3),
self.numbers[:3] + self.num... | XorLookupsTests |
python | giampaolo__psutil | tests/test_bsd.py | {
"start": 8129,
"end": 16913
} | class ____(PsutilTestCase):
@staticmethod
def parse_swapinfo():
# the last line is always the total
output = sh("swapinfo -k").splitlines()[-1]
parts = re.split(r'\s+', output)
if not parts:
raise ValueError(f"Can't parse swapinfo: {output}")
# the size is i... | FreeBSDSystemTestCase |
python | pytest-dev__pytest | src/_pytest/_code/code.py | {
"start": 52124,
"end": 55836
} | class ____(TerminalRepr):
args: Sequence[tuple[str, object]]
def toterminal(self, tw: TerminalWriter) -> None:
if self.args:
linesofar = ""
for name, value in self.args:
ns = f"{name} = {value}"
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
... | ReprFuncArgs |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/utils/eks_test_constants.py | {
"start": 3851,
"end": 4191
} | class ____:
"""All possible inputs for creating an EKS Cluster."""
REQUIRED: list[tuple[str, Any]] = [ROLE_ARN, RESOURCES_VPC_CONFIG]
OPTIONAL: list[tuple[str, Any]] = [
CLIENT_REQUEST_TOKEN,
ENCRYPTION_CONFIG,
LOGGING,
KUBERNETES_NETWORK_CONFIG,
TAGS,
VERSIO... | ClusterInputs |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/LabelItem.py | {
"start": 228,
"end": 5368
} | class ____(GraphicsWidgetAnchor, GraphicsWidget):
"""
GraphicsWidget displaying text.
Used mainly as axis labels, titles, etc.
Note: To display text inside a scaled view (ViewBox, PlotWidget, etc) use TextItem
"""
def __init__(self, text=' ', parent=None, angle=0, **args):
... | LabelItem |
python | google__pytype | pytype/errors/error_printer.py | {
"start": 4227,
"end": 9435
} | class ____:
"""Pretty printer for some specific matcher error types."""
def __init__(self, pp: pretty_printer_base.PrettyPrinterBase):
self._pp = pp
def _print_protocol_error(self, error: error_types.ProtocolError) -> str:
"""Pretty-print the protocol error."""
convert = self._pp.ctx.pytd_convert
... | MatcherErrorPrinter |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/kinesis_analytics.py | {
"start": 3355,
"end": 6649
} | class ____(KinesisAnalyticsV2BaseSensor):
"""
Waits for AWS Managed Service for Apache Flink application to start.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:KinesisAnalyticsV2StartApplicationCompletedSensor`
:param applica... | KinesisAnalyticsV2StartApplicationCompletedSensor |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_sts.py | {
"start": 884,
"end": 1067
} | class ____:
def test_get_conn_returns_a_boto3_connection(self):
hook = StsHook(aws_conn_id="aws_default", region_name="us-east-1")
assert hook.conn is not None
| TestSTS |
python | django__django | tests/serializers/models/base.py | {
"start": 2166,
"end": 2351
} | class ____(models.Model):
name = models.CharField(max_length=20, primary_key=True)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
| Actor |
python | neetcode-gh__leetcode | python/0450-delete-node-in-a-bst.py | {
"start": 192,
"end": 922
} | class ____:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return root
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)
... | Solution |
python | getsentry__sentry | src/sentry/auth/providers/saml2/rippling/provider.py | {
"start": 1049,
"end": 1534
} | class ____(SAML2Provider):
name = "Rippling"
key = "rippling"
def get_saml_setup_pipeline(self) -> list[AuthView]:
return [SelectIdP(), WaitForCompletion()]
def attribute_mapping(self) -> dict[str, str]:
return {
Attributes.IDENTIFIER: "user_id",
Attributes.USER... | RipplingSAML2Provider |
python | Textualize__textual | src/textual/demo/game.py | {
"start": 9430,
"end": 9725
} | class ____(ModalScreen):
"""Modal screen containing the dialog."""
CSS = """
GameDialogScreen {
align: center middle;
}
"""
BINDINGS = [("escape", "dismiss")]
def compose(self) -> ComposeResult:
yield GameDialog()
| GameDialogScreen |
python | google__jax | tests/extend_test.py | {
"start": 4083,
"end": 4433
} | class ____(jtu.JaxTestCase):
def test_unknown_platform_error(self):
with self.assertRaisesRegex(
NotImplementedError,
"Registering an MLIR lowering rule for primitive .+ for an unknown "
"platform foo. Known platforms are: .+."):
mlir.register_lowering(prim=None, rule=None, platform... | MlirRegisterLoweringTest |
python | rapidsai__cudf | python/cudf/cudf/core/buffer/exposure_tracked_buffer.py | {
"start": 382,
"end": 3610
} | class ____(Buffer):
"""An exposure tracked buffer.
Parameters
----------
owner
The owning exposure tracked buffer this refers to.
offset
The offset relative to the start memory of owner (in bytes).
size
The size of the slice (in bytes)
"""
def __init__(
... | ExposureTrackedBuffer |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 66228,
"end": 67408
} | class ____(nn.Module):
def __init__(self, config: EdgeTamVideoPromptEncoderConfig):
super().__init__()
self.scale = config.scale
positional_embedding = self.scale * torch.randn((2, config.hidden_size // 2))
self.register_buffer("positional_embedding", positional_embedding)
def f... | EdgeTamVideoPositionalEmbedding |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 2056,
"end": 2187
} | class ____(BaseModel):
annotations: list[Annotation] | None = None
text: str
type: str = "output_text"
| ResponseOutputText |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 1957,
"end": 2410
} | class ____(vLLMCompletionRequest):
model_config = ConfigDict(arbitrary_types_allowed=True)
request_id: str = Field(
default_factory=lambda: f"{random_uuid()}",
description=(
"The request_id related to this request. If the caller does "
"not set it, a random_uuid will be ... | CompletionRequest |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 141262,
"end": 143082
} | class ____(Request):
"""
Moves all the source project's contents to the destination project and remove the source project
:param project: Project id
:type project: str
:param destination_project: The ID of the destination project
:type destination_project: str
"""
_service = "projects"... | MergeRequest |
python | django__django | tests/file_uploads/uploadhandler.py | {
"start": 1043,
"end": 1232
} | class ____(FileUploadHandler):
"""A handler that raises an exception."""
def receive_data_chunk(self, raw_data, start):
raise CustomUploadError("Oops!")
| ErroringUploadHandler |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/check_operators.py | {
"start": 6037,
"end": 7284
} | class ____(ChecksAutomationCondition):
@property
def base_name(self) -> str:
return "ALL_CHECKS_MATCH"
@property
def operator_type(self) -> OperatorType:
return "and"
async def evaluate(self, context: AutomationContext[AssetKey]) -> AutomationResult[AssetKey]: # pyright: ignore[re... | AllChecksCondition |
python | huggingface__transformers | src/transformers/models/univnet/modeling_univnet.py | {
"start": 1247,
"end": 1698
} | class ____(ModelOutput):
r"""
waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Batched 1D (mono-channel) output audio waveforms.
waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
The batched length in samples of each unpadded waveform in `waveforms`.
... | UnivNetModelOutput |
python | run-llama__llama_index | llama-index-core/llama_index/core/prompts/mixin.py | {
"start": 362,
"end": 3300
} | class ____(ABC):
"""
Prompt mixin.
This mixin is used in other modules, like query engines, response synthesizers.
This shows that the module supports getting, setting prompts,
both within the immediate module as well as child modules.
"""
def _validate_prompts(
self,
prom... | PromptMixin |
python | ray-project__ray | rllib/offline/estimators/tests/test_dr_learning.py | {
"start": 215,
"end": 6525
} | class ____(unittest.TestCase):
"""Learning tests for the DoublyRobust estimator.
Generates three GridWorldWallPolicy policies and batches with epsilon = 0.2, 0.5,
and 0.8 respectively using `get_cliff_walking_wall_policy_and_data`.
Tests that the estimators converge on all eight combinations of evalu... | TestDRLearning |
python | walkccc__LeetCode | solutions/1608. Special Array With X Elements Greater Than or Equal X/1608.py | {
"start": 0,
"end": 297
} | class ____:
def specialArray(self, nums: list[int]) -> int:
nums.sort()
if nums[0] >= len(nums):
return len(nums)
for i, (a, b) in enumerate(itertools.pairwise(nums)):
count = len(nums) - i - 1
if a < count and b >= count:
return count
return -1
| Solution |
python | PyCQA__pycodestyle | tests/test_api.py | {
"start": 306,
"end": 16729
} | class ____(unittest.TestCase):
"""Test the public methods."""
def setUp(self):
self._saved_stdout = sys.stdout
self._saved_stderr = sys.stderr
self._saved_checks = pycodestyle._checks
sys.stdout = io.StringIO()
sys.stderr = io.StringIO()
pycodestyle._checks = {
... | APITestCase |
python | PrefectHQ__prefect | src/prefect/cli/events.py | {
"start": 568,
"end": 6076
} | class ____(str, Enum):
json = "json"
text = "text"
@events_app.command()
async def stream(
format: StreamFormat = typer.Option(
StreamFormat.json, "--format", help="Output format (json or text)"
),
output_file: str = typer.Option(
None, "--output-file", help="File to write events t... | StreamFormat |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/yaml_utils/sample_yaml.py | {
"start": 3735,
"end": 5461
} | class ____(yaml.SafeDumper):
def increase_indent(self, flow=False, *args, **kwargs):
# makes the output somewhat prettier by forcing lists to be indented
return super().increase_indent(flow=flow, indentless=False)
def write_line_break(self) -> None: # pyright: ignore[reportIncompatibleMethodOv... | ComponentDumper |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 253307,
"end": 253653
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("check_run", "client_mutation_id")
check_run = sgqlc.types.Field("CheckRun", graphql_name="checkRun")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutati... | CreateCheckRunPayload |
python | miyuchina__mistletoe | test/test_latex_renderer.py | {
"start": 192,
"end": 5154
} | class ____(TestCase):
def setUp(self):
self.renderer = LaTeXRenderer()
self.renderer.render_inner = mock.Mock(return_value='inner')
self.renderer.__enter__()
self.addCleanup(self.renderer.__exit__, None, None, None)
def _test_token(self, token_name, expected_output, children=Tru... | TestLaTeXRenderer |
python | gevent__gevent | src/gevent/resolver/__init__.py | {
"start": 3444,
"end": 10760
} | class ____(object):
HOSTNAME_ENCODING = 'idna'
_LOCAL_HOSTNAMES = (
b'localhost',
b'ip6-localhost',
b'::1',
b'127.0.0.1',
)
_LOCAL_AND_BROADCAST_HOSTNAMES = _LOCAL_HOSTNAMES + (
b'255.255.255.255',
b'<broadcast>',
)
EAI_NONAME_MSG = (
'... | AbstractResolver |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/relativity/relativity.py | {
"start": 24477,
"end": 25007
} | class ____(pg.ItemGroup):
def __init__(self, sim):
pg.ItemGroup.__init__(self)
self.sim = sim
self.clocks = sim.clocks
self.items = {}
for name, cl in self.clocks.items():
item = ClockItem(cl)
self.addItem(item)
self.items[name] = ... | Animation |
python | apache__avro | lang/py/avro/schema.py | {
"start": 12136,
"end": 12945
} | class ____(LogicalSchema):
def __init__(self, precision, scale=0, max_precision=0):
if not isinstance(precision, int) or precision <= 0:
raise avro.errors.IgnoredLogicalType(f"Invalid decimal precision {precision}. Must be a positive integer.")
if precision > max_precision:
... | DecimalLogicalSchema |
python | numba__numba | numba/tests/test_record_dtype.py | {
"start": 41430,
"end": 57298
} | class ____(TestCase):
def get_cfunc(self, pyfunc, argspec):
return njit(argspec)(pyfunc)
def test_record_write_array(self):
# Testing writing to a 1D array within a structured type
nbval = np.recarray(1, dtype=recordwitharray)
nbrecord = numpy_support.from_dtype(recordwitharra... | TestNestedArrays |
python | getsentry__sentry | tests/sentry/backup/test_exports.py | {
"start": 5390,
"end": 20041
} | class ____(ExportTestCase):
"""
Ensures that only models with the allowed relocation scopes are actually exported.
"""
@staticmethod
def verify_model_inclusion(data: Any, scope: ExportScope) -> None:
"""
Ensure all in-scope models are included, and that no out-of-scope models are in... | ScopingTests |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/shell_a/package.py | {
"start": 216,
"end": 541
} | class ____(Package):
"""Simple package with one dependency for shell tests"""
homepage = "http://www.example.com"
url = "http://www.example.com/shell-a-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
version("2.0", md5="abcdef0123456789abcdef0123456789")
depends_on("shell-b... | ShellA |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 10911,
"end": 11355
} | class ____(PlotEvent):
''' Announce the start of "interactive level-of-detail" mode on a plot.
During interactive actions such as panning or zooming, Bokeh can
optionally, temporarily draw a reduced set of the data, in order to
maintain high interactive rates. This is referred to as interactive
Lev... | LODStart |
python | TheAlgorithms__Python | graphs/directed_and_undirected_weighted_graph.py | {
"start": 185,
"end": 8242
} | class ____:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
if self.graph.get(u):
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
... | DirectedGraph |
python | streamlit__streamlit | lib/tests/streamlit/components/v2/test_bidi_component.py | {
"start": 56828,
"end": 75992
} | class ____(DeltaGeneratorTestCase):
"""Verify that per-event *trigger* callbacks fire only for their event."""
COMPONENT_NAME = "trigger_component"
# ------------------------------------------------------------------
# Test lifecycle helpers
# ------------------------------------------------------... | BidiComponentTriggerCallbackTest |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 9434,
"end": 10238
} | class ____(BaseActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.SLACK
@property
def required_fields(self) -> list[str]:
return [
ACTION_FIELD_MAPPINGS[ActionType.SLACK][
ActionFieldMappingKeys.INTEGRATION_ID_KEY.value
... | SlackActionTranslator |
python | huggingface__transformers | tests/models/imagegpt/test_modeling_imagegpt.py | {
"start": 12749,
"end": 13805
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small") if is_vision_available() else None
@slow
def test_inference_causal_lm_head(self):
model = ImageGPTForCausalImageModeling.from_pretrai... | ImageGPTModelIntegrationTest |
python | python-openxml__python-docx | tests/image/test_gif.py | {
"start": 203,
"end": 960
} | class ____:
def it_can_construct_from_a_gif_stream(self, Gif__init__):
cx, cy = 42, 24
bytes_ = b"filler\x2a\x00\x18\x00"
stream = io.BytesIO(bytes_)
gif = Gif.from_stream(stream)
Gif__init__.assert_called_once_with(ANY, cx, cy, 72, 72)
assert isinstance(gif, Gif)
... | DescribeGif |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchMapping1.py | {
"start": 3369,
"end": 3442
} | class ____(TypedDict):
type: Literal["Int"]
int_value: int
| IntValue |
python | pytorch__pytorch | test/dynamo/test_aot_compile.py | {
"start": 937,
"end": 2480
} | class ____(torch._dynamo.aot_compile.SerializableCallable):
def __init__(self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]):
self.gm = gm
self.example_inputs = example_inputs
@classmethod
def serialize_compile_artifacts(cls, fn) -> bytes:
import sympy
from ... | CustomCompiledFunction |
python | pennersr__django-allauth | allauth/headless/usersessions/views.py | {
"start": 366,
"end": 1092
} | class ____(AuthenticatedAPIView):
input_class = {"DELETE": SelectSessionsInput}
def delete(self, request, *args, **kwargs):
sessions = self.input.cleaned_data["sessions"]
flows.sessions.end_sessions(request, sessions)
if self.request.user.is_authenticated:
return self._respo... | SessionsView |
python | sphinx-doc__sphinx | sphinx/writers/manpage.py | {
"start": 1162,
"end": 2349
} | class ____:
"""Flatten nested inline nodes:
Before:
<strong>foo=<emphasis>1</emphasis>
&bar=<emphasis>2</emphasis></strong>
After:
<strong>foo=</strong><emphasis>var</emphasis>
<strong>&bar=</strong><emphasis>2</emphasis>
"""
def __init__(self, document: nodes.docum... | NestedInlineTransform |
python | ray-project__ray | rllib/utils/tests/test_framework_agnostic_components.py | {
"start": 1195,
"end": 1397
} | class ____(DummyComponent, metaclass=ABCMeta):
"""Used for testing `from_config()`."""
@abstractmethod
def some_abstract_method(self):
raise NotImplementedError
| AbstractDummyComponent |
python | scipy__scipy | scipy/optimize/tests/test_least_squares.py | {
"start": 3300,
"end": 4441
} | class ____:
"""Provide data and function for exponential fitting in the form
y = a + exp(b * x) + noise."""
def __init__(self, a, b, noise, n_outliers=1, x_range=(-1, 1),
n_points=11, rng=None):
rng = np.random.default_rng(rng)
self.m = n_points
self.n = 2
... | ExponentialFittingProblem |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/units/__init__.py | {
"start": 1360,
"end": 11839
} | class ____:
"""Contexts that unit tests run in based on the type of content."""
controller = 'controller'
modules = 'modules'
module_utils = 'module_utils'
def command_units(args: UnitsConfig) -> None:
"""Run unit tests."""
handle_layout_messages(data_context().content.unit_messages)
cha... | TestContext |
python | sphinx-doc__sphinx | sphinx/ext/graphviz.py | {
"start": 1374,
"end": 2871
} | class ____:
"""A manipulator for clickable map file of graphviz."""
maptag_re = re.compile('<map id="(.*?)"')
href_re = re.compile('href=".*?"')
def __init__(self, filename: str, content: str, dot: str = '') -> None:
self.id: str | None = None
self.filename = filename
self.cont... | ClickableMapDefinition |
python | google__pytype | pytype/abstract/_instances.py | {
"start": 5842,
"end": 6428
} | class ____(_instance_base.Instance):
"""A representation of instances of coroutine."""
def __init__(
self, ctx: "context.Context", ret_var: cfg.Variable, node: cfg.CFGNode
) -> None:
super().__init__(ctx.convert.coroutine_type, ctx)
self.merge_instance_type_parameter(
node, abstract_utils.T... | Coroutine |
python | cython__cython | Cython/Plex/Transitions.py | {
"start": 148,
"end": 7141
} | class ____:
"""
A TransitionMap maps an input event to a set of states.
An input event is one of: a range of character codes,
the empty string (representing an epsilon move), or one
of the special symbols BOL, EOL, EOF.
For characters, this implementation compactly represents
the map by mea... | TransitionMap |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py | {
"start": 20595,
"end": 23587
} | class ____(CheckDocumentationContent):
name = "Main Source Section of the documentation follows our guidelines"
expected_section_index = 0
@property
def description(self) -> str:
template = TemplateContent("CONNECTOR_NAME_FROM_METADATA").section("CONNECTOR_NAME_FROM_METADATA")
if templ... | CheckSourceSectionContent |
python | getsentry__sentry | tests/sentry/web/frontend/test_organization_auth_settings.py | {
"start": 5563,
"end": 28886
} | class ____(AuthProviderTestCase):
def enroll_user_and_require_2fa(self, user, organization):
TotpInterface().enroll(user)
with assume_test_silo_mode(SiloMode.REGION):
organization.update(flags=models.F("flags").bitor(Organization.flags.require_2fa))
assert organization.flags.requ... | OrganizationAuthSettingsTest |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-deeplake-deepmemory-retriever/llama_index/packs/deeplake_deepmemory_retriever/base.py | {
"start": 451,
"end": 2374
} | class ____(BaseLlamaPack):
"""DeepMemory retriever pack."""
def __init__(
self,
dataset_path: str = "llama_index",
token: Optional[str] = None,
read_only: Optional[bool] = False,
overwrite: bool = False,
verbose: bool = True,
nodes: Optional[List[TextNode... | DeepMemoryRetrieverPack |
python | pytorch__pytorch | benchmarks/fastrnns/test_bench.py | {
"start": 827,
"end": 1563
} | class ____:
# See 'modeldef' fixture, which provides the things to benchmark
def test_forward(self, modeldef, benchmark):
benchmark(cuda_sync, modeldef.forward, *modeldef.inputs)
def test_backward(self, modeldef, benchmark):
backward_input = modeldef.forward(*modeldef.inputs)
if mod... | TestBenchNetwork |
python | django__django | tests/sphinx/testdata/package/module.py | {
"start": 232,
"end": 434
} | class ____(object):
def __init__(self):
pass
def my_method(self):
pass
@cached_property
def my_cached_property(self):
pass
def my_function(self):
pass
| MyClass |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/test_dataloaders.py | {
"start": 22928,
"end": 24128
} | class ____(Dataset):
# this dataset uses numpy instead of torch to produce random numbers
size = 16
def __getitem__(self, index):
return numpy.random.randint(0, 100, 3)
def __len__(self):
return self.size
def _user_worker_init_fn(_):
pass
def test_auto_add_worker_init_fn():
... | NumpyRandomDataset |
python | weaviate__weaviate-python-client | weaviate/util.py | {
"start": 25019,
"end": 25291
} | class ____(uuid_lib.UUID):
def __init__(self, hex_: int) -> None:
object.__setattr__(self, "int", hex_)
object.__setattr__(self, "is_safe", uuid_lib.SafeUUID.unknown)
def escape_string(value: str) -> str:
return quote(value, safe="")
| _WeaviateUUIDInt |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 29701,
"end": 33808
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("seconds", -5) == "5 sekundami"
assert self.locale._format_timeframe("seconds", -2) == "2 sekundami"
assert self.locale._format_timeframe("second", -1) == "sekundou"
assert self.locale._format_timeframe... | TestSlovakLocale |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 21109,
"end": 25096
} | class ____(SetupData):
def test_add_columns1(self, table_types):
self._setup(table_types)
t = table_types.Table()
t.add_columns([self.a, self.b, self.c])
assert t.colnames == ["a", "b", "c"]
def test_add_columns2(self, table_types):
self._setup(table_types)
t = t... | TestAddColumns |
python | pypa__setuptools | setuptools/_vendor/more_itertools/more.py | {
"start": 75537,
"end": 83572
} | class ____:
"""An extension of :func:`itertools.islice` that supports negative values
for *stop*, *start*, and *step*.
>>> iterable = iter('abcdefgh')
>>> list(islice_extended(iterable, -4, -1))
['e', 'f', 'g']
Slices with negative values require some caching of *iterable*, but thi... | islice_extended |
python | pytorch__pytorch | tools/test/test_codegen.py | {
"start": 8414,
"end": 11895
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.selector = SelectiveBuilder.get_nop_selector()
self.custom_native_function, _ = NativeFunction.from_yaml(
{"func": "custom::func() -> bool"},
loc=Location(__file__, 1),
valid_tags=set(),
)
... | TestGenSchemaRegistration |
python | pytorch__pytorch | torch/ao/nn/intrinsic/qat/modules/conv_fused.py | {
"start": 26990,
"end": 28203
} | class ____(ConvBn3d):
r"""
A ConvBnReLU3d module is a module fused from Conv3d, BatchNorm3d and ReLU,
attached with FakeQuantize modules for weight,
used in quantization aware training.
We combined the interface of :class:`torch.nn.Conv3d` and
:class:`torch.nn.BatchNorm3d` and :class:`torch.nn.... | ConvBnReLU3d |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 445,
"end": 690
} | class ____(Place):
# An explicit link to the parent (we can control the attribute name).
parent = models.OneToOneField(
Place, models.CASCADE, primary_key=True, parent_link=True
)
capacity = models.IntegerField()
| ParkingLot |
python | huggingface__transformers | src/transformers/models/mgp_str/modeling_mgp_str.py | {
"start": 9088,
"end": 10519
} | class ____(nn.Module):
def __init__(self, config: MgpstrConfig):
super().__init__()
# stochastic depth decay rule
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers, device="cpu")]
self.blocks = nn.Sequential(
*[MgpstrLayer(config=... | MgpstrEncoder |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_schemas.py | {
"start": 5888,
"end": 7253
} | class ____:
async def test_delete_block_schema(self, session, client, block_schemas):
schema_id = block_schemas[0].id
response = await client.delete(f"/block_schemas/{schema_id}")
assert response.status_code == status.HTTP_204_NO_CONTENT
session.expire_all()
result = await ... | TestDeleteBlockSchema |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 8510,
"end": 10935
} | class ____:
"""
Feature: Read data directly from Dataset into a Numpy array
"""
@pytest.mark.parametrize(
'source_shape,dest_shape,source_sel,dest_sel',
[
((100,), (100,), np.s_[0:10], np.s_[50:60]),
((70,), (100,), np.s_[50:60], np.s_[90:]),
((3... | TestReadDirectly |
python | networkx__networkx | networkx/generators/tests/test_directed.py | {
"start": 4593,
"end": 6020
} | class ____:
"""Unit tests for the
:func:`~networkx.generators.directed.random_uniform_k_out_graph`
function.
"""
def test_regularity(self):
"""Tests that the generated graph is `k`-out-regular."""
n = 10
k = 3
G = random_uniform_k_out_graph(n, k)
assert all(... | TestUniformRandomKOutGraph |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 5669,
"end": 6093
} | class ____(Partial):
def _delayedRender(self, request):
abort = getarg(request, b"abort", 0, type_=int)
request.write(b"this connection will be dropped\n")
tr = request.channel.transport
try:
if abort and hasattr(tr, "abortConnection"):
tr.abortConnection(... | Drop |
python | bokeh__bokeh | src/bokeh/models/widgets/indicators.py | {
"start": 1525,
"end": 1940
} | class ____(Widget):
""" Abstract base class for indicator components.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
#-----------------------------------------------------------------------------
# Ge... | Indicator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.