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 | facebook__pyre-check | client/commands/no_daemon_query.py | {
"start": 1082,
"end": 5812
} | class ____:
"""
Data structure for configuration options the backend check command can recognize.
Need to keep in sync with `source/command/checkCommand.ml`
"""
base_arguments: backend_arguments.BaseArguments
query: str
no_validation_on_class_lookup_failure: bool
def serialize(self) -... | Arguments |
python | pypa__hatch | tests/backend/metadata/test_hatch.py | {
"start": 4175,
"end": 4674
} | class ____:
def test_unknown(self, isolation):
with pytest.raises(ValueError, match="Unknown version scheme: foo"):
_ = HatchMetadata(isolation, {"version": {"scheme": "foo"}}, PluginManager()).version.scheme
def test_cached(self, isolation):
metadata = HatchMetadata(isolation, {"ve... | TestVersionScheme |
python | kamyu104__LeetCode-Solutions | Python/queens-that-can-attack-the-king.py | {
"start": 29,
"end": 652
} | class ____(object):
def queensAttacktheKing(self, queens, king):
"""
:type queens: List[List[int]]
:type king: List[int]
:rtype: List[List[int]]
"""
dirctions = [(-1, 0), (0, 1), (1, 0), (0, -1),
(-1, 1), (1, 1), (1, -1), (-1, -1)]
result ... | Solution |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 54756,
"end": 68815
} | class ____(unittest.TestCase):
def testDefault(self):
pool = descriptor_pool.DescriptorPool()
file_desc = descriptor_pb2.FileDescriptorProto(name='some/file.proto')
file = pool.AddSerializedFile(file_desc.SerializeToString())
self.assertFalse(
file._GetFeatures().HasExtension(unittest_feature... | FeatureSetDefaults |
python | sympy__sympy | sympy/physics/quantum/spin.py | {
"start": 8129,
"end": 9327
} | class ____(SpinOpBase, HermitianOperator):
"""The Jx operator."""
_coord = 'x'
basis = 'Jx'
def _eval_commutator_JyOp(self, other):
return I*hbar*JzOp(self.name)
def _eval_commutator_JzOp(self, other):
return -I*hbar*JyOp(self.name)
def _apply_operator_JzKet(self, ket, **opt... | JxOp |
python | pola-rs__polars | py-polars/src/polars/io/cloud/credential_provider/_providers.py | {
"start": 4398,
"end": 9782
} | class ____(CachingCredentialProvider):
"""
AWS Credential Provider.
Using this requires the `boto3` Python package to be installed.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
"""
def... | CredentialProviderAWS |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 10682,
"end": 11051
} | class ____(HTTPException):
"""*403* `Forbidden`
Raise if the user doesn't have the permission for the requested resource
but was authenticated.
"""
code = 403
description = (
"You don't have the permission to access the requested"
" resource. It is either read-protected or not ... | Forbidden |
python | tensorflow__tensorflow | tensorflow/python/eager/remote_test.py | {
"start": 2178,
"end": 8388
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
super(SingleWorkerTest, self).setUp()
workers, _ = test_util.create_local_cluster(1, 0)
remote.connect_to_remote_host(workers[0].target)
def tearDown(self):
super(SingleWorkerTest, self).tearDown()
# Clear the current device... | SingleWorkerTest |
python | django__django | django/contrib/flatpages/sitemaps.py | {
"start": 146,
"end": 584
} | class ____(Sitemap):
def items(self):
if not django_apps.is_installed("django.contrib.sites"):
raise ImproperlyConfigured(
"FlatPageSitemap requires django.contrib.sites, which isn't installed."
)
Site = django_apps.get_model("sites.Site")
current_site... | FlatPageSitemap |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 10724,
"end": 11534
} | class ____(ASTExpression):
def __init__(self, name: ASTNestedName) -> None:
# note: this class is basically to cast a nested name as an expression
self.name = name
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTIdExpression):
return NotImplemented
... | ASTIdExpression |
python | getsentry__sentry | src/sentry/incidents/endpoints/serializers/alert_rule_trigger_action.py | {
"start": 3112,
"end": 4974
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
# Mark that we're using legacy AlertRuleTriggerAction models
report_used_legacy_models()
from sentry.incidents.serializers import ACTION_TARGET_TYPE_TO_STRING
priority = (
obj.sentry_app_config.ge... | AlertRuleTriggerActionSerializer |
python | pypa__pip | src/pip/_vendor/packaging/_musllinux.py | {
"start": 327,
"end": 2694
} | class ____(NamedTuple):
major: int
minor: int
def _parse_musl_version(output: str) -> _MuslVersion | None:
lines = [n for n in (n.strip() for n in output.splitlines()) if n]
if len(lines) < 2 or lines[0][:4] != "musl":
return None
m = re.match(r"Version (\d+)\.(\d+)", lines[1])
if not ... | _MuslVersion |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/load/test_load.py | {
"start": 541,
"end": 6086
} | class ____:
pass
@pytest.mark.requires("openai", "langchain_openai")
def test_loads_openai_llm() -> None:
from langchain_openai import OpenAI
llm = CommunityOpenAI(
model="davinci",
temperature=0.5,
openai_api_key="hello",
top_p=0.8,
)
llm_string = dumps(llm)
l... | NotSerializable |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes5.py | {
"start": 6623,
"end": 6691
} | class ____:
def __hash__(self) -> int:
return 0
| ParentClass6 |
python | astropy__astropy | astropy/units/tests/test_quantity_array_methods.py | {
"start": 20340,
"end": 21956
} | class ____:
"""Structured arrays are not specifically supported, but we should not
prevent their use unnecessarily.
Note that these tests use simple units. Now that structured units are
supported, it may make sense to deprecate this.
"""
def setup_method(self):
self.ra = (
... | TestStructuredArray |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_map_metrics/column_values_match_like_pattern_list.py | {
"start": 513,
"end": 2056
} | class ____(ColumnMapMetricProvider):
condition_metric_name = "column_values.match_like_pattern_list"
condition_value_keys = ("like_pattern_list", "match_on")
@column_condition_partial(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(cls, column, like_pattern_list, match_on, _dialect, **kwargs):
... | ColumnValuesMatchLikePatternList |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 5795,
"end": 7447
} | class ____(XYGlyph, LineGlyph, FillGlyph, HatchGlyph):
''' Render annular wedges.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
__example__ = "examples/reference/models/AnnularWedge.py"
_arg... | AnnularWedge |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/lstm.py | {
"start": 2394,
"end": 3508
} | class ____(LightningModule):
def __init__(self, vocab_size: int = 33278):
super().__init__()
self.model = SimpleLSTM(vocab_size=vocab_size)
self.hidden: Optional[tuple[Tensor, Tensor]] = None
def on_train_epoch_end(self) -> None:
self.hidden = None
def training_step(self, b... | LightningLSTM |
python | python-jsonschema__jsonschema | jsonschema/tests/test_validators.py | {
"start": 64529,
"end": 65552
} | class ____:
"""
Make sure functionality from draft 6 doesn't leak backwards in time.
"""
def test_True_is_not_a_schema(self):
with self.assertRaises(exceptions.SchemaError) as e:
self.Validator.check_schema(True)
self.assertIn("True is not of type", str(e.exception))
de... | AntiDraft6LeakMixin |
python | numba__numba | numba/core/externals.py | {
"start": 3370,
"end": 4851
} | class ____(_Installer):
"""
Map the math functions from the C runtime library into the LLVM
execution environment.
"""
def _do_install(self, context):
is32bit = utils.MACHINE_BITS == 32
c_helpers = _helperlib.c_helpers
if sys.platform.startswith('win32') and is32bit:
... | _ExternalMathFunctions |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 10447,
"end": 11593
} | class ____(django_test.TestCase):
def setUp(self):
super().setUp()
NonIntegerPkFactory.reset_sequence()
def test_first(self):
nonint = NonIntegerPkFactory.build()
self.assertEqual('foo0', nonint.foo)
def test_many(self):
nonint1 = NonIntegerPkFactory.build()
... | DjangoNonIntegerPkTestCase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 432767,
"end": 437212
} | class ____(sgqlc.types.Interface):
"""Represents an owner of a Repository."""
__schema__ = github_schema
__field_names__ = ("avatar_url", "id", "login", "repositories", "repository", "resource_path", "url")
avatar_url = sgqlc.types.Field(
sgqlc.types.non_null(URI),
graphql_name="avatarU... | RepositoryOwner |
python | pennersr__django-allauth | allauth/socialaccount/providers/fxa/views.py | {
"start": 259,
"end": 1021
} | class ____(OAuth2Adapter):
provider_id = PROVIDER_ID
access_token_url = FXA_OAUTH_ENDPOINT + "/token"
authorize_url = FXA_OAUTH_ENDPOINT + "/authorization"
profile_url = FXA_PROFILE_ENDPOINT + "/profile"
def complete_login(self, request, app, token, **kwargs):
headers = {"Authorization": "B... | FirefoxAccountsOAuth2Adapter |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/shrinking/choicetree.py | {
"start": 3850,
"end": 4607
} | class ____:
"""Records sequences of choices made during shrinking so that we
can track what parts of a pass has run. Used to create Chooser
objects that are the main interface that a pass uses to make
decisions about what to do.
"""
def __init__(self) -> None:
self.root = TreeNode()
... | ChoiceTree |
python | google__jax | tests/xla_bridge_test.py | {
"start": 959,
"end": 8739
} | class ____(jtu.JaxTestCase):
def test_set_device_assignment_no_partition(self):
compile_options = compiler.get_compile_options(
num_replicas=4, num_partitions=1, device_assignment=[0, 1, 2, 3])
self.assertEqual(compile_options.device_assignment.replica_count(), 4)
self.assertEqual(compile_options... | XlaBridgeTest |
python | getsentry__sentry | tests/sentry/integrations/slack/threads/activity_notifications/test_external_issue_created_activity.py | {
"start": 295,
"end": 926
} | class ____(TestCase):
def test_throws_error_on_invalid_activity_type(self) -> None:
with pytest.raises(Exception):
self.activity.type = 500
_ExternalIssueCreatedActivity(self.activity)
def test_throws_error_on_unsupported_activity_type(self) -> None:
with pytest.raises(E... | TestInit |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 6863,
"end": 7077
} | class ____(Protocol):
def __call__(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
**kwargs: object,
) -> tuple[torch.Tensor, ...]: ...
| _AttentionOp |
python | wandb__wandb | landfill/functional_tests/lightning_fabric/pl_base.py | {
"start": 2236,
"end": 2899
} | class ____:
def __init__(self, wandb_logger):
self.wandb_logger = wandb_logger
self.table = wandb.Table(columns=["image", "prediction", "ground_truth"])
def on_test_batch_end(self, images, predictions, ground_truths):
for image, prediction, ground_truth in zip(images, predictions, groun... | TableLoggingCallback |
python | PyCQA__pylint | doc/data/messages/i/invalid-slots/good.py | {
"start": 0,
"end": 46
} | class ____:
__slots__ = ("name", "age")
| Person |
python | ray-project__ray | python/ray/llm/_internal/serve/engines/vllm/vllm_models.py | {
"start": 1491,
"end": 2080
} | class ____(BaseModelExtended):
"""Configuration for placement group."""
bundles: List[BundleConfig] = Field(description="List of resource bundles")
strategy: Literal["PACK", "SPREAD", "STRICT_PACK", "STRICT_SPREAD"] = Field(
default="PACK", description="Placement group strategy"
)
@model_v... | PlacementGroupConfig |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/base.py | {
"start": 3241,
"end": 10996
} | class ____(BaseModel, Generic[P]):
_example_type: ClassVar[Type[BaseLlamaDataExample]]
examples: List[BaseLlamaDataExample] = Field(
default=[], description="Data examples of this dataset."
)
_predictions_cache: List[BaseLlamaExamplePrediction] = PrivateAttr(
default_factory=list
)
... | BaseLlamaDataset |
python | HypothesisWorks__hypothesis | hypothesis-python/docs/_ext/hypothesis_linkcheck.py | {
"start": 1466,
"end": 2071
} | class ____(HyperlinkAvailabilityChecker):
def is_ignored_uri(self, uri: str) -> bool:
if is_intersphinx_link(uri):
return True
return super().is_ignored_uri(uri)
sphinx.builders.linkcheck.HyperlinkAvailabilityChecker = HypothesisLinkChecker
# Hook the builder to get access to the int... | HypothesisLinkChecker |
python | apache__airflow | helm-tests/tests/helm_tests/other/test_redis.py | {
"start": 19270,
"end": 20159
} | class ____:
"""Tests redis service account."""
def test_default_automount_service_account_token(self):
docs = render_chart(
values={
"redis": {
"serviceAccount": {"create": True},
},
},
show_only=["templates/redis/r... | TestRedisServiceAccount |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 44073,
"end": 44575
} | class ____(MemoryUsage):
_parameters = ["frame", "deep", "_index"]
_defaults = {"deep": False, "_index": True}
@property
def chunk_kwargs(self):
return {"deep": self.deep, "index": self._index}
@property
def combine_kwargs(self):
return {"is_dataframe": is_dataframe_like(self.f... | MemoryUsageFrame |
python | docker__docker-py | tests/unit/models_secrets_test.py | {
"start": 104,
"end": 362
} | class ____(unittest.TestCase):
def test_secrets_repr(self):
client = make_fake_client()
secret = client.secrets.create(name="super_secret", data="secret")
assert secret.__repr__() == f"<Secret: '{FAKE_SECRET_NAME}'>"
| CreateServiceTest |
python | PyCQA__pylint | tests/regrtest_data/ignore_option_10669/test/__init__.py | {
"start": 1,
"end": 46
} | class ____:
"""many issues here"""
pass
| i |
python | pallets__click | src/click/_termui_impl.py | {
"start": 949,
"end": 18044
} | class ____(t.Generic[V]):
def __init__(
self,
iterable: cabc.Iterable[V] | None,
length: int | None = None,
fill_char: str = "#",
empty_char: str = " ",
bar_template: str = "%(bar)s",
info_sep: str = " ",
hidden: bool = False,
show_eta: bool =... | ProgressBar |
python | pytorch__pytorch | torch/_inductor/cudagraph_utils.py | {
"start": 11627,
"end": 11863
} | class ____:
"""
Info needed to realign inputs
"""
placeholders: Sequence[PlaceholderInfo]
stack_traces: list[Optional[str]]
cudagraph_fail_reasons: list[str]
@dataclasses.dataclass(frozen=True)
| CudagraphCachedInfo |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias5.py | {
"start": 868,
"end": 1092
} | class ____(Foo):
def __int__(self) -> int:
return super().__int__() + 1
v1: FooIsh[Bar] = 42
v2: FooIsh[Bar] = Bar()
# This should generate an error.
v3: FooIsh[type[Bar]] = 42
MyTypeAlias = dict[_T1, _T2]
| Bar |
python | spack__spack | lib/spack/spack/cmd/create.py | {
"start": 4509,
"end": 5031
} | class ____(PackageTemplate):
"""Provides appropriate overrides for Autotools-based packages
that *do* come with a ``configure`` script"""
base_class_name = "AutotoolsPackage"
package_class_import = (
"from spack_repo.builtin.build_systems.autotools import AutotoolsPackage"
)
body_def =... | AutotoolsPackageTemplate |
python | bokeh__bokeh | src/bokeh/models/layouts.py | {
"start": 21489,
"end": 22304
} | class ____(LayoutDOM):
''' A panel that allows to group UI elements.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
title = Nullable(String, help="""
The title text of the group. If not provid... | GroupBox |
python | pikepdf__pikepdf | src/pikepdf/codec.py | {
"start": 4041,
"end": 4153
} | class ____(PdfDocCodec, codecs.StreamWriter):
"""Implement PdfDocEncoding stream writer."""
| PdfDocStreamWriter |
python | walkccc__LeetCode | solutions/162. Find Peak Element/162.py | {
"start": 0,
"end": 233
} | class ____:
def findPeakElement(self, nums: list[int]) -> int:
l = 0
r = len(nums) - 1
while l < r:
m = (l + r) // 2
if nums[m] >= nums[m + 1]:
r = m
else:
l = m + 1
return l
| Solution |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_import_export.py | {
"start": 16972,
"end": 17991
} | class ____(TestCase):
"""
If a custom field is declared, import should work if either the Field's
attribute name or column name is referenced in the ``fields`` list (issue 1815).
"""
fixtures = ["author"]
class _EBookResource(ModelResource):
published = Field(attribute="published", col... | CustomColumnNameImportTest |
python | pytorch__pytorch | torch/distributed/_tools/mem_tracker.py | {
"start": 2327,
"end": 3301
} | class ____(_State):
"""
An enum to define the state of a module.
- PRE_FW: The module is about to run the forward pass.
- POST_FW: The module has finished running the forward pass.
- PEAK_FW: The module has reached the peak memory usage during the forward pass.
- PRE_BW: The mod... | _ModState |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 19497,
"end": 19939
} | class ____(BaseActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.WEBHOOK
@property
def target_type(self) -> int | None:
return None
@property
def required_fields(self) -> list[str]:
return [
ACTION_FIELD_MAPPINGS[ActionType.... | WebhookActionTranslator |
python | wandb__wandb | wandb/integration/fastai/__init__.py | {
"start": 9261,
"end": 9302
} | class ____(wandb.Error):
pass
| FastaiError |
python | pytorch__pytorch | torch/_export/db/examples/optional_input.py | {
"start": 89,
"end": 447
} | class ____(torch.nn.Module):
"""
Tracing through optional input is not supported yet
"""
def forward(self, x, y=torch.randn(2, 3)):
if y is not None:
return x + y
return x
example_args = (torch.randn(2, 3),)
tags = {"python.object-model"}
support_level = SupportLevel.SUPPO... | OptionalInput |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 23870,
"end": 24751
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.conv = nn.Conv2d(
config.decoder_hidden_size,
config.decoder_hidden_size,
kernel_size=3,
padding=1,
)
self.layernorm = SegGptLayerNorm(
normalized_sh... | SegGptDecoderHead |
python | modin-project__modin | modin/tests/pandas/test_io.py | {
"start": 47384,
"end": 48729
} | class ____:
def test_read_table(self, make_csv_file):
unique_filename = make_csv_file(delimiter="\t")
eval_io(
fn_name="read_table",
# read_table kwargs
filepath_or_buffer=unique_filename,
)
@pytest.mark.parametrize("set_async_read_mode", [False, True... | TestTable |
python | celery__celery | celery/backends/base.py | {
"start": 36195,
"end": 47738
} | class ____(Backend):
key_t = ensure_bytes
task_keyprefix = 'celery-task-meta-'
group_keyprefix = 'celery-taskset-meta-'
chord_keyprefix = 'chord-unlock-'
implements_incr = False
def __init__(self, *args, **kwargs):
if hasattr(self.key_t, '__func__'): # pragma: no cover
self... | BaseKeyValueStoreBackend |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-talk/components.py | {
"start": 505,
"end": 866
} | class ____(RecordExtractor):
def extract_records(self, response: requests.Response) -> List[Record]:
ivrs = response.json().get("ivrs", [])
records = []
for ivr in ivrs:
for menu in ivr.get("menus", []):
records.append({"ivr_id": ivr["id"], **menu})
return... | IVRMenusRecordExtractor |
python | networkx__networkx | networkx/classes/tests/test_multidigraph.py | {
"start": 14711,
"end": 15272
} | class ____(nx.MultiDiGraph):
node_dict_factory = CustomDictClass # type: ignore[assignment]
node_attr_dict_factory = CustomDictClass # type: ignore[assignment]
adjlist_outer_dict_factory = CustomDictClass # type: ignore[assignment]
adjlist_inner_dict_factory = CustomDictClass # type: ignore[assignme... | MultiDiGraphSubClass |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 20765,
"end": 22196
} | class ____(EigCases):
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
def test_types(self, dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
w, v = np.linalg.eig(x)
assert_equal(w.dtype, dtype)
assert_equal(v.dtype, dtype)
x = np.array([[1, 0.... | TestEig |
python | gevent__gevent | src/greentest/3.9/test_httplib.py | {
"start": 60764,
"end": 70163
} | class ____(TestCase):
def setUp(self):
if not hasattr(client, 'HTTPSConnection'):
self.skipTest('ssl support required')
def make_server(self, certfile):
from test.ssl_servers import make_https_server
return make_https_server(self, certfile=certfile)
def test_attributes... | HTTPSTest |
python | fluentpython__example-code | 09-pythonic-obj/vector2d_v0.py | {
"start": 659,
"end": 1436
} | class ____:
typecode = 'd' # <1>
def __init__(self, x, y):
self.x = float(x) # <2>
self.y = float(y)
def __iter__(self):
return (i for i in (self.x, self.y)) # <3>
def __repr__(self):
class_name = type(self).__name__
return '{}({!r}, {!r})'.format(class_na... | Vector2d |
python | dask__dask | dask/_expr.py | {
"start": 41657,
"end": 43861
} | class ____(Expr):
"""
An expression that guarantees that all keys are suffixes with a unique id.
This can be used to break a common subexpression apart.
"""
_parameters = ["expr"]
_ALLOWED_TYPES = [HLGExpr, LLGExpr, HLGFinalizeCompute, _HLGExprSequence]
def __dask_keys__(self):
ret... | ProhibitReuse |
python | numpy__numpy | benchmarks/benchmarks/bench_io.py | {
"start": 996,
"end": 1669
} | class ____(Benchmark):
def setup(self):
self.d = np.ones(50000)
self.e = self.d.copy()
self.m = (self.d == 1)
self.im = (~ self.m)
self.m8 = self.m.copy()
self.m8[::8] = (~ self.m[::8])
self.im8 = (~ self.m8)
def time_copyto(self):
np.copyto(self.... | CopyTo |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_modelresource/test_resource_fields.py | {
"start": 5060,
"end": 6308
} | class ____(TestCase):
# issue 1697
# Add a declared field to the Resource, which is not present in the import file.
# The import should succeed without issue.
class MyBookResource(resources.ModelResource):
author_email = fields.Field(
attribute="author_email", column_name="author_ema... | ModelResourceDeclarationsNotInImportTest |
python | langchain-ai__langchain | libs/core/tests/unit_tests/prompts/test_few_shot.py | {
"start": 15099,
"end": 17813
} | class ____(BaseExampleSelector):
"""An example selector for testing purposes.
This selector returns the examples as-is.
"""
def __init__(self, examples: Sequence[dict[str, str]]) -> None:
"""Initializes the selector."""
self.examples = examples
def add_example(self, example: dict[... | AsyncAsIsSelector |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 58066,
"end": 58385
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(AuditLogOrderField, graphql_name="field")
direction = sgqlc.types.Field(OrderDirection, graphql_name="direction")
| AuditLogOrder |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/component_tree.py | {
"start": 1727,
"end": 20458
} | class ____(IHaveNew):
"""The hierarchy of Component instances defined in the project.
Manages and caches the component loading process, including finding component declarations
to build the initial declaration tree, loading these Components, and eventually building the
Definitions.
"""
defs_mo... | ComponentTree |
python | huggingface__transformers | tests/models/fnet/test_modeling_fnet.py | {
"start": 1470,
"end": 1854
} | class ____(ConfigTester):
def create_and_test_config_common_properties(self):
config = self.config_class(**self.inputs_dict)
if self.has_text_modality:
self.parent.assertTrue(hasattr(config, "vocab_size"))
self.parent.assertTrue(hasattr(config, "hidden_size"))
self.parent... | FNetConfigTester |
python | django__django | tests/forms_tests/field_tests/test_integerfield.py | {
"start": 180,
"end": 7424
} | class ____(FormFieldAssertionsMixin, SimpleTestCase):
def test_integerfield_1(self):
f = IntegerField()
self.assertWidgetRendersTo(
f, '<input type="number" name="f" id="id_f" required>'
)
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
... | IntegerFieldTest |
python | pypa__pip | src/pip/_internal/models/selection_prefs.py | {
"start": 208,
"end": 2016
} | class ____:
"""
Encapsulates the candidate selection preferences for downloading
and installing files.
"""
__slots__ = [
"allow_yanked",
"allow_all_prereleases",
"format_control",
"prefer_binary",
"ignore_requires_python",
]
# Don't include an allow_... | SelectionPreferences |
python | pola-rs__polars | py-polars/src/polars/_typing.py | {
"start": 13856,
"end": 14492
} | class ____:
"""
The context given when writing file-level parquet metadata.
.. warning::
This functionality is considered **experimental**. It may be removed or
changed at any point without it being considered a breaking change.
"""
def __init__(self, *, arrow_schema: str) -> None:... | ParquetMetadataContext |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_user_message.py | {
"start": 1358,
"end": 2111
} | class ____(BaseModel):
content: List[Content]
"""The content of the message."""
role: Literal["user"]
"""The role of the message sender. Always `user`."""
type: Literal["message"]
"""The type of the item. Always `message`."""
id: Optional[str] = None
"""The unique ID of the item.
... | RealtimeConversationItemUserMessage |
python | wntrblm__nox | nox/virtualenv.py | {
"start": 7329,
"end": 11698
} | class ____(abc.ABC):
"""An environment with a 'bin' directory and a set of 'env' vars."""
location: str
# Does this environment provide any process isolation?
is_sandboxed = False
# Special programs that aren't included in the environment.
allowed_globals: ClassVar[tuple[Any, ...]] = ()
... | ProcessEnv |
python | ray-project__ray | python/ray/data/_internal/arrow_block.py | {
"start": 4374,
"end": 6007
} | class ____(TableBlockBuilder):
def __init__(self):
if pyarrow is None:
raise ImportError("Run `pip install pyarrow` for Arrow support")
super().__init__((pyarrow.Table, bytes))
@staticmethod
def _table_from_pydict(columns: Dict[str, List[Any]]) -> Block:
return pyarrow_t... | ArrowBlockBuilder |
python | getsentry__sentry | src/sentry/dynamic_sampling/models/base.py | {
"start": 400,
"end": 719
} | class ____(ABC, Generic[Input, Output]):
@abstractmethod
def _run(self, model_input: Input) -> Output:
raise NotImplementedError()
def run(self, model_input: Input) -> Output:
if not model_input.validate():
raise InvalidModelInputError()
return self._run(model_input)
| Model |
python | altair-viz__altair | altair/vegalite/data.py | {
"start": 1206,
"end": 1783
} | class ____(_DataTransformerRegistry):
def disable_max_rows(self) -> PluginEnabler:
"""Disable the MaxRowsError."""
options = self.options
if self.active in {"default", "vegafusion"}:
options = options.copy()
options["max_rows"] = None
return self.enable(**opti... | DataTransformerRegistry |
python | marshmallow-code__marshmallow | tests/foo_serializer.py | {
"start": 41,
"end": 97
} | class ____(Schema):
_id = fields.Integer()
| FooSerializer |
python | kamyu104__LeetCode-Solutions | Python/maximum-swap.py | {
"start": 76,
"end": 600
} | class ____(object):
def maximumSwap(self, num):
"""
:type num: int
:rtype: int
"""
digits = list(str(num))
left, right = 0, 0
max_idx = len(digits)-1
for i in reversed(xrange(len(digits))):
if digits[i] > digits[max_idx]:
ma... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/D208.py | {
"start": 182,
"end": 274
} | class ____:
"""Over indented last line
Args:
Returns:
"""
| Platform |
python | Netflix__metaflow | metaflow/user_decorators/common.py | {
"start": 49,
"end": 822
} | class ____:
def __init__(
self, parent: Optional["_TrieNode"] = None, component: Optional[str] = None
):
self.parent = parent
self.component = component
self.children = {} # type: Dict[str, "_TrieNode"]
self.total_children = 0
self.value = None
self.end_v... | _TrieNode |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 20560,
"end": 21173
} | class ____(Static, can_focus=True):
"""A focusable widget with a priority binding."""
BINDINGS = [
Binding("0", "app.record('widget_0')", "0", priority=False),
Binding("a", "app.record('widget_a')", "a", priority=False),
Binding("b", "app.record('widget_b')", "b", priority=False),
... | PriorityOverlapWidget |
python | tensorflow__tensorflow | tensorflow/python/eager/benchmarks/resnet50/resnet50.py | {
"start": 5507,
"end": 13202
} | class ____(tf.keras.Model):
"""Instantiates the ResNet50 architecture.
Args:
data_format: format for the image. Either 'channels_first' or
'channels_last'. 'channels_first' is typically faster on GPUs while
'channels_last' is typically faster on CPUs. See
https://www.tensorflow.org/performan... | ResNet50 |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_bitcoin_tx_is_confirmed.py | {
"start": 899,
"end": 1906
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.bitcoin_tx_is_confirmed"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def ... | ColumnValuesBitcoinTxIsConfirmed |
python | kamyu104__LeetCode-Solutions | Python/shuffle-an-array.py | {
"start": 45,
"end": 687
} | class ____(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.__nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.... | Solution |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 7784,
"end": 8382
} | class ____(ConcreteTemplate):
cases = list(integer_binop_cases)
# Ensure that float32 ** int doesn't go through DP computations
cases += [signature(types.float32, types.float32, op)
for op in (types.int32, types.int64, types.uint64)]
cases += [signature(types.float64, types.float64, op)
... | BinOpPower |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/dist_autograd_test.py | {
"start": 102206,
"end": 107044
} | class ____(RpcAgentTestFixture):
@skip_if_lt_x_gpu(4)
def test_device_maps_backward_pass(self):
options = self.rpc_backend_options
dst = worker_name((self.rank + 1) % self.world_size)
# The reverse of this device mapping should be used for the backward pass.
options.set_device_m... | TensorPipeCudaDistAutogradTest |
python | urllib3__urllib3 | test/test_ssl.py | {
"start": 210,
"end": 8756
} | class ____:
@pytest.mark.parametrize(
"addr",
[
# IPv6
"::1",
"::",
"FE80::8939:7684:D84b:a5A4%251",
# IPv4
"127.0.0.1",
"8.8.8.8",
b"127.0.0.1",
# IPv6 w/ Zone IDs
"FE80::8939:768... | TestSSL |
python | pypa__pipenv | pipenv/installers.py | {
"start": 1646,
"end": 1804
} | class ____(RuntimeError):
def __init__(self, desc, c):
super().__init__(desc)
self.out = c.stdout
self.err = c.stderr
| InstallerError |
python | getsentry__sentry | src/sentry/sentry_apps/api/parsers/sentry_app.py | {
"start": 1675,
"end": 2026
} | class ____(serializers.Field):
def to_internal_value(self, data):
if data is None:
return
if data == "" or data == {}:
return {}
try:
validate_ui_element_schema(data)
except SchemaValidationError as e:
raise ValidationError(e.message)... | SchemaField |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/sagemaker.py | {
"start": 10156,
"end": 11563
} | class ____(SageMakerBaseSensor):
"""
Poll the pipeline until it reaches a terminal state; raise AirflowException with the failure reason.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:SageMakerPipelineSensor`
:param pipeline_e... | SageMakerPipelineSensor |
python | django-haystack__django-haystack | haystack/backends/solr_backend.py | {
"start": 849,
"end": 27188
} | class ____(BaseSearchBackend):
# Word reserved by Solr for special use.
RESERVED_WORDS = ("AND", "NOT", "OR", "TO")
# Characters reserved by Solr for special use.
# The '\\' must come first, so as not to overwrite the other slash replacements.
RESERVED_CHARACTERS = (
"\\",
"+",
... | SolrSearchBackend |
python | walkccc__LeetCode | solutions/3015. Count the Number of Houses at a Certain Distance I/3015.py | {
"start": 0,
"end": 3721
} | class ____:
def countOfPairs(self, n: int, x: int, y: int) -> list[int]:
if x > y:
x, y = y, x
def bothInRing(ringLen: int) -> list[int]:
"""
Returns the contribution from the scenario where two houses are located
in the ring.
"""
res = [0] * n
for k in range(1, (rin... | Solution |
python | readthedocs__readthedocs.org | readthedocs/storage/__init__.py | {
"start": 1013,
"end": 1168
} | class ____(LazyObject):
def _setup(self):
self._wrapped = get_storage_class(settings.RTD_BUILD_COMMANDS_STORAGE)()
| ConfiguredBuildCommandsStorage |
python | pytorch__pytorch | test/jit/test_hooks_modules.py | {
"start": 864,
"end": 1201
} | class ____(torch.nn.Module):
def __init__(self, name: str, submodule_name: str):
super().__init__()
self.name = name
self.submodule = SubmoduleForwardSingleInput(submodule_name)
def forward(self, input: str):
input = input + "_outermod"
return self.submodule(input)
| ModuleForwardSingleInput |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/utils/lazymodules.py | {
"start": 754,
"end": 2094
} | class ____:
"""Lazy module loader class."""
def __init__(self, modname, second_level_attrs=None):
"""
Lazy module loader class.
Parameters
----------
modname: str
Module name to lazy load.
second_level_attrs: list (optional)
List of secon... | LazyModule |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 111416,
"end": 112259
} | class ____(Normalize):
"""
The inverse hyperbolic sine scale is approximately linear near
the origin, but becomes logarithmic for larger positive
or negative values. Unlike the `SymLogNorm`, the transition between
these linear and logarithmic regions is smooth, which may reduce
the risk of visua... | AsinhNorm |
python | bokeh__bokeh | src/bokeh/models/expressions.py | {
"start": 8845,
"end": 9114
} | class ____(XYComponent):
""" X-component of a coordinate system transform to cartesian coordinates. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| XComponent |
python | huggingface__transformers | src/transformers/models/roberta/modeling_roberta.py | {
"start": 15487,
"end": 16885
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = RobertaCrossAttention if is_cross_attention else RobertaSelfAttention
self.self = attention_... | RobertaAttention |
python | fluentpython__example-code-2e | 16-op-overloading/vector_v7.py | {
"start": 6817,
"end": 10401
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 114513,
"end": 118568
} | class ____(fixtures.MappedTest):
"""test cascade behavior as it relates to object lists passed
to flush().
"""
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_aut... | PartialFlushTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-linkedin-ads/components.py | {
"start": 3020,
"end": 4833
} | class ____(HttpRequester):
"""
A custom HTTP requester that ensures safe encoding of query parameters, preserving the symbols ():,% during UTF-8 encoding.
"""
request_body_json: Optional[RequestInput] = None
request_headers: Optional[RequestInput] = None
request_parameters: Optional[RequestInpu... | SafeEncodeHttpRequester |
python | eventlet__eventlet | eventlet/green/zmq.py | {
"start": 646,
"end": 2169
} | class ____:
"""A Lock that can be acquired by at most one thread. Any other
thread calling acquire will be blocked in a queue. When release
is called, the threads are awoken in the order they blocked,
one at a time. This lock can be required recursively by the same
thread."""
def __init__(self)... | _QueueLock |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/sql.py | {
"start": 5942,
"end": 7505
} | class ____(db.sql.expression.FunctionElement):
"""Like CURRENT_TIMESTAMP, but has the same semantics on MySQL, Postgres, and Sqlite."""
type = db.types.DateTime() # type: ignore
@compiles(get_sql_current_timestamp, "mysql")
def compiles_get_sql_current_timestamp_mysql(_element, _compiler, **_kw) -> str:
... | get_sql_current_timestamp |
python | scrapy__scrapy | scrapy/core/downloader/contextfactory.py | {
"start": 5228,
"end": 7070
} | class ____:
"""Context factory to used to override the acceptable protocols
to set up the [OpenSSL.SSL.Context] for doing NPN and/or ALPN
negotiation.
"""
def __init__(self, context_factory: Any, acceptable_protocols: list[bytes]):
verifyObject(IPolicyForHTTPS, context_factory)
self... | AcceptableProtocolsContextFactory |
python | django__django | tests/model_inheritance/models.py | {
"start": 1759,
"end": 1917
} | class ____(models.Model):
rating = models.IntegerField(null=True, blank=True)
class Meta:
abstract = True
ordering = ["-rating"]
| Rating |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.