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 | doocs__leetcode | solution/1700-1799/1754.Largest Merge Of Two Strings/Solution.py | {
"start": 0,
"end": 423
} | class ____:
def largestMerge(self, word1: str, word2: str) -> str:
i = j = 0
ans = []
while i < len(word1) and j < len(word2):
if word1[i:] > word2[j:]:
ans.append(word1[i])
i += 1
else:
ans.append(word2[j])
... | Solution |
python | arrow-py__arrow | arrow/locales.py | {
"start": 96475,
"end": 97742
} | class ____(Locale):
names = ["ro", "ro-ro"]
past = "{0} în urmă"
future = "peste {0}"
and_word = "și"
timeframes = {
"now": "acum",
"second": "o secunda",
"seconds": "{0} câteva secunde",
"minute": "un minut",
"minutes": "{0} minute",
"hour": "o oră"... | RomanianLocale |
python | getsentry__sentry | src/sentry/api/endpoints/release_thresholds/release_threshold_index.py | {
"start": 1135,
"end": 2309
} | class ____(OrganizationEndpoint):
owner: ApiOwner = ApiOwner.ENTERPRISE
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(self, request: Request, organization: Organization) -> HttpResponse:
validator = ReleaseThresholdIndexGETValidator(
data=request.query_p... | ReleaseThresholdIndexEndpoint |
python | pytorch__pytorch | torchgen/model.py | {
"start": 54780,
"end": 73333
} | class ____:
# The name of the operator this function schema describes.
name: OperatorName
arguments: Arguments
# TODO: Need to handle collisions with argument names at some point
returns: tuple[Return, ...]
@property
def is_mutable(self) -> bool:
def is_write(arg: Argument) -> boo... | FunctionSchema |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/forms.py | {
"start": 4096,
"end": 4189
} | class ____(ReprForm):
_regex = forms.RegexField(regex="[A-Z]{3}\\.[a-z]{4}")
| RegexFieldForm |
python | walkccc__LeetCode | solutions/2222. Number of Ways to Select Buildings/2222.py | {
"start": 0,
"end": 489
} | class ____:
def numberOfWays(self, s: str) -> int:
ans = 0
# before[i] := the number of i before the current digit
before = [0] * 2
# after[i] := the number of i after the current digit
after = [0] * 2
after[0] = s.count('0')
after[1] = len(s) - after[0]
for c in s:
num = int(c)... | Solution |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 4360,
"end": 4590
} | class ____(BaseScal):
blas_func = fblas.dscal
dtype = float64
try:
class TestCscal(BaseScal):
blas_func = fblas.cscal
dtype = complex64
except AttributeError:
class TestCscal:
pass
| TestDscal |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-gel/llama_index/storage/kvstore/gel/base.py | {
"start": 2481,
"end": 10731
} | class ____(BaseKVStore):
"""Gel Key-Value store."""
def __init__(self, record_type: str = "Record") -> None:
"""
Initialize GelKVStore.
Args:
record_type: The name of the record type in Gel schema.
"""
self.record_type = record_type
self._sync_clie... | GelKVStore |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 45248,
"end": 47171
} | class ____(TypedDict, total=False):
type: Required[Literal['enum']]
cls: Required[Any]
members: Required[list[Any]]
sub_type: Literal['str', 'int', 'float']
missing: Callable[[Any], Any]
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def enum_schema(
cl... | EnumSchema |
python | pennersr__django-allauth | allauth/socialaccount/providers/mediawiki/provider.py | {
"start": 445,
"end": 821
} | class ____(ProviderAccount):
def get_profile_url(self):
userpage = settings.get(
"USERPAGE_TEMPLATE", "https://meta.wikimedia.org/wiki/User:{username}"
)
username = self.account.extra_data.get("username")
if not username:
return None
return userpage.fo... | MediaWikiAccount |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 10590,
"end": 10692
} | class ____(json.JSON):
def result_processor(self, dialect, coltype):
return None
| AsyncpgJSON |
python | pypa__pipenv | pipenv/vendor/click/exceptions.py | {
"start": 8356,
"end": 8880
} | class ____(ClickException):
"""Raised if a file cannot be opened."""
def __init__(self, filename: str, hint: t.Optional[str] = None) -> None:
if hint is None:
hint = _("unknown error")
super().__init__(hint)
self.ui_filename: str = format_filename(filename)
self.fil... | FileError |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/steps/changelog.py | {
"start": 445,
"end": 2648
} | class ____(StepModifyingFiles):
context: ConnectorContext
title = "Add changelog entry"
def __init__(
self,
context: ConnectorContext,
documentation_directory: Directory,
new_version: str,
comment: str,
pull_request_number: str | int | None,
) -> None:
... | AddChangelogEntry |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 48029,
"end": 52197
} | class ____:
def test_vs_nonmasked(self):
x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
assert_array_almost_equal(mstats.normaltest(x),
stats.normaltest(x))
assert_array_almost_equal(mstats.skewtest(x),
stats.skewtest(x))
... | TestNormalitytests |
python | PrefectHQ__prefect | tests/server/models/test_filters.py | {
"start": 15066,
"end": 22211
} | class ____:
params = [
[{}, 12],
[dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1", "f-2"]))), 8],
[dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1", "f-100"]))), 5],
[dict(flow_filter=filters.FlowFilter(name=dict(any_=["f-1"]))), 5],
[dict(flow_filter=filte... | TestCountFlowRunModels |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_materializations.py | {
"start": 369,
"end": 4332
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_materializations(self, graphql_context: WorkspaceRequestContext, snapshot):
selector = infer_job_selector(graphql_context, "materialization_job")
logs = sync_execute_get_events(
context=graphql_context,
variables={
... | TestMaterializations |
python | fluentpython__example-code-2e | 22-dyn-attr-prop/oscon/schedule_v3.py | {
"start": 888,
"end": 2070
} | class ____(Record):
def __repr__(self):
try:
return f'<{self.__class__.__name__} {self.name!r}>'
except AttributeError:
return super().__repr__()
@property
def venue(self):
key = f'venue.{self.venue_serial}'
return self.__class__.fetch(key)
# tag::S... | Event |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/text/sentence.py | {
"start": 999,
"end": 12616
} | class ____(MetadataAwareTextSplitter):
"""
Parse text with a preference for complete sentences.
In general, this class tries to keep sentences and paragraphs together. Therefore
compared to the original TokenTextSplitter, there are less likely to be
hanging sentences or parts of sentences at the en... | SentenceSplitter |
python | cherrypy__cherrypy | cherrypy/tutorial/tut10_http_errors.py | {
"start": 333,
"end": 3023
} | class ____(object):
"""HTTP error representation app."""
# Set a custom response for 403 errors.
_cp_config = {'error_page.403': os.path.join(curpath, 'custom_error.html')}
@cherrypy.expose
def index(self):
"""Produce HTTP response body of error display app index URI."""
# display ... | HTTPErrorDemo |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 2756,
"end": 2883
} | class ____(TypedDict):
success: bool
message: str | None
data: list[AnomalyThresholdDataPoint]
| SeerDetectorDataResponse |
python | ethereum__web3.py | tests/utils.py | {
"start": 81,
"end": 2157
} | class ____:
def __init__(self, initial_delay=0, max_delay=1, initial_step=0.01):
self.initial_delay = initial_delay
self.initial_step = initial_step
self.max_delay = max_delay
self.current_delay = initial_delay
def __call__(self):
delay = self.current_delay
if s... | PollDelayCounter |
python | doocs__leetcode | solution/1800-1899/1861.Rotating the Box/Solution.py | {
"start": 0,
"end": 660
} | class ____:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
m, n = len(box), len(box[0])
ans = [[None] * m for _ in range(n)]
for i in range(m):
for j in range(n):
ans[j][m - i - 1] = box[i][j]
for j in range(m):
q = deque()
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 460303,
"end": 461023
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
AcceptEnterpriseAdministratorInvitation
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "invitation", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique ... | AcceptEnterpriseAdministratorInvitationPayload |
python | doocs__leetcode | solution/2500-2599/2582.Pass the Pillow/Solution.py | {
"start": 0,
"end": 222
} | class ____:
def passThePillow(self, n: int, time: int) -> int:
ans = k = 1
for _ in range(time):
ans += k
if ans == 1 or ans == n:
k *= -1
return ans
| Solution |
python | django__django | tests/lookup/models.py | {
"start": 925,
"end": 1089
} | class ____(models.Model):
articles = models.ManyToManyField(Article)
name = models.CharField(max_length=100)
class Meta:
ordering = ("name",)
| Tag |
python | tensorflow__tensorflow | tensorflow/python/grappler/layout_optimizer_test.py | {
"start": 7422,
"end": 83195
} | class ____(test.TestCase):
"""Tests the Grappler layout optimizer."""
def _assert_trans_nchw_to_nhwc(self, name, nodes):
self.assertIn(name + '-TransposeNCHWToNHWC-LayoutOptimizer', nodes)
def _assert_trans_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-TransposeNHWCToNCHW-LayoutOptimizer', nod... | LayoutOptimizerTest |
python | PrefectHQ__prefect | tests/input/test_actions.py | {
"start": 318,
"end": 580
} | class ____(pydantic.BaseModel):
name: str
age: int
@pytest.fixture
def flow_run_context(flow_run, prefect_client):
with FlowRunContext.model_construct(
flow_run=flow_run, client=prefect_client
) as context:
yield context
| DemoModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/compute.py | {
"start": 10961,
"end": 18714
} | class ____(ComputeEngineBaseOperator):
"""
Creates an Instance in Google Compute Engine based on specified parameters from existing Template.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ComputeEngineInsertInstanceFromTemplate... | ComputeEngineInsertInstanceFromTemplateOperator |
python | plotly__plotly.py | plotly/graph_objs/barpolar/marker/_pattern.py | {
"start": 233,
"end": 15295
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.marker"
_path_str = "barpolar.marker.pattern"
_valid_props = {
"bgcolor",
"bgcolorsrc",
"fgcolor",
"fgcolorsrc",
"fgopacity",
"fillmode",
"path",
"pathsrc",
"shape",
... | Pattern |
python | huggingface__transformers | src/transformers/models/bros/processing_bros.py | {
"start": 707,
"end": 1129
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"add_special_tokens": True,
"padding": False,
"stride": 0,
"return_overflowing_tokens": False,
"return_special_tokens_mask": False,
"return_offsets_mapping": Fals... | BrosProcessorKwargs |
python | openai__openai-python | src/openai/resources/responses/input_items.py | {
"start": 898,
"end": 4328
} | class ____(SyncAPIResource):
@cached_property
def with_raw_response(self) -> InputItemsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.githu... | InputItems |
python | walkccc__LeetCode | solutions/1255. Maximum Score Words Formed by Letters/1255.py | {
"start": 0,
"end": 812
} | class ____:
def maxScoreWords(
self,
words: list[str],
letters: list[str],
score: list[int],
) -> int:
count = collections.Counter(letters)
def useWord(i: int) -> int:
isValid = True
earned = 0
for c in words[i]:
count[c] -= 1
if count[c] < 0:
... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 52317,
"end": 54054
} | class ____(RRuleLocator):
"""
Make ticks on a given day of each year that is a multiple of base.
Examples::
# Tick every year on Jan 1st
locator = YearLocator()
# Tick every 5 years on July 4th
locator = YearLocator(5, month=7, day=4)
"""
def __init__(self, base=1, month=1... | YearLocator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/vertex_ai/pipeline_job.py | {
"start": 1964,
"end": 24535
} | class ____(GoogleBaseHook, OperationHelper):
"""Hook for Google Cloud Vertex AI Pipeline Job APIs."""
def __init__(
self,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(
... | PipelineJobHook |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 19191,
"end": 19975
} | class ____(nn.Module):
def __init__(self, config: EfficientLoFTRConfig):
super().__init__()
hidden_size = config.hidden_size
intermediate_size = config.intermediate_size
self.fc1 = nn.Linear(hidden_size * 2, intermediate_size, bias=False)
self.activation = ACT2FN[config.mlp_a... | EfficientLoFTRMLP |
python | tensorflow__tensorflow | tensorflow/lite/python/convert.py | {
"start": 5076,
"end": 44930
} | class ____(enum.Enum):
"""Enum class defining the sets of ops available to generate TFLite models.
WARNING: Experimental interface, subject to change.
"""
# Convert model using TensorFlow Lite builtin ops.
TFLITE_BUILTINS = "TFLITE_BUILTINS"
# Convert model using TensorFlow ops. Not all TensorFlow ops ar... | OpsSet |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_wpwazpcdm.py | {
"start": 7890,
"end": 11683
} | class ____(FlatFLRWMixinTest, TestwpwaCDM):
"""Test :class:`astropy.cosmology.FlatwpwaCDM`."""
def setup_class(self):
"""Setup for testing."""
super().setup_class(self)
self.cls = FlatwpwaCDM
def test_repr(self, cosmo_cls, cosmo):
"""Test method ``.__repr__()``."""
... | TestFlatwpwaCDM |
python | getsentry__sentry | src/sentry/db/postgres/transactions.py | {
"start": 2214,
"end": 4486
} | class ____(threading.local):
enabled = True
in_test_transaction_enforcement = InTestTransactionEnforcement()
@contextlib.contextmanager
def in_test_hide_transaction_boundary() -> Generator[None]:
"""
In production, has no effect.
In tests, it hides 'in_test_assert_no_transaction' invocations against... | InTestTransactionEnforcement |
python | lazyprogrammer__machine_learning_examples | rl3/a2c/atari_wrappers.py | {
"start": 3335,
"end": 4420
} | class ____(gym.Wrapper):
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
gym.Wrapper.__init__(self, env)
# most recent raw observations (for max pooling across time steps)
self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype='uint8')
... | MaxAndSkipEnv |
python | doocs__leetcode | solution/1200-1299/1233.Remove Sub-Folders from the Filesystem/Solution2.py | {
"start": 593,
"end": 814
} | class ____:
def removeSubfolders(self, folder: List[str]) -> List[str]:
trie = Trie()
for i, f in enumerate(folder):
trie.insert(i, f)
return [folder[i] for i in trie.search()]
| Solution |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 168812,
"end": 182172
} | class ____(Qwen3OmniMoePreTrainedModel, GenerationMixin):
config_class = Qwen3OmniMoeConfig
output_modalities = ("text", "audio")
def __init__(self, config: Qwen3OmniMoeConfig):
super().__init__(config)
self.thinker = Qwen3OmniMoeThinkerForConditionalGeneration._from_config(config.thinker_... | Qwen3OmniMoeForConditionalGeneration |
python | kubernetes-client__python | kubernetes/client/models/v1_env_var_source.py | {
"start": 383,
"end": 6895
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1EnvVarSource |
python | realpython__materials | python-313/free-threading-jit/benchmarks/pyfeatures.py | {
"start": 1061,
"end": 1463
} | class ____(Feature):
def __init__(self):
super().__init__("JIT Compiler")
@property
def supported(self) -> bool:
return "_Py_JIT" in sysconfig.get_config_var("PY_CORE_CFLAGS")
@property
def enabled(self) -> bool:
if sys.version_info >= (3, 13):
return _testinter... | JitCompiler |
python | python__mypy | test-data/unit/plugins/arg_names.py | {
"start": 189,
"end": 1713
} | class ____(Plugin):
def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
if fullname in {
"mod.func",
"mod.func_unfilled",
"mod.func_star_expr",
"mod.ClassInit",
"mod.Outer.NestedClassInit",
}:
... | ArgNamesPlugin |
python | dask__distributed | distributed/client.py | {
"start": 219150,
"end": 221594
} | class ____:
"""Collect task metadata within a context block
This gathers ``TaskState`` metadata and final state from the scheduler
for tasks which are submitted and finished within the scope of this
context manager.
Examples
--------
>>> with get_task_metadata() as tasks:
... x.com... | get_task_metadata |
python | getsentry__sentry | src/sentry/auth/providers/github/views.py | {
"start": 1081,
"end": 3447
} | class ____(AuthView):
def __init__(
self, org: RpcOrganization | dict[str, Any] | None = None, *args: Any, **kwargs: Any
) -> None:
self.org = org
super().__init__(*args, **kwargs)
def handle(self, request: HttpRequest, pipeline: AuthHelper) -> HttpResponseBase:
data: dict[s... | FetchUser |
python | jazzband__django-simple-history | simple_history/tests/tests/test_templatetags.py | {
"start": 103,
"end": 132
} | class ____:
bar = "bar"
| Foo |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 19128,
"end": 25425
} | class ____(BlenderbotSmallPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
[`BlenderbotSmallEncoderLayer`].
Args:
config: BlenderbotSmallConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(s... | BlenderbotSmallEncoder |
python | ray-project__ray | python/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist_trainable.py | {
"start": 636,
"end": 5822
} | class ____(tune.Trainable):
def setup(self, config):
use_cuda = config.get("use_gpu") and torch.cuda.is_available()
self.device = torch.device("cuda" if use_cuda else "cpu")
self.netD = Discriminator().to(self.device)
self.netD.apply(weights_init)
self.netG = Generator().to(s... | PytorchTrainable |
python | pytorch__pytorch | test/inductor/test_provenance_tracing.py | {
"start": 1374,
"end": 1601
} | class ____(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, a, b, c):
x = a * 3.14
y = torch.addmm(c, x, b)
z = torch.nn.functional.gelu(y)
return z
| Model |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/missing_maxsplit_arg.py | {
"start": 15,
"end": 162
} | class ____(str):
class_str = "1,2,3"
def split(self, sep=None, maxsplit=-1) -> list[str]:
return super().split(sep, maxsplit)
| Foo |
python | sympy__sympy | sympy/physics/paulialgebra.py | {
"start": 1436,
"end": 6002
} | class ____(Symbol):
"""
The class representing algebraic properties of Pauli matrices.
Explanation
===========
The symbol used to display the Pauli matrices can be changed with an
optional parameter ``label="sigma"``. Pauli matrices with different
``label`` attributes cannot multiply toget... | Pauli |
python | openai__openai-python | src/openai/types/beta/realtime/session.py | {
"start": 2651,
"end": 4272
} | class ____(BaseModel):
create_response: Optional[bool] = None
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None
"""Used only for `semantic_vad` mode.
The eagerness of the model ... | TurnDetection |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called.py | {
"start": 133,
"end": 501
} | class ____(ctypes.BigEndianStructure):
"""This class should not emit a super-init-not-called warning.
It previously did, because ``next(node.infer())`` was used in that checker's logic
and the first inferred node was an Uninferable object, leading to this false positive.
"""
def __init__(self):
... | Foo |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 107750,
"end": 108012
} | class ____(BaseModel, extra="forbid"):
shard_id: int = Field(..., description="")
from_peer_id: int = Field(..., description="")
to_peer_id: int = Field(..., description="")
method: "ShardTransferMethod" = Field(..., description="")
| RestartTransfer |
python | getsentry__sentry | src/sentry/relay/types/rule_condition.py | {
"start": 1296,
"end": 1538
} | class ____(TypedDict):
"""Glob pattern matching condition
Glob matching is done in Relay with the following crate: https://docs.rs/globset/latest/globset
"""
op: Literal["glob"]
name: str
value: list[str]
| GlobCondition |
python | mwaskom__seaborn | tests/_core/test_properties.py | {
"start": 8710,
"end": 12410
} | class ____(DataFixtures):
def assert_equal(self, a, b):
assert self.unpack(a) == self.unpack(b)
def unpack(self, x):
return x
@pytest.mark.parametrize("data_type", ["cat", "num", "bool"])
def test_default(self, data_type, vectors):
scale = self.prop().default_scale(vectors[d... | ObjectPropertyBase |
python | dagster-io__dagster | python_modules/automation/automation/parse_dataproc_configs.py | {
"start": 359,
"end": 1337
} | class ____:
def __init__(self, name, enum_names, enum_descriptions):
self.name = name
self.enum_names = enum_names
self.enum_descriptions = enum_descriptions
def write(self, printer):
capitalized_name = self.name[0].upper() + self.name[1:]
printer.line(capitalized_name +... | Enum |
python | ansible__ansible | lib/ansible/module_utils/common/sentinel.py | {
"start": 168,
"end": 2372
} | class ____:
"""
Object which can be used to mark whether an entry as being special
A sentinel value demarcates a value or marks an entry as having a special meaning. In C, the
Null byte is used as a sentinel for the end of a string. In Python, None is often used as
a Sentinel in optional paramete... | Sentinel |
python | graphql-python__graphene | graphene/relay/node.py | {
"start": 549,
"end": 1520
} | class ____(Field):
def __init__(
self,
node=None,
parent_type=None,
required=True,
global_id_type=DefaultGlobalIDType,
*args,
**kwargs,
):
super(GlobalID, self).__init__(
global_id_type.graphene_type, required=required, *args, **kwargs
... | GlobalID |
python | davidhalter__jedi | test/completion/recursion.py | {
"start": 1340,
"end": 1587
} | class ____:
def a(self, b):
for i in b:
for i in self.a(i):
#?
yield i
foo = int
foo = foo # type: foo
#? int
foo
while True:
bar = int
bar = bar # type: bar
#? int()
bar
| B |
python | falconry__falcon | falcon/routing/compiled.py | {
"start": 1896,
"end": 29915
} | class ____:
"""Fast URI router which compiles its routing logic to Python code.
Generally you do not need to use this router class directly, as an
instance is created by default when the falcon.App class is initialized.
The router treats URI paths as a tree of URI segments and searches by
checking... | CompiledRouter |
python | facebook__pyre-check | client/commands/daemon_querier.py | {
"start": 1050,
"end": 1187
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
response: List[str]
@dataclasses.dataclass(frozen=True)
| QueryModulesOfPathResponse |
python | numba__numba | numba/np/ufunc/dufunc.py | {
"start": 836,
"end": 5444
} | class ____:
def __init__(self, ufunc, a, a_ty, indices, indices_ty, b=None, b_ty=None):
self.ufunc = ufunc
self.a = a
self.a_ty = a_ty
self.indices = indices
self.indices_ty = indices_ty
self.b = b
self.b_ty = b_ty
def run(self, context, builder):
... | UfuncAtIterator |
python | TheAlgorithms__Python | machine_learning/decision_tree.py | {
"start": 5738,
"end": 7212
} | class ____:
"""Decision Tres test class"""
@staticmethod
def helper_mean_squared_error_test(labels, prediction):
"""
helper_mean_squared_error_test:
@param labels: a one dimensional numpy array
@param prediction: a floating point value
return value: helper_mean_squar... | TestDecisionTree |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 99009,
"end": 100718
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | Qwen2_5OmniTalkerCausalLMOutputWithPast |
python | bokeh__bokeh | tests/unit/bokeh/core/test_properties.py | {
"start": 15605,
"end": 15636
} | class ____(HasProps):
pass
| Foo |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/abstractClass8.py | {
"start": 203,
"end": 421
} | class ____(Foo):
@abstractmethod
def bar(self):
pass
@abstractmethod
def bar2(self):
pass
@final
# This should generate an error because Foo.foo, Bar.bar, and Bar.bar1
# are abstract.
| Bar |
python | mwaskom__seaborn | seaborn/relational.py | {
"start": 14853,
"end": 34630
} | class ____(_RelationalPlotter):
_legend_attributes = ["color", "s", "marker"]
def __init__(self, *, data=None, variables={}, legend=None):
# TODO this is messy, we want the mapping to be agnostic about
# the kind of plot to draw, but for the time being we need to set
# this informatio... | _ScatterPlotter |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dynamic.py | {
"start": 9285,
"end": 9835
} | class ____(_AppenderMixin[_T], Query[_T]): # type: ignore[misc]
"""A dynamic query that supports basic collection storage operations.
Methods on :class:`.AppenderQuery` include all methods of
:class:`_orm.Query`, plus additional methods used for collection
persistence.
"""
def mixin_user_query... | AppenderQuery |
python | huggingface__transformers | src/transformers/models/chameleon/modeling_chameleon.py | {
"start": 43883,
"end": 50197
} | class ____(ChameleonPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = ChameleonModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(confi... | ChameleonForConditionalGeneration |
python | Pylons__pyramid | tests/test_scripts/test_pshell.py | {
"start": 14378,
"end": 14537
} | class ____:
def __init__(self, name, value):
self.name = name
self.value = value
def load(self):
return self.value
| DummyEntryPoint |
python | pennersr__django-allauth | allauth/headless/tokens/views.py | {
"start": 428,
"end": 1054
} | class ____(APIView):
input_class = RefreshTokenInput
def post(self, request: HttpRequest):
refresh_token = self.input.cleaned_data["refresh_token"]
strategy: AbstractTokenStrategy = app_settings.TOKEN_STRATEGY
at_rt = strategy.refresh_token(refresh_token)
if at_rt is None:
... | RefreshTokenView |
python | django__django | tests/backends/sqlite/tests.py | {
"start": 5455,
"end": 7720
} | class ____(TransactionTestCase):
available_apps = ["backends"]
def test_autoincrement(self):
"""
auto_increment fields are created with the AUTOINCREMENT keyword
in order to be monotonically increasing (#10164).
"""
with connection.schema_editor(collect_sql=True) as edit... | SchemaTests |
python | Textualize__textual | docs/examples/widgets/selection_list_tuples.py | {
"start": 103,
"end": 769
} | class ____(App[None]):
CSS_PATH = "selection_list.tcss"
def compose(self) -> ComposeResult:
yield Header()
yield SelectionList[int]( # (1)!
("Falken's Maze", 0, True),
("Black Jack", 1),
("Gin Rummy", 2),
("Hearts", 3),
("Bridge", 4),... | SelectionListApp |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_striphmtl.py | {
"start": 54,
"end": 1053
} | class ____(util.MdCase):
"""Test legacy stripping in HTML."""
extension = ['pymdownx.striphtml']
extension_configs = {}
def test_multiple_inline(self):
"""Test multiple inline."""
self.check_markdown(
r'''
Comments test:
<!-- BEGIN INCLUDE -->
... | TestStripHTML |
python | django__django | tests/gis_tests/relatedapp/models.py | {
"start": 1339,
"end": 1500
} | class ____(SimpleModel):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, models.SET_NULL, related_name="books", null=True)
| Book |
python | kamyu104__LeetCode-Solutions | Python/first-unique-character-in-a-string.py | {
"start": 66,
"end": 502
} | class ____(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lookup = defaultdict(int)
candidtates = set()
for i, c in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
... | Solution |
python | sphinx-doc__sphinx | tests/roots/test-ext-viewcode/spam/mod2.py | {
"start": 127,
"end": 166
} | class ____:
"""this is Class2"""
| Class2 |
python | python-pillow__Pillow | Tests/test_image.py | {
"start": 37986,
"end": 38871
} | class ____:
@pytest.mark.parametrize("mode", Image.MODES)
def test_roundtrip_bytes_constructor(self, mode: str) -> None:
im = hopper(mode)
source_bytes = im.tobytes()
reloaded = Image.frombytes(mode, im.size, source_bytes)
assert reloaded.tobytes() == source_bytes
@pytest.m... | TestImageBytes |
python | spyder-ide__spyder | spyder/plugins/run/api.py | {
"start": 7065,
"end": 7310
} | class ____(TypedDict):
"""Per run executor configuration parameters."""
# Dictionary that maps from parameter identifiers to the actual
# configuration.
params: Dict[str, ExtendedRunExecutionParameters]
| StoredRunExecutorParameters |
python | keras-team__keras | keras/src/metrics/confusion_metrics.py | {
"start": 6278,
"end": 7941
} | class ____(_ConfusionMatrixConditionCount):
"""Calculates the number of true negatives.
If `sample_weight` is given, calculates the sum of the weights of
true negatives. This metric creates one local variable, `accumulator`
that is used to keep track of the number of true negatives.
If `sample_wei... | TrueNegatives |
python | django__django | django/contrib/gis/db/models/aggregates.py | {
"start": 2610,
"end": 2920
} | class ____(GeoAggregate):
name = "Extent3D"
is_extent = "3D"
def __init__(self, expression, **extra):
super().__init__(expression, output_field=ExtentField(), **extra)
def convert_value(self, value, expression, connection):
return connection.ops.convert_extent3d(value)
| Extent3D |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_katz_centrality.py | {
"start": 10727,
"end": 11240
} | class ____:
@classmethod
def setup_class(cls):
global np
np = pytest.importorskip("numpy")
pytest.importorskip("scipy")
def test_eigenvector_v_katz_random(self):
G = nx.gnp_random_graph(10, 0.5, seed=1234)
l = max(np.linalg.eigvals(nx.adjacency_matrix(G).todense()))
... | TestKatzEigenvectorVKatz |
python | fsspec__filesystem_spec | fsspec/implementations/tests/memory/memory_test.py | {
"start": 349,
"end": 426
} | class ____(abstract.AbstractPipeTests, MemoryFixtures):
pass
| TestMemoryPipe |
python | django__django | django/db/migrations/operations/models.py | {
"start": 44444,
"end": 45901
} | class ____(IndexOperation):
category = OperationCategory.ALTERATION
option_name = "constraints"
def __init__(self, model_name, name, constraint):
self.model_name = model_name
self.name = name
self.constraint = constraint
def state_forwards(self, app_label, state):
state... | AlterConstraint |
python | ray-project__ray | python/ray/train/tensorflow/keras.py | {
"start": 3134,
"end": 5495
} | class ____(_Callback):
def __init__(
self,
checkpoint_on: Union[str, List[str]] = "epoch_end",
report_metrics_on: Union[str, List[str]] = "epoch_end",
metrics: Optional[Union[str, List[str], Dict[str, str]]] = None,
):
if isinstance(checkpoint_on, str):
checkp... | RayReportCallback |
python | ipython__ipython | IPython/utils/tempdir.py | {
"start": 350,
"end": 1264
} | class ____:
def __init__(self, filename, mode, bufsize=-1, add_to_syspath=False, **kwds):
"""
Open a file named `filename` in a temporary directory.
This context manager is preferred over `NamedTemporaryFile` in
stdlib `tempfile` when one needs to reopen the file.
Arguments... | NamedFileInTemporaryDirectory |
python | keras-team__keras | keras/src/legacy/layers.py | {
"start": 4673,
"end": 7406
} | class ____(Layer):
"""DEPRECATED."""
def __init__(self, factor, interpolation="bilinear", seed=None, **kwargs):
super().__init__(**kwargs)
self.seed_generator = backend.random.SeedGenerator(seed)
self.factor = factor
if isinstance(factor, (tuple, list)):
self.width_l... | RandomWidth |
python | kamyu104__LeetCode-Solutions | Python/escape-a-large-maze.py | {
"start": 80,
"end": 1533
} | class ____(object):
def isEscapePossible(self, blocked, source, target):
"""
:type blocked: List[List[int]]
:type source: List[int]
:type target: List[int]
:rtype: bool
"""
R, C = 10**6, 10**6
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
de... | Solution |
python | encode__django-rest-framework | tests/test_testing.py | {
"start": 2469,
"end": 9802
} | class ____(TestCase):
def setUp(self):
self.client = APIClient()
def test_credentials(self):
"""
Setting `.credentials()` adds the required headers to each request.
"""
self.client.credentials(HTTP_AUTHORIZATION='example')
for _ in range(0, 3):
respon... | TestAPITestClient |
python | openai__openai-python | src/openai/_extras/numpy_proxy.py | {
"start": 340,
"end": 805
} | class ____(LazyProxy[Any]):
@override
def __load__(self) -> Any:
try:
import numpy
except ImportError as err:
raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err
return numpy
if not TYPE_CHECKING:
numpy = NumpyProxy()
def has_numpy() -> bool:
tr... | NumpyProxy |
python | huggingface__transformers | tests/models/informer/test_modeling_informer.py | {
"start": 19398,
"end": 22764
} | class ____(unittest.TestCase):
def test_inference_no_head(self):
model = InformerModel.from_pretrained("huggingface/informer-tourism-monthly").to(torch_device)
batch = prepare_batch()
torch.manual_seed(0)
with torch.no_grad():
output = model(
past_values=... | InformerModelIntegrationTests |
python | getsentry__responses | responses/tests/test_recorder.py | {
"start": 5534,
"end": 7793
} | class ____:
def setup_method(self):
self.out_file = Path("response_record")
def teardown_method(self):
if self.out_file.exists():
self.out_file.unlink()
assert not self.out_file.exists()
@pytest.mark.parametrize("parser", (yaml, tomli_w))
def test_add_from_file(sel... | TestReplay |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 8226,
"end": 9195
} | class ____(ModelOutput):
r"""
audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*):
Decoded audio values, obtained using the decoder part of Mimi.
decoder_past_key_values (`Cache`, *optional*):
Pre-computed hidden-states (key and values in the self-attentio... | MimiDecoderOutput |
python | falconry__falcon | tests/test_cmd_inspect_app.py | {
"start": 602,
"end": 1049
} | class ____:
async def on_get(self, req, resp):
resp.text = 'Test\n'
resp.status = '200 OK'
def create_app(asgi):
app_cls = falcon.asgi.App if asgi else App
return app_cls()
def make_app(asgi=False):
app = create_app(asgi)
app.add_route('/test', DummyResourceAsync() if asgi else D... | DummyResourceAsync |
python | scrapy__scrapy | tests/test_downloadermiddleware_cookies.py | {
"start": 1996,
"end": 30475
} | class ____:
def assertCookieValEqual(self, first, second, msg=None):
def split_cookies(cookies):
return sorted([s.strip() for s in to_bytes(cookies).split(b";")])
assert split_cookies(first) == split_cookies(second), msg
def setup_method(self):
crawler = get_crawler(Default... | TestCookiesMiddleware |
python | pyparsing__pyparsing | tests/test_unit.py | {
"start": 395747,
"end": 402077
} | class ____(ppt.TestParseResultsAsserts, TestCase):
"""
Tests for recursive parsing
"""
suite_context = None
save_suite_context = None
def setUp(self):
recursion_suite_context.restore()
def tearDown(self):
default_suite_context.restore()
def test_repeat_as_recurse(self... | Test11_LR1_Recursion |
python | crytic__slither | slither/solc_parsing/declarations/custom_error.py | {
"start": 898,
"end": 4473
} | class ____(CallerContextExpression):
def __init__(
self,
custom_error: CustomError,
custom_error_data: dict,
contract_parser: Optional["ContractSolc"],
slither_parser: "SlitherCompilationUnitSolc",
) -> None:
self._slither_parser: "SlitherCompilationUnitSolc" = sl... | CustomErrorSolc |
python | pytorch__pytorch | torch/_inductor/analysis/profile_analysis.py | {
"start": 12585,
"end": 24523
} | class ____:
_devices: DeviceMap
def __init__(
self,
path: str,
benchmark_name: Optional[str] = None,
dtype: Optional[Union[torch.dtype, str]] = None,
):
"""
Convenience class for running common operations on chrome/perfetto json traces.
"""
se... | JsonProfile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.