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 | huggingface__transformers | tests/models/florence2/test_processing_florence2.py | {
"start": 923,
"end": 11654
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Florence2Processor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
image_processor = image_processor_class.from_pretrained("florence-commun... | Florence2ProcessorTest |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/line/_colorbar.py | {
"start": 233,
"end": 61634
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d.line"
_path_str = "scatter3d.line.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexpo... | ColorBar |
python | ray-project__ray | python/ray/serve/llm/__init__.py | {
"start": 809,
"end": 940
} | class ____(_LLMConfig):
"""The configuration for starting an LLM deployment."""
pass
@PublicAPI(stability="alpha")
| LLMConfig |
python | neetcode-gh__leetcode | python/0054-spiral-matrix.py | {
"start": 0,
"end": 949
} | class ____:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
left, right = 0, len(matrix[0])
top, bottom = 0, len(matrix)
while left < right and top < bottom:
# get every i in the top row
for i in range(left, right):
res.a... | Solution |
python | apache__airflow | providers/mysql/tests/unit/mysql/transfers/test_s3_to_mysql.py | {
"start": 1084,
"end": 4765
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
models.Connection(
conn_id="s3_test",
conn_type="s3",
schema="test",
extra='{"aws_access_key_id":... | TestS3ToMySqlTransfer |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-weighted-tree.py | {
"start": 535,
"end": 2274
} | class ____(object):
def treeQueries(self, n, edges, queries):
"""
:type n: int
:type edges: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
def iter_dfs():
L, R, dist, lookup = [0]*n, [0]*n, [0]*n, [0]*n
cnt = 0
... | Solution |
python | doocs__leetcode | solution/2100-2199/2154.Keep Multiplying Found Values by Two/Solution.py | {
"start": 0,
"end": 187
} | class ____:
def findFinalValue(self, nums: List[int], original: int) -> int:
s = set(nums)
while original in s:
original <<= 1
return original
| Solution |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 29885,
"end": 30514
} | class ____:
"""Holds counter state for invoking a method several times in a row."""
def __init__(self, count):
self.counter = 0
self.count = count
def go2(self):
raise OSError("Hi there, I'm an IOError")
def go(self):
"""Raise a NameError with an IOError as cause until... | NoIOErrorCauseAfterCount |
python | numpy__numpy | numpy/typing/tests/data/pass/ufunc_config.py | {
"start": 318,
"end": 403
} | class ____:
def write(self, a: str, b: int = 1) -> None:
return None
| Write2 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_eks.py | {
"start": 7301,
"end": 12792
} | class ____(TestEksTrigger):
def setup_method(self):
super().setup_method()
self.get_waiter_patcher = patch(
"airflow.providers.amazon.aws.hooks.eks.EksHook.get_waiter", return_value="waiter"
)
self.mock_waiter = self.get_waiter_patcher.start()
self.trigger = Eks... | TestEksDeleteClusterTriggerDeleteNodegroupsAndFargateProfiles |
python | numpy__numpy | numpy/_build_utils/tempita/_tempita.py | {
"start": 17165,
"end": 36992
} | class ____:
def __call__(self, *args, **kw):
return self
def __str__(self):
return ""
def __repr__(self):
return "Empty"
def __unicode__(self):
return ""
def __iter__(self):
return iter(())
def __bool__(self):
return False
Empty = _Empty()
d... | _Empty |
python | sympy__sympy | sympy/physics/quantum/cg.py | {
"start": 4480,
"end": 7162
} | class ____(Wigner3j):
r"""Class for Clebsch-Gordan coefficient.
Explanation
===========
Clebsch-Gordan coefficients describe the angular momentum coupling between
two systems. The coefficients give the expansion of a coupled total angular
momentum state and an uncoupled tensor product state. T... | CG |
python | doocs__leetcode | solution/2200-2299/2273.Find Resultant Array After Removing Anagrams/Solution.py | {
"start": 0,
"end": 426
} | class ____:
def removeAnagrams(self, words: List[str]) -> List[str]:
def check(s: str, t: str) -> bool:
if len(s) != len(t):
return True
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return True... | Solution |
python | pytorch__pytorch | tools/test/test_utils.py | {
"start": 62,
"end": 870
} | class ____(unittest.TestCase):
def test_create_from_namespaced_tuple(self) -> None:
helper = NamespaceHelper.from_namespaced_entity("aten::add")
self.assertEqual(helper.entity_name, "add")
self.assertEqual(helper.get_cpp_namespace(), "aten")
def test_default_namespace(self) -> None:
... | TestNamespaceHelper |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_method_docstrings.py | {
"start": 189,
"end": 12634
} | class ____:
"""Test that method docstrings are validated correctly and self/cls parameters are handled properly."""
# Using function-based validation approach
def test_instance_method_docstring_validation(self):
"""Test that instance method docstrings are validated correctly."""
@public
... | TestMethodDocstringValidation |
python | networkx__networkx | networkx/algorithms/isomorphism/temporalisomorphvf2.py | {
"start": 5084,
"end": 10946
} | class ____(DiGraphMatcher):
def __init__(self, G1, G2, temporal_attribute_name, delta):
"""Initialize TimeRespectingDiGraphMatcher.
G1 and G2 should be nx.DiGraph or nx.MultiDiGraph instances.
Examples
--------
To create a TimeRespectingDiGraphMatcher which checks for
... | TimeRespectingDiGraphMatcher |
python | kubernetes-client__python | kubernetes/client/models/v1_runtime_class.py | {
"start": 383,
"end": 9352
} | 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... | V1RuntimeClass |
python | ray-project__ray | rllib/examples/envs/classes/random_env.py | {
"start": 4272,
"end": 4630
} | class ____(RandomEnv):
def __init__(self, config=None):
config = config or {}
config.update(
{
"observation_space": gym.spaces.Box(-1.0, 1.0, (5000,)),
"action_space": gym.spaces.Box(-1.0, 1.0, (5,)),
}
)
super().__init__(config... | RandomLargeObsSpaceEnvContActions |
python | Textualize__textual | docs/examples/guide/widgets/hello04.py | {
"start": 363,
"end": 909
} | class ____(Static):
"""Display a greeting."""
DEFAULT_CSS = """
Hello {
width: 40;
height: 9;
padding: 1 2;
background: $panel;
border: $secondary tall;
content-align: center middle;
}
"""
def on_mount(self) -> None:
self.next_word()
... | Hello |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial003_py310.py | {
"start": 71,
"end": 1548
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLM... | Hero |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 11050,
"end": 11584
} | class ____:
def setup(self):
dti = date_range("2016-01-01", periods=10000, tz="US/Pacific")
index = np.array(dti)
unsorted_index = index.copy()
unsorted_index[10] = unsorted_index[20]
self.df_unsorted = DataFrame(index=unsorted_index, data={"a": 1})
self.df_sort = D... | SortedAndUnsortedDatetimeIndexLoc |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/text_area_unfocus.py | {
"start": 153,
"end": 433
} | class ____(App):
AUTO_FOCUS = None
def compose(self) -> ComposeResult:
text_area = TextArea.code_editor()
text_area.cursor_blink = False
yield text_area
app = TextAreaUnfocusSnapshot()
if __name__ == "__main__":
app.run()
| TextAreaUnfocusSnapshot |
python | huggingface__transformers | src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py | {
"start": 1600,
"end": 2258
} | class ____(PreTrainedModel):
config: GPTNeoXJapaneseConfig
base_model_prefix = "gpt_neox_japanese"
_no_split_modules = ["GPTNeoXJapaneseLayer"]
_skip_keys_device_placement = "past_key_values"
_can_compile_fullgraph = True
@torch.no_grad()
def _init_weights(self, module):
"""Initiali... | GPTNeoXJapanesePreTrainedModel |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/runtime_types_tests/test_types.py | {
"start": 7443,
"end": 20490
} | class ____(Exception):
# Made to make exception explicit so that we aren't accidentally masking other Exceptions
pass
def _always_fails(_, _value):
raise AlwaysFailsException("kdjfkjd")
ThrowsExceptionType = dg.DagsterType(
name="ThrowsExceptionType",
type_check_fn=_always_fails,
)
def _return... | AlwaysFailsException |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test_base.py | {
"start": 1434,
"end": 13207
} | class ____(test.TestCase):
def _opFwdBwd(self, labels, logits):
"""Runs the op-under-test both forwards and backwards"""
logits = ops_lib.convert_to_tensor(logits) # needed for the gradient tape
with backprop_lib.GradientTape() as tape:
tape.watch(logits)
loss = nn_ops.sparse_softmax_cross_e... | SparseXentOpTestBase |
python | walkccc__LeetCode | solutions/3193. Count the Number of Inversions/3193.py | {
"start": 0,
"end": 893
} | class ____:
def numberOfPermutations(self, n: int, requirements: list[list[int]]) -> int:
MOD = 1_000_000_007
MAX_INVERSIONS = 400
# dp[i][j] := the number of ways to arrange the first i numbers of the
# permutation s.t. there are j inversions
dp = [[0] * (MAX_INVERSIONS + 1) for _ in range(n + 1)... | Solution |
python | celery__celery | t/unit/utils/test_platforms.py | {
"start": 3473,
"end": 5224
} | class ____:
@patch('signal.getsignal')
def test_getitem(self, getsignal):
signals['SIGINT']
getsignal.assert_called_with(signal.SIGINT)
def test_supported(self):
assert signals.supported('INT')
assert not signals.supported('SIGIMAGINARY')
@t.skip.if_win32
def test_... | test_Signals |
python | huggingface__transformers | tests/models/ibert/test_modeling_ibert.py | {
"start": 15016,
"end": 31207
} | class ____(unittest.TestCase):
def test_quant_embedding(self):
weight_bit = 8
embedding = QuantEmbedding(2, 4, quant_mode=True, weight_bit=weight_bit)
embedding_weight = torch.tensor([[-1.0, -2.0, -3.0, -4.0], [5.0, 6.0, 7.0, 8.0]])
embedding.weight = nn.Parameter(embedding_weight)
... | IBertModelIntegrationTest |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triangulation.py | {
"start": 62,
"end": 9784
} | class ____:
"""
An unstructured triangular grid consisting of npoints points and
ntri triangles. The triangles can either be specified by the user
or automatically generated using a Delaunay triangulation.
Parameters
----------
x, y : (npoints,) array-like
Coordinates of grid point... | Triangulation |
python | pandas-dev__pandas | pandas/tests/indexes/base_class/test_where.py | {
"start": 76,
"end": 341
} | class ____:
def test_where_intlike_str_doesnt_cast_ints(self):
idx = Index(range(3))
mask = np.array([True, False, True])
res = idx.where(mask, "2")
expected = Index([0, "2", 2])
tm.assert_index_equal(res, expected)
| TestWhere |
python | doocs__leetcode | solution/0300-0399/0382.Linked List Random Node/Solution.py | {
"start": 151,
"end": 615
} | class ____:
def __init__(self, head: Optional[ListNode]):
self.head = head
def getRandom(self) -> int:
n = ans = 0
head = self.head
while head:
n += 1
x = random.randint(1, n)
if n == x:
ans = head.val
head = head.n... | Solution |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 4706,
"end": 4859
} | class ____(ShowFieldTypeAndContent, Model2A):
objects = MyManagerQuerySet.as_manager()
field4 = models.CharField(max_length=30)
| ModelWithMyManager2 |
python | ray-project__ray | python/ray/tune/progress_reporter.py | {
"start": 15985,
"end": 16582
} | class ____:
"""Remote reporter abstract mixin class.
Subclasses of this class will use a Ray Queue to display output
on the driver side when running Ray Client."""
@property
def output_queue(self) -> Queue:
return getattr(self, "_output_queue", None)
@output_queue.setter
def outpu... | RemoteReporterMixin |
python | walkccc__LeetCode | solutions/211. Add and Search Word - Data structure design/211.py | {
"start": 108,
"end": 762
} | class ____:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node: TrieNode = self.root
for c in word:
node = node.children.setdefault(c, TrieNode())
node.isWord = True
def search(self, word: str) -> bool:
return self._dfs(word, 0, self.root)
def _dfs... | WordDictionary |
python | django__django | tests/expressions/tests.py | {
"start": 112747,
"end": 113317
} | class ____(SimpleTestCase):
def test_empty_group_by(self):
expr = ExpressionWrapper(Value(3), output_field=IntegerField())
self.assertEqual(expr.get_group_by_cols(), [])
def test_non_empty_group_by(self):
value = Value("f")
value.output_field = None
expr = ExpressionWrap... | ExpressionWrapperTests |
python | docker__docker-py | tests/integration/api_exec_test.py | {
"start": 270,
"end": 8273
} | class ____(BaseAPIIntegrationTest):
def test_execute_command_with_proxy_env(self):
# Set a custom proxy config on the client
self.client._proxy_configs = ProxyConfig(
ftp='a', https='b', http='c', no_proxy='d'
)
container = self.client.create_container(
TEST_... | ExecTest |
python | pdm-project__pdm | src/pdm/cli/commands/new.py | {
"start": 172,
"end": 811
} | class ____(InitCommand):
"""Create a new Python project at <project_path>"""
supports_other_generator = False
arguments = (verbose_option,)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
super().add_arguments(parser)
parser.add_argument("project_path", help="The pat... | Command |
python | paramiko__paramiko | tests/test_transport.py | {
"start": 38834,
"end": 41747
} | class ____(unittest.TestCase):
def test_preferred_lists_default_to_private_attribute_contents(self):
t = Transport(sock=Mock())
assert t.preferred_ciphers == t._preferred_ciphers
assert t.preferred_macs == t._preferred_macs
assert t.preferred_keys == tuple(
t._preferred_k... | AlgorithmDisablingTests |
python | realpython__materials | geoshops/nearbyshops/admin.py | {
"start": 132,
"end": 202
} | class ____(OSMGeoAdmin):
list_display = ("name", "location")
| ShopAdmin |
python | crytic__slither | slither/utils/halstead.py | {
"start": 1204,
"end": 4673
} | class ____:
"""Class to hold the Halstead metrics for a single contract."""
contract: Contract
all_operators: List[str] = field(default_factory=list)
all_operands: List[str] = field(default_factory=list)
n1: int = 0
n2: int = 0
N1: int = 0
N2: int = 0
n: int = 0
N: int = 0
S... | HalsteadContractMetrics |
python | pandas-dev__pandas | pandas/tests/tools/test_to_timedelta.py | {
"start": 392,
"end": 11254
} | class ____:
def test_to_timedelta_none(self):
# GH#23055
assert to_timedelta(None) is pd.NaT
def test_to_timedelta_dt64_raises(self):
# Passing datetime64-dtype data to TimedeltaIndex is no longer
# supported GH#29794
msg = r"dtype datetime64\[ns\] cannot be converted t... | TestTimedeltas |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 21676,
"end": 23429
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.attention = UniSpeechSatAttention(
embed_dim=config.hidden_size,
num_heads=config.num_attention_heads,
dropout=config.attention_dropout,
is_decoder=False,
... | UniSpeechSatEncoderLayerStableLayerNorm |
python | astropy__astropy | astropy/io/fits/column.py | {
"start": 15613,
"end": 18219
} | class ____:
"""
Descriptor for attributes of `Column` that are associated with keywords
in the FITS header and describe properties of the column as specified in
the FITS standard.
Each `ColumnAttribute` may have a ``validator`` method defined on it.
This validates values set on this attribute t... | ColumnAttribute |
python | numpy__numpy | tools/swig/test/testFlat.py | {
"start": 5240,
"end": 5501
} | class ____(FlatTestCase):
def __init__(self, methodName="runTest"):
FlatTestCase.__init__(self, methodName)
self.typeStr = "float"
self.typeCode = "f"
######################################################################
| floatTestCase |
python | sympy__sympy | sympy/stats/drv.py | {
"start": 6617,
"end": 9520
} | class ____(PSpace):
is_real = True
is_Discrete = True
@property
def pdf(self):
return self.density(*self.symbols)
def where(self, condition):
rvs = random_symbols(condition)
assert all(r.symbol in self.symbols for r in rvs)
if len(rvs) > 1:
raise NotImpl... | DiscretePSpace |
python | walkccc__LeetCode | solutions/2901. Longest Unequal Adjacent Groups Subsequence II/2901.py | {
"start": 0,
"end": 824
} | class ____:
def getWordsInLongestSubsequence(
self,
n: int,
words: list[str],
groups: list[int],
) -> list[str]:
ans = []
# dp[i] := the length of the longest subsequence ending in `words[i]`
dp = [1] * n
# prev[i] := the best index of words[i]
prev = [-1] * n
for i ... | Solution |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 34149,
"end": 34187
} | class ____(Session):
pass
| _MySession |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 41946,
"end": 43662
} | class ____(BaseConfigOption[List[types.ModuleType]]):
"""A list of Python scripts to be treated as instances of plugins."""
def __init__(self, plugins_key: str) -> None:
super().__init__()
self.default = []
self.plugins_key = plugins_key
def pre_validation(self, config: Config, key... | Hooks |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 832164,
"end": 832964
} | class ____(sgqlc.types.Type):
"""Information about pagination in a connection."""
__schema__ = github_schema
__field_names__ = ("end_cursor", "has_next_page", "has_previous_page", "start_cursor")
end_cursor = sgqlc.types.Field(String, graphql_name="endCursor")
"""When paginating forwards, the curso... | PageInfo |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_has_measurements.py | {
"start": 247,
"end": 6937
} | class ____(APITestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
self.two_min_ago = before_now(minutes=2)
self.transaction_data = load_data("transaction", timestamp=before_now(minutes=1))
self.features: dict[str, bool] = {}... | OrganizationEventsHasMeasurementsTest |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 3334,
"end": 3594
} | class ____:
pass
class_list = [WithForward | DefaultMetaclass]
class_list_reversed_invalid = [WithReverse | DefaultMetaclass] # [unsupported-binary-operation]
class_list_reversed_valid = [DefaultMetaclass | WithReverse]
# Pathological cases
| DefaultMetaclass |
python | numba__numba | numba/core/callconv.py | {
"start": 36635,
"end": 37551
} | class ____(ErrorModel):
"""
In the Numpy error model, floating-point errors don't raise an
exception. The FPU exception state is inspected by Numpy at the
end of a ufunc's execution and a warning is raised if appropriate.
Note there's no easy way to set the FPU exception state from LLVM.
Instr... | NumpyErrorModel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess13.py | {
"start": 123,
"end": 422
} | class ____:
produce: type[Mock] = Mock
reveal_type(MockProducer.produce, expected_text="type[Mock]")
reveal_type(MockProducer().produce, expected_text="type[Mock]")
reveal_type(MockProducer.produce(), expected_text="Mock")
reveal_type(MockProducer().produce(), expected_text="Mock")
| MockProducer |
python | doocs__leetcode | solution/2700-2799/2798.Number of Employees Who Met the Target/Solution.py | {
"start": 0,
"end": 146
} | class ____:
def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
return sum(x >= target for x in hours)
| Solution |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_tpe.py | {
"start": 14649,
"end": 15047
} | class ____(unittest.TestCase, CasePerDomain):
def work(self):
# -- smoke test that things simply run,
# for each type of several search spaces.
trials = Trials()
fmin(
passthrough,
space=self.bandit.expr,
algo=partial(tpe.suggest, n_EI_candidate... | TestSuggest |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/output_parsers/test_yaml_parser.py | {
"start": 346,
"end": 2629
} | class ____(BaseModel):
action: Actions = Field(description="Action to be performed")
action_input: str = Field(description="Input to be used in the action")
additional_fields: str | None = Field(
description="Additional fields",
default=None,
)
for_new_lines: str = Field(description=... | TestModel |
python | spyder-ide__spyder | spyder/plugins/toolbar/api.py | {
"start": 297,
"end": 513
} | class ____:
File = 'file_toolbar'
Run = 'run_toolbar'
Debug = 'debug_toolbar'
Profile = 'profile_toolbar'
Main = 'main_toolbar'
WorkingDirectory = 'working_directory_toolbar'
| ApplicationToolbars |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 23024,
"end": 25232
} | class ____(_BaseMultiHostUrl):
"""A type that will accept any Postgres DSN.
* User info required
* TLD not required
* Host required
* Supports multiple hosts
If further validation is required, these properties can be used by validators to enforce specific behaviour:
```python
from pyd... | PostgresDsn |
python | ray-project__ray | python/ray/train/v2/api/context.py | {
"start": 5761,
"end": 6585
} | class ____(TrainContext):
"""Implementation of TrainContext for distributed mode."""
def get_experiment_name(self) -> str:
return get_internal_train_context().get_experiment_name()
def get_world_size(self) -> int:
return get_internal_train_context().get_world_size()
def get_world_rank... | DistributedTrainContext |
python | google__jax | jax/_src/memory.py | {
"start": 596,
"end": 745
} | class ____(enum.Enum):
Device = enum.auto()
Host = enum.auto()
Any = enum.auto()
def __repr__(self):
return f"MemorySpace.{self.name}"
| Space |
python | django__django | tests/admin_views/models.py | {
"start": 12029,
"end": 12244
} | class ____(models.Model):
posted = models.DateField(default=link_posted_default)
url = models.URLField()
post = models.ForeignKey("Post", models.CASCADE)
readonly_link_content = models.TextField()
| Link |
python | walkccc__LeetCode | solutions/2131. Longest Palindrome by Concatenating Two Letter Words/2131.py | {
"start": 0,
"end": 393
} | class ____:
def longestPalindrome(self, words: list[str]) -> int:
ans = 0
count = [[0] * 26 for _ in range(26)]
for a, b in words:
i = ord(a) - ord('a')
j = ord(b) - ord('a')
if count[j][i]:
ans += 4
count[j][i] -= 1
else:
count[i][j] += 1
for i in ran... | Solution |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-jinaai/llama_index/embeddings/jinaai/base.py | {
"start": 5345,
"end": 10579
} | class ____(MultiModalEmbedding):
"""
JinaAI class for embeddings.
Args:
model (str): Model for embedding.
Defaults to `jina-embeddings-v3`
"""
api_key: Optional[str] = Field(default=None, description="The JinaAI API key.")
model: str = Field(
default="jina-embeddin... | JinaEmbedding |
python | numpy__numpy | numpy/polynomial/polynomial.py | {
"start": 50419,
"end": 52667
} | class ____(ABCPolyBase):
"""A power series class.
The Polynomial class provides the standard Python numerical methods
'+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
attributes and methods listed below.
Parameters
----------
coef : array_like
Polynomial coefficien... | Polynomial |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-multiple-arrays.py | {
"start": 123,
"end": 595
} | class ____(object):
def intersection(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
MAX_NUM = 1000
cnt = [0]*(MAX_NUM+1)
for num in nums:
for x in num:
cnt[x] += 1
return [i for i in xrange(1, MAX_NUM+1) ... | Solution |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_str_returned.py | {
"start": 708,
"end": 829
} | class ____:
""" __str__ returns int """
def __str__(self): # [invalid-str-returned]
return 1
| SecondBadStr |
python | GokuMohandas__MadeWithML | madewithml/predict.py | {
"start": 1357,
"end": 5393
} | class ____:
def __init__(self, preprocessor, model):
self.preprocessor = preprocessor
self.model = model
self.model.eval()
def __call__(self, batch):
results = self.model.predict(collate_fn(batch))
return {"output": results}
def predict_proba(self, batch):
r... | TorchPredictor |
python | nedbat__coveragepy | coverage/debug.py | {
"start": 4029,
"end": 12140
} | class ____(NoDebugging):
"""A DebugControl that won't write anywhere."""
def write(self, msg: str, *, exc: BaseException | None = None) -> None:
pass
def info_header(label: str) -> str:
"""Make a nice header string."""
return "--{:-<60s}".format(" " + label + " ")
def info_formatter(info: I... | DevNullDebug |
python | viewflow__viewflow | viewflow/workflow/nodes/join.py | {
"start": 229,
"end": 4504
} | class ____(mixins.NextNodeActivationMixin, Activation):
"""Activation for parallel Join node."""
type: str = "join"
def __init__(self, *args, **kwargs): # noqa D102
self.next_task = None
super().__init__(*args, **kwargs)
@classmethod
def create(cls, flow_task, prev_activation, to... | JoinActivation |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 2776,
"end": 3646
} | class ____(unittest.TestCase):
# Optional tuple (certfile, keyfile, password) to use for HTTPS servers.
tls = None
def setUp(self):
self._threads = threading_helper.threading_setup()
os.environ = os_helper.EnvironmentVarGuard()
self.server_started = threading.Event()
self.t... | BaseTestCase |
python | huggingface__transformers | src/transformers/models/esm/configuration_esm.py | {
"start": 871,
"end": 2574
} | class ____:
"""
Args:
sequence_dim:
Single representation channel dimension
pairwise_dim:
Pair representation channel dimension
ipa_dim:
IPA hidden channel dimension
resnet_dim:
Angle resnet (Alg. 23 lines 11-14) hidden channel dime... | StructureModuleConfig |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 853,
"end": 1095
} | class ____(TestModel):
spaces = CharField(column_name='s p aces')
symbols = CharField(column_name='w/-nug!')
camelCaseName = CharField(column_name='camelCaseName')
class Meta:
table_name = 'oddColumnNames'
| OddColumnNames |
python | scipy__scipy | scipy/interpolate/tests/test_fitpack2.py | {
"start": 17361,
"end": 23257
} | class ____:
# NOTE: The systems in this test class are rank-deficient
def test_linear_constant(self):
x = [1,1,1,2,2,2,3,3,3]
y = [1,2,3,1,2,3,1,2,3]
z = [3,3,3,3,3,3,3,3,3]
s = 0.1
tx = [1+s,3-s]
ty = [1+s,3-s]
with pytest.warns(UserWarning, match="\nThe ... | TestLSQBivariateSpline |
python | ansible__ansible | test/integration/targets/jinja_plugins/collections/ansible_collections/foo/bar/plugins/test/good_collection_test.py | {
"start": 180,
"end": 299
} | class ____:
def tests(self):
return {
'world': lambda x: x.lower() == 'world',
}
| TestModule |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_server__embed.py | {
"start": 10723,
"end": 10944
} | class ____:
def test_root(self) -> None:
assert bes._process_app_path("/") == ""
def test_arg(self) -> None:
assert bes._process_app_path("/stuff") == "&bokeh-app-path=/stuff"
| Test__process_app_path |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-occurrences-of-a-substring.py | {
"start": 88,
"end": 1085
} | class ____(object):
def maxFreq(self, s, maxLetters, minSize, maxSize):
"""
:type s: str
:type maxLetters: int
:type minSize: int
:type maxSize: int
:rtype: int
"""
M, p = 10**9+7, 113
power, rolling_hash = pow(p, minSize-1, M), 0
left... | Solution |
python | apache__airflow | task-sdk-integration-tests/tests/task_sdk_tests/jwt_plugin.py | {
"start": 977,
"end": 3665
} | class ____:
"""Generator for JWT tokens used in Task SDK API authentication."""
def __init__(self):
"""Initialize JWT configuration from environment variables."""
self.secret = os.getenv("AIRFLOW__API_AUTH__JWT_SECRET", "test-secret-key-for-testing")
self.issuer = os.getenv("AIRFLOW__AP... | JWTTokenGenerator |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 190086,
"end": 190597
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("subscribable_id", "state", "client_mutation_id")
subscribable_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="subscribableId"
)
state = sgqlc.typ... | UpdateSubscriptionInput |
python | python-openxml__python-docx | tests/opc/test_package.py | {
"start": 703,
"end": 10615
} | class ____:
"""Unit-test suite for `docx.opc.package.OpcPackage` objects."""
def it_can_open_a_pkg_file(self, PackageReader_, PartFactory_, Unmarshaller_):
# mockery ----------------------
pkg_file = Mock(name="pkg_file")
pkg_reader = PackageReader_.from_file.return_value
# exer... | DescribeOpcPackage |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details.py | {
"start": 14993,
"end": 21329
} | class ____(BaseGSVTestCase):
endpoint = "sentry-api-0-organization-group-search-view-details"
method = "put"
def setUp(self) -> None:
self.base_data = self.create_base_data()
self.login_as(user=self.user_2)
# Get the second user's views for testing
self.view_id = str(self.b... | OrganizationGroupSearchViewsPutTest |
python | mwaskom__seaborn | seaborn/_marks/bar.py | {
"start": 518,
"end": 3307
} | class ____(Mark):
def _make_patches(self, data, scales, orient):
transform = scales[orient]._matplotlib_scale.get_transform()
forward = transform.transform
reverse = transform.inverted().transform
other = {"x": "y", "y": "x"}[orient]
pos = reverse(forward(data[orient]) - ... | BarBase |
python | PrefectHQ__prefect | src/integrations/prefect-dask/tests/test_utils.py | {
"start": 1807,
"end": 4483
} | class ____:
async def test_from_task(self):
@task
async def test_task():
delayed_num = dask.delayed(42)
async with get_async_dask_client() as client:
assert isinstance(client, Client)
result = await client.compute(delayed_num).result()
... | TestDaskAsyncClient |
python | huggingface__transformers | src/transformers/models/janus/modeling_janus.py | {
"start": 38771,
"end": 41263
} | class ____(JanusPreTrainedModel):
config: JanusVQVAEConfig
_no_split_modules = [
"JanusVQVAEAttnBlock",
"JanusVQVAEResnetBlock",
"JanusVQVAEVectorQuantizer",
]
main_input_name = "pixel_values"
def __init__(self, config: JanusVQVAEConfig):
super().__init__(config)
... | JanusVQVAE |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 13324,
"end": 13415
} | class ____(OAuthFlow):
authorizationUrl: str
tokenUrl: str
| OAuthFlowAuthorizationCode |
python | encode__starlette | starlette/middleware/base.py | {
"start": 4077,
"end": 8877
} | class ____:
def __init__(self, app: ASGIApp, dispatch: DispatchFunction | None = None) -> None:
self.app = app
self.dispatch_func = self.dispatch if dispatch is None else dispatch
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
... | BaseHTTPMiddleware |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 36880,
"end": 36992
} | class ____(str, Enum):
KEEP = "keep"
REMOVE = "remove"
INACTIVE = "inactive"
| BranchingScheduleHandling |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/storage/dummy_cache_storage_test.py | {
"start": 2971,
"end": 4487
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.storage = DummyCacheStorage()
def test_dummy_storage_get_always_not_found(self):
"""Test that storage.get() always returns CacheStorageKeyNotFoundError."""
with pytest.raises(CacheStorageKeyNotFoundError):
... | DummyCacheStorageTest |
python | pytorch__pytorch | test/inductor/test_perf.py | {
"start": 2622,
"end": 2678
} | class ____(InductorTestCase):
device = DEVICE
| TestCase |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin_ini/plugin_optional_inheritance.py | {
"start": 155,
"end": 453
} | class ____(Bar):
name: str
b = Bar(foo={'id': 1})
assert b.foo.id == 1
# MYPY: error: Item "None" of "Optional[Foo]" has no attribute "id" [union-attr]
z = Baz(foo={'id': 1}, name='test')
assert z.foo.id == 1
# MYPY: error: Item "None" of "Optional[Foo]" has no attribute "id" [union-attr]
| Baz |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec14.py | {
"start": 723,
"end": 1112
} | class ____(Generic[P, T]):
@overload
@classmethod
def method1(
cls, run: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs
) -> Self: ...
@overload
@classmethod
def method1(cls) -> "ClassB[[], None]": ...
@classmethod
def method1(cls, *args: Any, **kwargs: Any) -> Any: .... | ClassB |
python | pytorch__pytorch | test/dynamo/test_structured_trace.py | {
"start": 5319,
"end": 102359
} | class ____(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
torch._logging.structured.INTERN_TABLE.clear()
self.buffer = io.StringIO()
self.old_level = trace_log.level
trace_log.setLevel(logging.DEBUG)
self.handler = logging.StreamHandler(sel... | StructuredTraceTest |
python | Lightning-AI__lightning | tests/tests_pytorch/test_cli.py | {
"start": 18413,
"end": 20076
} | class ____(BoringModel):
def __init__(self, out_dim: int = 2, hidden_dim: int = 2) -> None:
super().__init__()
self.save_hyperparameters()
self.hidden_dim = hidden_dim
self.layer = torch.nn.Linear(32, out_dim)
def test_lightning_cli_ckpt_path_argument_hparams(cleandir):
class C... | BoringCkptPathModel |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 179111,
"end": 187634
} | class ____:
def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_,
expected_stat, xp):
dtype = xp.asarray(1.).dtype
f_obs = xp.asarray(f_obs, dtype=dtype)
f_exp = xp.asarray(f_exp, dtype=dtype) if f_exp is not None else f_exp
if axis is ... | TestPowerDivergence |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 4993,
"end": 5471
} | class ____(Model):
"""
Specify a project for the AlertRule
"""
__relocation_scope__ = RelocationScope.Organization
alert_rule = FlexibleForeignKey("sentry.AlertRule", db_index=False)
project = FlexibleForeignKey("sentry.Project")
date_added = models.DateTimeField(default=timezone.now)
... | AlertRuleProjects |
python | pypa__pipenv | pipenv/vendor/tomlkit/source.py | {
"start": 258,
"end": 1211
} | class ____:
def __init__(
self,
source: Source,
save_marker: bool | None = False,
restore: bool | None = False,
) -> None:
self._source = source
self._save_marker = save_marker
self.restore = restore
def __enter__(self) -> _State:
# Entering t... | _State |
python | keras-team__keras | keras/src/layers/layer.py | {
"start": 2266,
"end": 71405
} | class ____(BackendLayer, Operation):
"""This is the class from which all layers inherit.
A layer is a callable object that takes as input one or more tensors and
that outputs one or more tensors. It involves *computation*, defined
in the `call()` method, and a *state* (weight variables). State can be
... | Layer |
python | getsentry__sentry | src/sentry/notifications/utils/__init__.py | {
"start": 21039,
"end": 22290
} | class ____(PerformanceProblemContext):
def to_dict(self) -> dict[str, str | float | list[str]]:
return {
"transaction_name": self.transaction,
"slow_span_description": self.slow_span_description,
"slow_span_duration": self.slow_span_duration,
"transaction_dura... | RenderBlockingAssetProblemContext |
python | numpy__numpy | numpy/_core/tests/test_defchararray.py | {
"start": 6632,
"end": 11918
} | class ____:
def A(self):
return np.array([[' abc ', ''],
['12345', 'MixedCase'],
['123 \t 345 \0 ', 'UPPER']]) \
.view(np.char.chararray)
def B(self):
return np.array([[' \u03a3 ', ''],
['12345'... | TestInformation |
python | getsentry__sentry | src/sentry/integrations/messaging/metrics.py | {
"start": 3151,
"end": 3327
} | class ____(StrEnum):
"""Common reasons why a messaging command may fail."""
MISSING_DATA = "missing_data"
INVALID_STATE = "invalid_state"
| MessageCommandFailureReason |
python | numba__numba | numba/testing/main.py | {
"start": 24550,
"end": 27289
} | class ____(object):
"""
A minimal picklable object able to instantiate a runner in a
child process and run a test case with it.
"""
def __init__(self, runner_cls, runner_args):
self.runner_cls = runner_cls
self.runner_args = runner_args
# Python 2 doesn't know how to pickle ins... | _MinimalRunner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.