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 | scikit-image__scikit-image | benchmarks/benchmark_registration.py | {
"start": 622,
"end": 1121
} | class ____:
"""Benchmark for registration routines in scikit-image."""
param_names = ["dtype"]
params = [(np.float32, np.float64)]
def setup(self, *args):
I0, I1, _ = data.stereo_motorcycle()
self.I0 = rgb2gray(I0)
self.I1 = rgb2gray(I1)
def time_tvl1(self, dtype):
... | RegistrationSuite |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 272649,
"end": 273155
} | class ____(sgqlc.types.Input):
"""Ways in which lists of releases can be ordered upon return."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(ReleaseOrderField), graphql_name="field")
"""The field in which to order releases by.""... | ReleaseOrder |
python | ray-project__ray | rllib/env/wrappers/atari_wrappers.py | {
"start": 1464,
"end": 1707
} | class ____(gym.RewardWrapper):
def __init__(self, env):
gym.RewardWrapper.__init__(self, env)
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
@PublicAPI
| ClipRewardEnv |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/rate_limiting.py | {
"start": 2894,
"end": 13466
} | class ____(ErrorHandler):
def __init__(self, stream_name: str = "<unknown stream>", sobject_options: Optional[Mapping[str, Any]] = None) -> None:
self._stream_name = stream_name
self._sobject_options: Mapping[str, Any] = sobject_options or {}
@property
def max_retries(self) -> Optional[int]... | SalesforceErrorHandler |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/repartition.py | {
"start": 700,
"end": 2307
} | class ____(IR):
"""
Repartition a DataFrame.
Notes
-----
Repartitioning means that we are not modifying any
data, nor are we reordering or shuffling rows. We
are only changing the overall partition count. For
now, we only support an N -> [1...N] repartitioning
(inclusive). The outpu... | Repartition |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 100935,
"end": 102438
} | class ____:
@pytest.fixture(scope='function')
def rng(self):
return np.random.default_rng(1234)
@pytest.mark.parametrize("dist", [stats.gumbel_r, stats.gumbel_l])
@pytest.mark.parametrize("loc_rvs", [-1, 0, 1])
@pytest.mark.parametrize("scale_rvs", [.1, 1, 5])
@pytest.mark.parametrize('... | TestGumbel_r_l |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/base_test.py | {
"start": 2630,
"end": 4742
} | class ____(trt_test.TfTrtIntegrationTestBase):
def GraphFn(self, inp):
"""Create a graph containing multiple segment."""
dtype = inp.dtype
conv_filter = constant_op.constant(
[[[[1., 0.5, 4., 6., 0.5, 1.], [1., 0.5, 1., 1., 0.5, 1.]]]],
name="weights",
dtype=dtype)
conv = nn.c... | SimpleMultiEnginesTest |
python | numba__llvmlite | llvmlite/binding/orcjit.py | {
"start": 6749,
"end": 8036
} | class ____(ffi.ObjectRef):
"""
A resource tracker is created for each loaded JIT library and keeps the
module alive.
OrcJIT supports unloading libraries that are no longer used. This resource
tracker should be stored in any object that reference functions or constants
for a JITted library. When... | ResourceTracker |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 19129,
"end": 19218
} | class ____(TestMaskedArrayBroadcast, LongitudeSetup):
pass
| TestMaskedLongitudeBroadcast |
python | pypa__warehouse | warehouse/static.py | {
"start": 170,
"end": 2989
} | class ____:
def __init__(self):
self.manifests = {}
def __call__(self, path, url):
manifest_path, manifest = self.get_manifest(url)
if manifest_path is not None:
manifest_dir = os.path.dirname(manifest_path)
if os.path.commonpath([manifest_path, path]) == manifes... | ImmutableManifestFiles |
python | google__jax | jax/_src/pallas/mosaic_gpu/primitives.py | {
"start": 80918,
"end": 81137
} | class ____:
shape: tuple[int, ...]
dtype: jnp.dtype
layout: SomeLayout
inline_mgpu_p = jax_core.Primitive("inline_mgpu_p")
inline_mgpu_p.multiple_results = True
@dataclasses.dataclass(frozen=True)
| ShapeDtypeStruct |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_triggerer.py | {
"start": 29385,
"end": 29524
} | class ____(LogGroomerTestBase):
"""Triggerer log groomer."""
obj_name = "triggerer"
folder = "triggerer"
| TestTriggererLogGroomer |
python | getsentry__sentry | tests/sentry/replays/endpoints/test_organization_replay_details.py | {
"start": 302,
"end": 8304
} | class ____(APITestCase, ReplaysSnubaTestCase):
endpoint = "sentry-api-0-organization-replay-details"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.replay_id = uuid4().hex
self.url = reverse(self.endpoint, args=(self.organization.slug, self.replay_id... | OrganizationReplayDetailsTest |
python | huggingface__transformers | src/transformers/models/rembert/modeling_rembert.py | {
"start": 21882,
"end": 27438
} | class ____(RemBertPreTrainedModel):
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self.embeddings = RemBe... | RemBertModel |
python | google__jax | tests/custom_partitioning_sharding_rule_test.py | {
"start": 10603,
"end": 22399
} | class ____(jtu.JaxTestCase):
def run(self, result=None):
with ir.Context() as ctx, ir.Location.unknown(ctx):
sdy.register_dialect(ctx)
stablehlo.register_dialect(ctx)
module = ir.Module.create()
with ir.InsertionPoint(module.body):
super().run(result)
def get_tensor_type(self, ... | SdyShardingRuleConversionTest |
python | pypa__warehouse | tests/unit/admin/views/test_organizations.py | {
"start": 62273,
"end": 66315
} | class ____:
@pytest.mark.usefixtures("_enable_organizations")
def test_set_total_size_limit_with_integer(self, db_request):
organization = OrganizationFactory.create(name="foo")
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
... | TestSetTotalSizeLimit |
python | doocs__leetcode | lcof2/剑指 Offer II 051. 节点之和最大的路径/Solution.py | {
"start": 192,
"end": 638
} | class ____:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
left = max(0, dfs(root.left))
right = max(0, dfs(root.right))
nonlocal ans
ans = max(ans, root.va... | Solution |
python | pypa__pipenv | pipenv/patched/pip/_internal/commands/list.py | {
"start": 1466,
"end": 13484
} | class ____(IndexGroupCommand):
"""
List installed packages, including editables.
Packages are listed in a case-insensitive sorted order.
"""
ignore_require_venv = True
usage = """
%prog [options]"""
def add_options(self) -> None:
self.cmd_opts.add_option(
"-o",
... | ListCommand |
python | pypa__warehouse | tests/unit/accounts/test_security_policy.py | {
"start": 475,
"end": 5603
} | class ____:
def test_verify(self):
assert verifyClass(
ISecurityPolicy,
security_policy.BasicAuthSecurityPolicy,
)
def test_noops(self):
"""Basically, anything that isn't `identity()` is a no-op."""
policy = security_policy.BasicAuthSecurityPolicy()
... | TestBasicAuthSecurityPolicy |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/relationships/tutorial001.py | {
"start": 263,
"end": 425
} | class ____(TeamBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
heroes: List["Hero"] = Relationship(back_populates="team")
| Team |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 32780,
"end": 35878
} | class ____(nn.Module):
def __init__(self, config: ConditionalDetrConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = DetrAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
dropout=config.attention_dropou... | ConditionalDetrEncoderLayer |
python | getsentry__sentry | tests/sentry/issue_detection/test_slow_db_span_detector.py | {
"start": 651,
"end": 6638
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self._settings = get_detection_settings()
def find_problems(self, event: dict[str, Any]) -> list[PerformanceProblem]:
detector = SlowDBQueryDetector(self._settings, event)
run_detector_on_data(detector, event)
... | SlowDBQueryDetectorTest |
python | getsentry__sentry | src/sentry/utils/redis.py | {
"start": 3017,
"end": 13067
} | class ____:
def __init__(self, options_manager: OptionsManager) -> None:
self._clusters_bytes: dict[str, RedisCluster[bytes] | StrictRedis[bytes]] = {}
self._clusters_str: dict[str, RedisCluster[str] | StrictRedis[str]] = {}
self._options_manager = options_manager
def _supports(self, co... | RedisClusterManager |
python | PyCQA__pylint | tests/functional/u/unexpected_special_method_signature.py | {
"start": 1183,
"end": 1365
} | class ____:
def __enter__(self):
return self
def __exit__(self, exc_type, value, tb, stack): # [unexpected-special-method-signature]
pass
| SecondBadContextManager |
python | pytorch__pytorch | torch/testing/_internal/autograd_function_db.py | {
"start": 739,
"end": 1700
} | class ____(torch.autograd.Function):
@staticmethod
def forward(input):
input_np = to_numpy(input)
dinput = torch.tensor(3 * input_np ** 2, device=input.device)
return torch.tensor(input_np ** 3, device=input.device), dinput
@staticmethod
def setup_context(ctx, inputs, output):
... | NumpyCube |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/wheel.py | {
"start": 4732,
"end": 43979
} | class ____(object):
"""
Class to build and install from Wheel files (PEP 427).
"""
wheel_version = (1, 1)
hash_kind = 'sha256'
def __init__(self, filename=None, sign=False, verify=False):
"""
Initialise an instance using a (valid) filename.
"""
self.sign = sign
... | Wheel |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py | {
"start": 9701,
"end": 9923
} | class ____(graphene.ObjectType):
records = non_null_list(GrapheneAutoMaterializeAssetEvaluationRecord)
class Meta:
name = "AutoMaterializeAssetEvaluationRecords"
| GrapheneAutoMaterializeAssetEvaluationRecords |
python | kamyu104__LeetCode-Solutions | Python/integer-break.py | {
"start": 49,
"end": 1706
} | class ____(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n < 4:
return n - 1
# Proof.
# 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak
# - For each ai >= 4, we can always maximize the product b... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/rocm/rocm_template_buffer.py | {
"start": 208,
"end": 827
} | class ____(TemplateBuffer):
def __init__(
self,
layout: Layout,
inputs: Sequence[Buffer],
make_kernel_render: Callable[_P, _T],
workspace_size: int,
template: "ROCmTemplate", # type: ignore[name-defined] # noqa: F821
) -> None:
super().__init__(layout, i... | ROCmTemplateBuffer |
python | ray-project__ray | rllib/examples/algorithms/sac/benchmark_sac_mujoco.py | {
"start": 1687,
"end": 4491
} | class ____(Stopper):
def __init__(self, benchmark_envs):
self.benchmark_envs = benchmark_envs
def __call__(self, trial_id, result):
# Stop training if the mean reward is reached.
if (
result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
>= self.benchmark_envs[result["... | BenchmarkStopper |
python | ethereum__web3.py | tests/integration/test_ethereum_tester.py | {
"start": 7701,
"end": 22692
} | class ____(EthModuleTest):
test_eth_sign = not_implemented(EthModuleTest.test_eth_sign, MethodUnavailable)
test_eth_sign_ens_names = not_implemented(
EthModuleTest.test_eth_sign_ens_names, MethodUnavailable
)
test_eth_sign_typed_data = not_implemented(
EthModuleTest.test_eth_sign_typed_d... | TestEthereumTesterEthModule |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 66067,
"end": 67185
} | class ____(torch.nn.Module):
def __init__(self, qengine="fbgemm"):
super().__init__()
self.qconfig = torch.ao.quantization.get_default_qconfig(qengine)
self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float)
self.bn = torch.nn.BatchNorm2d(5).to(dtype=torch.float)
... | AnnotatedConvBnReLUModel |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 27993,
"end": 28667
} | class ____(_MutableDictTestBase, fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
MutableDict = cls._type_fixture()
mutable_pickle = MutableDict.as_mutable(PickleType)
Table(
"foo",
metadata,
Column(
"id", Integer, ... | MutableWithScalarPickleTest |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/top_level.py | {
"start": 144,
"end": 191
} | class ____(expr_context): ...
# Some comment.
| Load |
python | pexpect__pexpect | pexpect/popen_spawn.py | {
"start": 396,
"end": 6159
} | class ____(SpawnBase):
def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
logfile=None, cwd=None, env=None, encoding=None,
codec_errors='strict', preexec_fn=None):
super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
searc... | PopenSpawn |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 37631,
"end": 38447
} | class ____(Interface):
"""An object representing the default CSRF settings to be used for
all view configurations which do not explicitly declare their own."""
require_csrf = Attribute(
'Boolean attribute. If ``True``, then CSRF checks will be enabled by '
'default for the view unless overr... | IDefaultCSRFOptions |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/pickleable.py | {
"start": 2577,
"end": 2833
} | class ____:
def __init__(self, data):
self.data = data
def __hash__(self):
return id(self)
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
raise NotImplementedError
| BrokenComparable |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/sensors/test_msgraph.py | {
"start": 1345,
"end": 6793
} | class ____:
def test_execute_with_result_processor_with_old_signature(self):
status = load_json_from_resources(dirname(__file__), "..", "resources", "status.json")
response = mock_json_response(200, *status)
with patch_hook_and_request_adapter(response):
sensor = MSGraphSensor(
... | TestMSGraphSensor |
python | PyCQA__pylint | doc/data/messages/t/too-many-ancestors/good.py | {
"start": 0,
"end": 185
} | class ____:
beaver_tailed: bool
can_swim: bool
has_beak: bool
has_fur: bool
has_vertebrae: bool
lays_egg: bool
protected_specie: bool
venomous: bool
| Animal |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/keras_tensor.py | {
"start": 17376,
"end": 18032
} | class ____(KerasTensor):
"""A specialized KerasTensor representation for `tf.sparse.SparseTensor`s.
Specifically, it specializes the conversion to a placeholder in order
to maintain dense shape information.
"""
def _to_placeholder(self):
spec = self.type_spec
# nest.map_structure loses dense shape ... | SparseKerasTensor |
python | ansible__ansible | test/units/modules/utils.py | {
"start": 82,
"end": 289
} | class ____(Exception):
pass
def exit_json(*args, **kwargs):
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs):
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
| AnsibleFailJson |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-of-a-path-with-special-roads.py | {
"start": 1322,
"end": 2545
} | class ____(object):
def minimumCost(self, start, target, specialRoads):
"""
:type start: List[int]
:type target: List[int]
:type specialRoads: List[List[int]]
:rtype: int
"""
start, target = tuple(start), tuple(target)
adj = collections.defaultdict(lis... | Solution2 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 9902,
"end": 10312
} | class ____(graphene.InputObjectType):
repositoryName = graphene.NonNull(graphene.String)
repositoryLocationName = graphene.NonNull(graphene.String)
resourceName = graphene.NonNull(graphene.String)
class Meta:
description = (
"""This type represents the fields necessary to identify a... | GrapheneResourceSelector |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 98951,
"end": 99346
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(DiscussionOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgqlc.t... | DiscussionOrder |
python | getsentry__sentry | src/sentry/interfaces/contexts.py | {
"start": 6473,
"end": 6699
} | class ____(ContextType):
type = "os"
context_to_tag_mapping = {
"": "{os}",
"name": "{name}",
"rooted": "{rooted}",
"build": "{build}",
}
# build, rooted
@contexttype
| OsContextType |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 25766,
"end": 30118
} | class ____(Request):
"""
Create a new project
:param name: Project name Unique within the company.
:type name: str
:param description: Project description.
:type description: str
:param tags: User-defined tags
:type tags: Sequence[str]
:param system_tags: System tags. This field is ... | CreateRequest |
python | ray-project__ray | python/ray/dashboard/modules/reporter/reporter_head.py | {
"start": 2232,
"end": 35778
} | class ____(SubprocessModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ray_config = None
# TODO(fyrestone): Avoid using ray.state in dashboard, it's not
# asynchronous and will lead to low performance. ray disconnect()
# will be hang when t... | ReportHead |
python | kamyu104__LeetCode-Solutions | Python/stepping-numbers.py | {
"start": 856,
"end": 1539
} | class ____(object):
def countSteppingNumbers(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in xrange(1, high):
if result[-1] >= high:
break
d1 = ... | Solution2 |
python | tiangolo__fastapi | docs_src/header_param_models/tutorial002_pv1_py39.py | {
"start": 112,
"end": 434
} | class ____(BaseModel):
class 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: CommonHeaders = Header()):
return headers
| CommonHeaders |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 28546,
"end": 31740
} | class ____:
def test_valid_name(self):
for s, p in [
(POLICY_SCRAPY_DEFAULT, DefaultReferrerPolicy),
(POLICY_NO_REFERRER, NoReferrerPolicy),
(POLICY_NO_REFERRER_WHEN_DOWNGRADE, NoReferrerWhenDowngradePolicy),
(POLICY_SAME_ORIGIN, SameOriginPolicy),
... | TestSettingsPolicyByName |
python | geekcomputers__Python | Merge_linked_list.py | {
"start": 234,
"end": 2422
} | class ____:
# Function to initialize head
def __init__(self):
self.head = None
self.tail = None
# Method to print linked list
def printList(self):
temp = self.head
while temp:
print(temp.data, end="->")
temp = temp.next
# Function to add of ... | LinkedList |
python | langchain-ai__langchain | libs/partners/qdrant/tests/integration_tests/common.py | {
"start": 2188,
"end": 3337
} | class ____(SparseEmbeddings):
"""Fake sparse embeddings which remembers all the texts seen so far
"to return consistent vectors for the same texts.
"""
def __init__(self, dimensionality: int = 25) -> None:
self.known_texts: list[str] = []
self.dimensionality = dimensionality
def em... | ConsistentFakeSparseEmbeddings |
python | pytorch__pytorch | torch/_inductor/cache.py | {
"start": 1813,
"end": 7473
} | class ____(Cache[Key, Value]):
"""
In-memory cache implementation using a dictionary and thread lock.
"""
def __init__(self: Self) -> None:
"""
Initialize an empty in-memory cache.
"""
self._cache: dict[Key, Value] = {}
self._lock: Lock = Lock()
def get(self... | InMemoryCache |
python | kamyu104__LeetCode-Solutions | Python/sort-items-by-groups-respecting-dependencies.py | {
"start": 58,
"end": 1058
} | class ____(object):
def __init__(self):
self.__nodes = set()
self.__in_degree = collections.defaultdict(set)
self.__out_degree = collections.defaultdict(set)
def add_node(self, node):
self.__nodes.add(node)
def add_edge(self, src, dst):
self.add_node(src... | Topo |
python | django__django | tests/auth_tests/test_views.py | {
"start": 20994,
"end": 22581
} | class ____(AuthViewsTestCase):
user_email = "staffmember@example.com"
@classmethod
def setUpTestData(cls):
cls.u1 = CustomUser.custom_objects.create(
email="staffmember@example.com",
date_of_birth=datetime.date(1976, 11, 8),
)
cls.u1.set_password("password")
... | CustomUserPasswordResetTest |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/chat_template_stage.py | {
"start": 4486,
"end": 4966
} | class ____(StatefulStage):
"""
A stage that applies chat template.
"""
fn: Type[StatefulStageUDF] = ChatTemplateUDF
def get_required_input_keys(self) -> Dict[str, str]:
"""The required input keys of the stage and their descriptions."""
return {
"messages": "A list of me... | ChatTemplateStage |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/adls2/resources.py | {
"start": 888,
"end": 971
} | class ____(Config):
credential_type: Literal["key"] = "key"
key: str
| ADLS2Key |
python | joke2k__faker | faker/providers/ssn/es_CO/__init__.py | {
"start": 818,
"end": 2111
} | class ____(BaseProvider):
nuip_formats = OrderedDict(
[
("10########", 0.25),
("11########", 0.25),
("12########", 0.1),
("%!######", 0.4),
]
)
legal_person_nit_formats = [
"8########",
"9########",
]
def nuip(self) ->... | Provider |
python | tornadoweb__tornado | tornado/test/gen_test.py | {
"start": 17672,
"end": 18016
} | class ____(RequestHandler):
@gen.coroutine
def get(self):
yield gen.moment
self.write("1")
yield gen.moment
self.write("2")
yield gen.moment
# just write, don't finish
self.write("3")
# "Undecorated" here refers to the absence of @asynchronous.
| GenCoroutineUnfinishedSequenceHandler |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 9890,
"end": 10860
} | class ____(LTTextLine):
def __init__(self, word_margin):
LTTextLine.__init__(self, word_margin)
self._y0 = -INF
return
def add(self, obj):
if isinstance(obj, LTChar) and self.word_margin:
margin = self.word_margin * max(obj.width, obj.height)
if obj.y1+m... | LTTextLineVertical |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/loop_distributed_test.py | {
"start": 3586,
"end": 5271
} | class ____(reference_test_base.TestCase, parameterized.TestCase):
@parameterized.parameters(*itertools.product(
(
no_vars_loop,
single_var_loop,
two_vars_loop,
loop_with_break,
loop_with_continue,
),
(
_distributed_dataset,
_dist... | ReferenceTest |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 5029,
"end": 5388
} | class ____(BaseSafeMigrationTest):
app = "bad_flow_rename_field_app"
migrate_from = "0001_initial"
migrate_to = "0002_rename_field"
def test(self) -> None:
with pytest.raises(
UnsafeOperationException, match="Renaming column TestTable.field to new_field is unsafe"
):
... | RenameFieldTest |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/angle_helper.py | {
"start": 4665,
"end": 4846
} | class ____(LocatorBase):
def __call__(self, v1, v2):
return select_step24(v1, v2, self.nbins, self._include_last,
threshold_factor=1)
| LocatorH |
python | psf__requests | src/requests/exceptions.py | {
"start": 3069,
"end": 3167
} | class ____(RequestException, ValueError):
"""The URL provided was somehow invalid."""
| InvalidURL |
python | FactoryBoy__factory_boy | factory/fuzzy.py | {
"start": 2164,
"end": 2876
} | class ____(BaseFuzzyAttribute):
"""Handles fuzzy choice of an attribute.
Args:
choices (iterable): An iterable yielding options; will only be unrolled
on the first call.
getter (callable or None): a function to parse returned values
"""
def __init__(self, choices, getter=No... | FuzzyChoice |
python | apache__thrift | lib/py/src/transport/THeaderTransport.py | {
"start": 1435,
"end": 1510
} | class ____(object):
BINARY = 0x00
COMPACT = 0x02
| THeaderSubprotocolID |
python | pypa__warehouse | tests/unit/manage/views/test_organizations.py | {
"start": 1821,
"end": 12835
} | class ____:
def test_manage_organization_application(self, db_request):
_organization_application = OrganizationApplicationFactory.create(
status=OrganizationApplicationStatus.Submitted
)
view = org_views.ManageOrganizationApplicationViews(
_organization_application,... | TestManageOrganizationApplication |
python | ray-project__ray | ci/ray_ci/ray_docker_container.py | {
"start": 360,
"end": 3071
} | class ____(DockerContainer):
"""
Container for building and publishing ray docker images
"""
def run(self, base: Optional[str] = None) -> None:
"""
Build and publish ray docker images
"""
assert "RAYCI_BUILD_ID" in os.environ, "RAYCI_BUILD_ID not set"
rayci_build... | RayDockerContainer |
python | realpython__materials | python-textual/grid_tcss.py | {
"start": 101,
"end": 415
} | class ____(App):
CSS_PATH = "grid.tcss"
def compose(self):
with Grid():
for row in range(6):
for col in range(4):
yield Static(f"Static ({row=}, {col=})")
if __name__ == "__main__":
app = GridLayoutAppWithTCSS()
app.run()
| GridLayoutAppWithTCSS |
python | jazzband__django-model-utils | tests/test_models/test_timeframed_model.py | {
"start": 350,
"end": 1349
} | class ____(TestCase):
def setUp(self) -> None:
self.now = datetime.now()
def test_not_yet_begun(self) -> None:
TimeFrame.objects.create(start=self.now + timedelta(days=2))
self.assertEqual(TimeFrame.timeframed.count(), 0)
def test_finished(self) -> None:
TimeFrame.objects.c... | TimeFramedModelTests |
python | PrefectHQ__prefect | tests/server/models/test_block_registration.py | {
"start": 3876,
"end": 5153
} | class ____:
async def test_register_new_block_schema(self, session):
block_type_id = await register_block_type(
session=session, block_type=Secret._to_block_type()
)
registered_block_schema_id = await register_block_schema(
session, block_schema=Secret._to_block_sche... | TestRegisterBlockSchema |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_test.py | {
"start": 54089,
"end": 83442
} | class ____(test.TestCase):
def test_raises_if_empty_feature_columns(self):
with self.assertRaisesRegex(ValueError,
'feature_columns must not be empty'):
fc.linear_model(features={}, feature_columns=[])
def test_should_be_feature_column(self):
with self.assertRaisesReg... | LinearModelTest |
python | kamyu104__LeetCode-Solutions | Python/loud-and-rich.py | {
"start": 38,
"end": 830
} | class ____(object):
def loudAndRich(self, richer, quiet):
"""
:type richer: List[List[int]]
:type quiet: List[int]
:rtype: List[int]
"""
def dfs(graph, quiet, node, result):
if result[node] is None:
result[node] = node
for n... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_api.py | {
"start": 311,
"end": 6665
} | class ____:
@pytest.fixture
def fb_api(self):
return source_facebook_marketing.api.MyFacebookAdsApi.init(access_token="foo", crash_log=False)
@pytest.mark.parametrize(
"max_rate,max_pause_interval,min_pause_interval,usage,pause_interval,expected_pause_interval",
[
(
... | TestMyFacebookAdsApi |
python | pallets__itsdangerous | src/itsdangerous/_json.py | {
"start": 78,
"end": 473
} | class ____:
"""Wrapper around json module that strips whitespace."""
@staticmethod
def loads(payload: str | bytes) -> t.Any:
return _json.loads(payload)
@staticmethod
def dumps(obj: t.Any, **kwargs: t.Any) -> str:
kwargs.setdefault("ensure_ascii", False)
kwargs.setdefault("... | _CompactJSON |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 24078,
"end": 24174
} | class ____:
def test_bool_definition(self):
assert nt.bool is np.bool
| TestBoolDefinition |
python | openai__openai-python | src/openai/types/beta/function_tool.py | {
"start": 249,
"end": 397
} | class ____(BaseModel):
function: FunctionDefinition
type: Literal["function"]
"""The type of tool being defined: `function`"""
| FunctionTool |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 6296,
"end": 11037
} | class ____(nn.Module):
"""
Multiscale deformable attention as proposed in Deformable DETR.
"""
def __init__(self, config: MMGroundingDinoConfig, num_heads: int, n_points: int):
super().__init__()
self.attn = MultiScaleDeformableAttention()
if config.d_model % num_heads != 0:
... | MMGroundingDinoMultiscaleDeformableAttention |
python | getsentry__sentry | tests/sentry/sentry_apps/api/bases/test_sentryapps.py | {
"start": 9550,
"end": 11071
} | class ____(TestCase):
def setUp(self) -> None:
self.endpoint = IntegrationPlatformEndpoint()
def test_handle_sentry_app_error(self) -> None:
error = SentryAppError(message="cool", status_code=400)
response = self.endpoint._handle_sentry_app_exception(error)
assert response.stat... | IntegrationPlatformEndpointTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor28.py | {
"start": 323,
"end": 479
} | class ____(ParentA, Generic[T]):
def __init__(self, a: T) -> None: ...
def func1(arg1: ParentA, arg2: ParentA): ...
func1(ChildA(1), ChildA(2))
| ChildA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/match3.py | {
"start": 186,
"end": 260
} | class ____(TypedDict):
name: Literal["b"]
other_extra_value: int
| TD2 |
python | aio-libs__aiohttp | aiohttp/client.py | {
"start": 50492,
"end": 54048
} | class ____:
__slots__ = ("_coro", "_resp", "_session")
def __init__(
self,
coro: Coroutine["asyncio.Future[Any]", None, ClientResponse],
session: ClientSession,
) -> None:
self._coro = coro
self._resp: ClientResponse | None = None
self._session = session
... | _SessionRequestContextManager |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 188019,
"end": 190928
} | class ____(VegaLiteSchema):
"""
BinParams schema wrapper.
Binning properties or boolean flag for determining whether to bin data or not.
Parameters
----------
anchor : float
A value in the binned domain at which to anchor the bins, shifting the bin
boundaries if necessary to en... | BinParams |
python | walkccc__LeetCode | solutions/780. Reaching Points/780.py | {
"start": 0,
"end": 272
} | class ____:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while sx < tx and sy < ty:
tx, ty = tx % ty, ty % tx
return (sx == tx and sy <= ty and (ty - sy) % tx == 0 or
sy == ty and sx <= tx and (tx - sx) % ty == 0)
| Solution |
python | huggingface__transformers | src/transformers/models/aria/modular_aria.py | {
"start": 18751,
"end": 40389
} | class ____(BaseImageProcessor):
"""
A vision processor for the Aria model that handles image preprocessing.
Initialize the AriaImageProcessor.
Args:
image_mean (`list`, *optional*, defaults to [0.5, 0.5, 0.5]):
Mean values for normalization.
image_std (`list`, *optional*, de... | AriaImageProcessor |
python | walkccc__LeetCode | solutions/2779. Maximum Beauty of an Array After Applying Operation/2779.py | {
"start": 0,
"end": 248
} | class ____:
def maximumBeauty(self, nums: list[int], k: int) -> int:
ans = 0
nums.sort()
l = 0
for r in range(len(nums)):
while nums[r] - nums[l] > 2 * k:
l += 1
ans = max(ans, r - l + 1)
return ans
| Solution |
python | pydata__xarray | xarray/tests/test_combine.py | {
"start": 12882,
"end": 29240
} | class ____:
def test_nested_concat(self):
objs = [Dataset({"x": [0]}), Dataset({"x": [1]})]
expected = Dataset({"x": [0, 1]})
actual = combine_nested(objs, concat_dim="x")
assert_identical(expected, actual)
actual = combine_nested(objs, concat_dim=["x"])
assert_identi... | TestNestedCombine |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 17078,
"end": 17474
} | class ____(tests.LimitedTestCase):
__test__ = False
def test_cursor_works_as_context_manager(self):
with self.connection.cursor() as c:
c.execute('select 1')
row = c.fetchone()
assert row == (1,)
def test_set_isolation_level(self):
self.connection.set_is... | TestPsycopg2Base |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_vies_vat.py | {
"start": 887,
"end": 1879
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_vies_vat"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(c... | ColumnValuesToBeValidViesVat |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/_utils.py | {
"start": 14387,
"end": 17751
} | class ____:
column_name: str
column_dtype: pl.DataType
field_id: int
load_from_bytes_impl: LoadFromBytesImpl | None
null_count: list[int | None]
min_values: list[bytes | None]
max_values: list[bytes | None]
def push_file_statistics(self, file: DataFile) -> None:
self.null_count.... | IcebergColumnStatisticsLoader |
python | pymupdf__PyMuPDF | src/table.py | {
"start": 49789,
"end": 64449
} | class ____:
def __init__(self, page, cells):
self.page = page
self.cells = cells
self.header = self._get_header() # PyMuPDF extension
@property
def bbox(self):
c = self.cells
return (
min(map(itemgetter(0), c)),
min(map(itemgetter(1), c)),
... | Table |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py | {
"start": 199,
"end": 238
} | class ____(
object
#
):
...
| A |
python | huggingface__transformers | src/transformers/pipelines/image_text_to_text.py | {
"start": 1337,
"end": 1485
} | class ____(enum.Enum):
TENSORS = 0
NEW_TEXT = 1
FULL_TEXT = 2
@add_end_docstrings(build_pipeline_init_args(has_processor=True))
| ReturnType |
python | jazzband__django-waffle | waffle/tests/test_mixin.py | {
"start": 1722,
"end": 2726
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.request = get()
def test_sample_must_be_active(self):
view = views.SampleView
self.assertRaises(Http404, process_request, self.request, view)
Sample.objects.create(name='foo', percent='100.0')
response ... | WaffleSampleMixinTest |
python | dask__distributed | distributed/semaphore.py | {
"start": 538,
"end": 9102
} | class ____:
"""An extension for the scheduler to manage Semaphores
This adds the following routes to the scheduler
* semaphore_acquire
* semaphore_release
* semaphore_close
* semaphore_refresh_leases
* semaphore_register
"""
def __init__(self, scheduler):
self.scheduler = ... | SemaphoreExtension |
python | huggingface__transformers | src/transformers/models/florence2/configuration_florence2.py | {
"start": 1342,
"end": 6262
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Florence2VisionModel`]. It is used to instantiate a Florence2VisionModel
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield ... | Florence2VisionConfig |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/attributes.py | {
"start": 44117,
"end": 50656
} | class ____(_ScalarAttributeImpl):
"""represents a scalar-holding InstrumentedAttribute,
where the target object is also instrumented.
Adds events to delete/set operations.
"""
default_accepts_scalar_loader = False
uses_objects = True
supports_population = True
collection = False
... | _ScalarObjectAttributeImpl |
python | django__django | tests/auth_tests/test_mixins.py | {
"start": 1292,
"end": 4372
} | class ____(TestCase):
factory = RequestFactory()
def test_stacked_mixins_success(self):
user = models.User.objects.create(username="joe", password="qwerty")
perms = models.Permission.objects.filter(
codename__in=("add_customuser", "change_customuser")
)
user.user_per... | AccessMixinTests |
python | huggingface__transformers | examples/modular-transformers/modeling_switch_function.py | {
"start": 4283,
"end": 7377
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: SwitchFunctionConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidd... | SwitchFunctionAttention |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 40995,
"end": 42653
} | class ____(ASTExpression):
def __init__(self, rooted: bool, array: bool, expr: ASTExpression) -> None:
self.rooted = rooted
self.array = array
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTDeleteExpr):
return NotImplemented
... | ASTDeleteExpr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.