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/roberta_prelayernorm/test_modeling_roberta_prelayernorm.py | {
"start": 14274,
"end": 28101
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
RobertaPreLayerNormForCausalLM,
RobertaPreLayerNormForMaskedLM,
RobertaPreLayerNormModel,
RobertaPreLayerNormForSequenceClassification,
... | RobertaPreLayerNormModelTest |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call_param.py | {
"start": 2762,
"end": 2970
} | class ____(TypedDict, total=False):
type: Required[Literal["screenshot"]]
"""Specifies the event type.
For a screenshot action, this property is always set to `screenshot`.
"""
| ActionScreenshot |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 24339,
"end": 24491
} | class ____(AbstractDeviceGrant):
class Meta(AbstractDeviceGrant.Meta):
swappable = "OAUTH2_PROVIDER_DEVICE_GRANT_MODEL"
@dataclass
| DeviceGrant |
python | pennersr__django-allauth | allauth/socialaccount/providers/doximity/provider.py | {
"start": 223,
"end": 407
} | class ____(ProviderAccount):
def get_profile_url(self):
return None
def get_avatar_url(self):
return self.account.extra_data.get("profile_photo")
| DoximityAccount |
python | getsentry__sentry | src/sentry/api/serializers/models/group.py | {
"start": 6203,
"end": 29522
} | class ____(Serializer, ABC):
def __init__(
self,
collapse=None,
expand=None,
):
self.collapse = collapse
self.expand = expand
def _serialize_assignees(self, item_list: Sequence[Group]) -> Mapping[int, Team | Any]:
gas = GroupAssignee.objects.filter(group__in=... | GroupSerializerBase |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 37434,
"end": 39544
} | class ____(TestCase):
class Schema(Config):
site_dir = c.SiteDir()
docs_dir = c.Dir()
def test_doc_dir_in_site_dir(self) -> None:
j = os.path.join
# The parent dir is not the same on every system, so use the actual dir name
parent_dir = mkdocs.__file__.split(os.sep)[-3]
... | SiteDirTest |
python | ray-project__ray | python/ray/tests/test_list_actors_4.py | {
"start": 388,
"end": 2374
} | class ____:
pass
A.options(name="hi", lifetime="detached").remote()
assert len(ray.util.list_named_actors()) == 1
assert ray.util.list_named_actors() == ["hi"]
assert ray.util.list_named_actors(all_namespaces=True) == \
[dict(name="hi", namespace="test")]
""".format(
address
)
run_string_as_d... | A |
python | plotly__plotly.py | plotly/graph_objs/treemap/_outsidetextfont.py | {
"start": 233,
"end": 17456
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap"
_path_str = "treemap.outsidetextfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
... | Outsidetextfont |
python | walkccc__LeetCode | solutions/2369. Check if There is a Valid Partition For The Array/2369.py | {
"start": 0,
"end": 592
} | class ____:
def validPartition(self, nums: list[int]) -> bool:
n = len(nums)
# dp[i] := True if there's a valid partition for the first i numbers
dp = [False] * (n + 1)
dp[0] = True
dp[2] = nums[0] == nums[1]
for i in range(3, n + 1):
dp[i] = (
dp[i - 2] and nums[i - 2] == num... | Solution |
python | spack__spack | var/spack/test_repos/spack_repo/diff/packages/p2/package.py | {
"start": 217,
"end": 313
} | class ____(Package):
version("1.0")
variant("p2var", default=True)
depends_on("p3")
| P2 |
python | pydantic__pydantic | pydantic/v1/mypy.py | {
"start": 8249,
"end": 10659
} | class ____:
__slots__ = (
'init_forbid_extra',
'init_typed',
'warn_required_dynamic_aliases',
'warn_untyped_fields',
'debug_dataclass_transform',
)
init_forbid_extra: bool
init_typed: bool
warn_required_dynamic_aliases: bool
warn_untyped_fields: bool
d... | PydanticPluginConfig |
python | scrapy__scrapy | tests/test_logformatter.py | {
"start": 483,
"end": 591
} | class ____(Item):
name = Field()
def __str__(self):
return f"name: {self['name']}"
| CustomItem |
python | pypa__pipenv | pipenv/patched/pip/_internal/models/direct_url.py | {
"start": 1804,
"end": 2475
} | class ____:
name: ClassVar = "vcs_info"
vcs: str
commit_id: str
requested_revision: Optional[str] = None
@classmethod
def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional["VcsInfo"]:
if d is None:
return None
return cls(
vcs=_get_required(d, str,... | VcsInfo |
python | ipython__ipython | IPython/core/guarded_eval.py | {
"start": 1942,
"end": 6864
} | class ____:
"""Definition of evaluation policy."""
allow_locals_access: bool = False
allow_globals_access: bool = False
allow_item_access: bool = False
allow_attr_access: bool = False
allow_builtins_access: bool = False
allow_all_operations: bool = False
allow_any_calls: bool = False
... | EvaluationPolicy |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 1201,
"end": 2460
} | class ____(BuiltinFilter):
"""
Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating
point kernels.
Kernels can only be applied to "L" and "RGB" images.
:param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).
:param kernel: A sequence contain... | Kernel |
python | huggingface__transformers | src/transformers/models/mpnet/configuration_mpnet.py | {
"start": 848,
"end": 5285
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MPNetModel`]. It is used to
instantiate a MPNet model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configura... | MPNetConfig |
python | pytorch__pytorch | test/test_mps.py | {
"start": 14514,
"end": 15550
} | class ____(TestCase):
_do_mps_memory_leak_check = True
def __init__(self, method_name='runTest'):
super().__init__(method_name)
test_method = getattr(self, method_name, None)
if test_method is not None:
# Wraps the tested method if we should do MPS memory check.
... | TestCaseMPS |
python | readthedocs__readthedocs.org | readthedocs/proxito/tests/test_full.py | {
"start": 57871,
"end": 67183
} | class ____(BaseDocServing):
def _test_cache_control_header_project(self, expected_value, host=None):
"""
Test the CDN-Cache-Control header on requests for `self.project`.
:param expected_value: The expected value of the header: 'public' or 'private'.
:param host: Hostname to use in ... | TestCDNCache |
python | pyca__cryptography | tests/hazmat/primitives/test_hash_vectors.py | {
"start": 2264,
"end": 2639
} | class ____:
test_sha512_224 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA2"),
["SHA512_224LongMsg.rsp", "SHA512_224ShortMsg.rsp"],
hashes.SHA512_224(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512_256()),
... | TestSHA512224 |
python | getsentry__sentry | tests/sentry/workflow_engine/migrations/test_0084_crons_dedupe_workflows.py | {
"start": 447,
"end": 16768
} | class ____(TestMigrations):
migrate_from = "0083_add_status_to_action"
migrate_to = "0084_crons_dedupe_workflows"
app = "workflow_engine"
def _create_cron_rule_with_workflow(
self,
project,
monitor_slug,
frequency=5,
environment=None,
owner_user=None,
... | DedupeCronWorkflowsTest |
python | pydantic__pydantic | tests/mypy/modules/from_orm_v1_noconflict.py | {
"start": 341,
"end": 506
} | class ____(BaseModel):
model_config = ConfigDict(
from_attributes=True,
strict=True,
)
x: int
cm = CustomModel.from_orm(obj)
| CustomModel |
python | huggingface__transformers | src/transformers/models/sam2/modular_sam2.py | {
"start": 39760,
"end": 39822
} | class ____(SamTwoWayTransformer):
pass
| Sam2TwoWayTransformer |
python | huggingface__transformers | src/transformers/models/lightglue/modeling_lightglue.py | {
"start": 11619,
"end": 12365
} | class ____(nn.Module):
def __init__(self, config: LightGlueConfig):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.intermediate_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, c... | LightGlueMLP |
python | ray-project__ray | ci/raydepsets/workspace.py | {
"start": 1875,
"end": 3303
} | class ____:
depsets: List[Depset] = field(default_factory=list)
@classmethod
def from_dict(cls, data: dict, config_name: str) -> "Config":
build_arg_sets = cls.parse_build_arg_sets(data.get("build_arg_sets", {}))
raw_depsets = data.get("depsets", [])
depsets = []
for depset ... | Config |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator9.py | {
"start": 215,
"end": 272
} | class ____:
# This should generate an error
yield
| Foo |
python | huggingface__transformers | src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | {
"start": 8342,
"end": 11484
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | XLMRobertaXLSelfAttention |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/python_logs.py | {
"start": 89,
"end": 292
} | class ____(str, Enum):
CRITICAL = "CRITICAL"
FATAL = "FATAL"
ERROR = "ERROR"
WARN = "WARN"
WARNING = "WARNING"
INFO = "INFO"
DEBUG = "DEBUG"
NOTSET = "NOTSET"
| PythonLogLevel |
python | pytorch__pytorch | test/dynamo/test_einops.py | {
"start": 622,
"end": 4250
} | class ____(TestCase):
"""
These tests adapted from similar tests in the einops repo.
https://github.com/arogozhnikov/einops/blob/main/einops/tests/test_other.py#L254
The goal of this test suite is to test torch.compile x einops for multiple
versions of einops. Our goal is to prevent regressions in ... | TestEinops |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 22957,
"end": 23630
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
... | Owlv2MLP |
python | kamyu104__LeetCode-Solutions | Python/remove-methods-from-project.py | {
"start": 43,
"end": 921
} | class ____(object):
def remainingMethods(self, n, k, invocations):
"""
:type n: int
:type k: int
:type invocations: List[List[int]]
:rtype: List[int]
"""
def bfs():
lookup = [False]*n
lookup[k] = True
q = [k]
whi... | Solution |
python | ansible__ansible | lib/ansible/_internal/_templating/_marker_behaviors.py | {
"start": 1157,
"end": 1303
} | class ____:
"""A numbered occurrence of a `Marker` value for later conversion to a warning."""
number: int
value: Marker
| _MarkerTracker |
python | django__django | tests/custom_lookups/tests.py | {
"start": 7328,
"end": 7397
} | class ____(RelatedGreaterThan):
lookup_name = "rmt"
| RelatedMoreThan |
python | Textualize__textual | src/textual/command.py | {
"start": 14911,
"end": 42814
} | class ____(SystemModalScreen[None]):
"""The Textual command palette."""
AUTO_FOCUS = "CommandInput"
COMPONENT_CLASSES: ClassVar[set[str]] = {
"command-palette--help-text",
"command-palette--highlight",
}
"""
| Class | Description |
| :- | :- |
| `command-palette--help-t... | CommandPalette |
python | Netflix__metaflow | metaflow/runtime.py | {
"start": 11448,
"end": 63924
} | class ____(object):
def __init__(
self,
flow,
graph,
flow_datastore,
metadata,
environment,
package,
logger,
entrypoint,
event_logger,
monitor,
run_id=None,
clone_run_id=None,
clone_only=False,
re... | NativeRuntime |
python | PrefectHQ__prefect | src/prefect/schedules.py | {
"start": 353,
"end": 7289
} | class ____:
"""
A dataclass representing a schedule.
Note that only one of `interval`, `cron`, or `rrule` can be defined at a time.
Attributes:
interval: A timedelta representing the frequency of the schedule.
cron: A valid cron string (e.g. "0 0 * * *").
rrule: A valid RRule s... | Schedule |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/tests/test_jobs.py | {
"start": 223,
"end": 1684
} | class ____:
@pytest.mark.parametrize(
"value, expected",
[
[
AccessControlRequest(
group_name="foo", permission_level=CanManage.canmanage
),
{
"group_name": "foo",
"permission_leve... | TestModelsJobs |
python | prabhupant__python-ds | data_structures/binary_trees/perfect_tree.py | {
"start": 56,
"end": 878
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def find_depth(node):
d = 0
while node:
d += 1
node = node.left
return d
def is_perfect_util(root, d, level=0):
if not root:
return True
if not root.left a... | Node |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 34543,
"end": 34646
} | class ____(StringEnum):
single_version = "single_version"
general = "general"
| VersionParadigmEnum |
python | dabeaz-course__practical-python | Solutions/4_4/stock.py | {
"start": 12,
"end": 487
} | class ____:
'''
An instance of a stock holding consisting of name, shares, and price.
'''
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
def cost(self):
'''
Return the cost as shares*price
'''
... | Stock |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 168818,
"end": 170390
} | class ____(TestCase):
def test_basic(self):
iterables = ['ab', 'cdef', 'ghi']
first_index = {}
for index, element in enumerate(product(*iterables)):
actual = mi.product_index(element, *iterables)
expected = first_index.setdefault(element, index)
self.asser... | ProductIndexTests |
python | numba__numba | numba/tests/test_sets.py | {
"start": 7255,
"end": 15026
} | class ____(BaseTest):
def test_constructor(self):
pyfunc = empty_constructor_usecase
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(), pyfunc())
pyfunc = constructor_usecase
cfunc = jit(nopython=True)(pyfunc)
def check(arg):
self.assert... | TestSets |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 24840,
"end": 27587
} | class ____(OrganizationMixin, HasObservations, db.Model):
__tablename__ = "organization_applications"
__repr__ = make_repr("name")
@declared_attr
def normalized_name(cls): # noqa: N805
return column_property(func.normalize_pep426_name(cls.name))
submitted_by_id: Mapped[UUID] = mapped_colu... | OrganizationApplication |
python | scikit-learn__scikit-learn | sklearn/feature_selection/_rfe.py | {
"start": 2040,
"end": 19702
} | class ____(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
"""Feature ranking with recursive feature elimination.
Given an external estimator that assigns weights to features (e.g., the
coefficients of a linear model), the goal of recursive feature elimination
(RFE) is to select features by recursiv... | RFE |
python | catalyst-team__catalyst | examples/catalyst_rl/ddpg.py | {
"start": 1198,
"end": 3407
} | class ____(ISampler):
def get_action(
self, env, network: nn.Module, state: np.array, sigma: Optional[float] = None
) -> np.array:
state = torch.tensor(state, dtype=torch.float32).unsqueeze(0)
action = network(state).detach().cpu().numpy()[0]
if sigma is not None:
act... | Sampler |
python | fastai__fastai | nbs/examples/migrating_lightning.py | {
"start": 339,
"end": 1599
} | class ____(LightningModule):
def __init__(self):
super().__init__()
self.l1 = torch.nn.Linear(28 * 28, 10)
def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1)))
def training_step(self, batch, batch_idx):
x,y = batch
y_hat = self(x)
loss = F.cross_e... | LitModel |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_line_miles_distance_between.py | {
"start": 570,
"end": 2130
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
# Please see {some doc} for information on how to choose an id string for your Metric.
condition_metric_name = "column_values.linestring_distance_miles"
condition_value_keys = (
"min_distance... | ColumnValuesLinestringMilesDistanceBetween |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 89911,
"end": 92840
} | class ____(LongT5PreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
}
_keys_to_ignore_on_load_unexpected = [r"decoder"]
def __init__(self, config: LongT5Config):
super().__init__(config)
self.shared = nn.Embedding(config.vocab_size, config.d... | LongT5EncoderModel |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/expect_column_pair_values_to_have_a_difference_of_three.py | {
"start": 2540,
"end": 6463
} | class ____(ColumnPairMapExpectation):
# </snippet>
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_column_pair_values_to_have_a_difference_of_three.py completed_docstring">
"""Expect two columns to have a row-wise difference of three."""
# </snippet>
... | ExpectColumnPairValuesToHaveADifferenceOfThree |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py | {
"start": 5386,
"end": 5574
} | class ____(BaseFSHandler):
@web.authenticated
@authorized
def get(self):
result = self.fs_info(self.get_path_argument("path"))
self.write_json(result)
| InfoHandler |
python | joblib__joblib | joblib/externals/loky/_base.py | {
"start": 792,
"end": 1057
} | class ____(_BaseFuture):
def _invoke_callbacks(self):
for callback in self._done_callbacks:
try:
callback(self)
except BaseException:
LOGGER.exception(f"exception calling callback for {self!r}")
| Future |
python | graphql-python__graphene | graphene/relay/mutation.py | {
"start": 147,
"end": 2213
} | class ____(Mutation):
class Meta:
abstract = True
@classmethod
def __init_subclass_with_meta__(
cls, output=None, input_fields=None, arguments=None, name=None, **options
):
input_class = getattr(cls, "Input", None)
base_name = re.sub("Payload$", "", name or cls.__name__)... | ClientIDMutation |
python | realpython__materials | primer-on-python-decorators/circle.py | {
"start": 0,
"end": 907
} | class ____:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
"""Get value of radius"""
return self._radius
@radius.setter
def radius(self, value):
"""Set radius, raise error if negative"""
if value >= 0:
self._radius =... | Circle |
python | django__django | tests/timezones/tests.py | {
"start": 11508,
"end": 28600
} | class ____(TestCase):
naive_warning = "DateTimeField Event.dt received a naive datetime"
@skipIfDBFeature("supports_timezones")
def test_aware_time_unsupported(self):
t = datetime.time(13, 20, 30, tzinfo=EAT)
msg = "backend does not support timezone-aware times."
with self.assertRai... | NewDatabaseTests |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/node.py | {
"start": 2211,
"end": 4681
} | class ____(BaseNodePostprocessor):
"""Similarity-based Node processor."""
similarity_cutoff: float = Field(default=0.0)
@classmethod
def class_name(cls) -> str:
return "SimilarityPostprocessor"
def _postprocess_nodes(
self,
nodes: List[NodeWithScore],
query_bundle:... | SimilarityPostprocessor |
python | Textualize__rich | tests/test_repr.py | {
"start": 2164,
"end": 3627
} | class ____:
def __init__(self, foo, /):
self.foo = 1
""",
globals(),
_locals,
)
p = _locals["PosOnly"](1)
assert repr(p) == "PosOnly(1)"
def test_rich_angular() -> None:
assert (repr(Bar("hello"))) == "<Bar 'hello' 'hello' egg=1>"
assert (repr(Bar("hello", bar=3))) ... | PosOnly |
python | python-openxml__python-docx | tests/image/test_tiff.py | {
"start": 14011,
"end": 14292
} | class ____:
def it_can_parse_a_long_int_IFD_entry(self):
bytes_ = b"foobaroo\x00\x00\x00\x2a"
stream_rdr = StreamReader(io.BytesIO(bytes_), BIG_ENDIAN)
val = _LongIfdEntry._parse_value(stream_rdr, 0, 1, None)
assert val == 42
| Describe_LongIfdEntry |
python | ZoranPandovski__al-go-rithms | data_structures/Arrays/Python/merge-intervals.py | {
"start": 0,
"end": 284
} | class ____:
def merge(self, intervals):
ans = []
for beg, end in sorted(intervals):
if not ans or ans[-1][1] < beg:
ans += [[beg, end]]
else:
ans[-1][1] = max(ans[-1][1], end)
return ans | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-the-longest-equal-subarray.py | {
"start": 93,
"end": 569
} | class ____(object):
def longestEqualSubarray(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
cnt = collections.Counter()
result = left = 0
for right in xrange(len(nums)):
cnt[nums[right]] += 1
result = max... | Solution |
python | jazzband__django-model-utils | tests/models.py | {
"start": 3484,
"end": 3529
} | class ____(TimeFramedModel):
pass
| TimeFrame |
python | wandb__wandb | wandb/vendor/pygments/lexers/scripting.py | {
"start": 10040,
"end": 25282
} | class ____(RegexLexer):
"""
For Second Life's Linden Scripting Language source code.
.. versionadded:: 2.0
"""
name = 'LSL'
aliases = ['lsl']
filenames = ['*.lsl']
mimetypes = ['text/x-lsl']
flags = re.MULTILINE
lsl_keywords = r'\b(?:do|else|for|if|jump|return|while)\b'
l... | LSLLexer |
python | numpy__numpy | numpy/_core/tests/test_shape_base.py | {
"start": 3034,
"end": 4002
} | class ____:
def test_0D_array(self):
a = array(1)
b = array(2)
res = [atleast_3d(a), atleast_3d(b)]
desired = [array([[[1]]]), array([[[2]]])]
assert_array_equal(res, desired)
def test_1D_array(self):
a = array([1, 2])
b = array([2, 3])
res = [atl... | TestAtleast3d |
python | Textualize__textual | src/textual/containers.py | {
"start": 6672,
"end": 8693
} | class ____(Widget):
"""A container with grid layout and automatic columns."""
DEFAULT_CSS = """
ItemGrid {
width: 1fr;
height: auto;
layout: grid;
}
"""
stretch_height: reactive[bool] = reactive(True)
min_column_width: reactive[int | None] = reactive(None, layout=Tr... | ItemGrid |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-string-iterable/llama_index/readers/string_iterable/base.py | {
"start": 214,
"end": 1234
} | class ____(BasePydanticReader):
"""
String Iterable Reader.
Gets a list of documents, given an iterable (e.g. list) of strings.
Example:
.. code-block:: python
from llama_index import TreeIndex
from llama_index.readers import StringIterableReader
documents... | StringIterableReader |
python | google__jax | tests/pallas/pipelining/schedule_api_test.py | {
"start": 1039,
"end": 1348
} | class ____:
shape: tuple[int, ...]
dtype: np.dtype
memory_space: Any | None = None
def get_ref_aval(self) -> state_types.AbstractRef:
return state_types.AbstractRef(
inner_aval=jax_core.ShapedArray(shape=self.shape, dtype=self.dtype),
memory_space=self.memory_space,
)
| MemoryRef |
python | django__django | tests/generic_views/test_edit.py | {
"start": 14887,
"end": 19555
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.author = Author.objects.create(
name="Randall Munroe",
slug="randall-munroe",
)
def test_delete_by_post(self):
res = self.client.get("/edit/author/%d/delete/" % self.author.pk)
self.assert... | DeleteViewTests |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 38855,
"end": 42416
} | class ____(BatchPointwiseOpsFusionFactory):
"""
Batch pointwise ops (e.g., sigmoid, relu, tanh) fusion in pre grad pass.
We fuse it in random place, and the introduced stack node may be merged in split cat.
"""
def __init__(self, op, **kwargs) -> None:
super().__init__(op, **kwargs)
... | BatchPointwiseOpsPreGradFusion |
python | great-expectations__great_expectations | tests/expectations/test_conditions.py | {
"start": 454,
"end": 1167
} | class ____:
"""Tests for the base Condition class."""
def test_condition_instantiation(self):
"""Test that Condition can be instantiated."""
condition = Condition()
assert isinstance(condition, Condition)
def test_and_with_two_conditions(sef):
condition_a = Condition()
... | TestCondition |
python | ray-project__ray | python/ray/tests/test_async_compat.py | {
"start": 549,
"end": 625
} | class ____:
async def async_fn(self) -> None:
pass
| YesAsyncMethods |
python | plotly__plotly.py | plotly/graph_objs/bar/unselected/_textfont.py | {
"start": 233,
"end": 2562
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar.unselected"
_path_str = "bar.unselected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of unselected points, applied only
when a selection exists.
The 'color' pr... | Textfont |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 9467,
"end": 9875
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "PresetNotFoundError"
preset = graphene.NonNull(graphene.String)
def __init__(self, preset, selector):
super().__init__()
self.preset = check.str_param(preset, "preset")
self.message =... | GraphenePresetNotFoundError |
python | getsentry__sentry-python | tests/integrations/litellm/test_litellm.py | {
"start": 2279,
"end": 2649
} | class ____:
def __init__(
self,
model="gpt-3.5-turbo",
choices=None,
usage=None,
):
self.id = "chatcmpl-test"
self.model = model
self.choices = choices or [MockChoice()]
self.usage = usage or MockUsage()
self.object = "chat.completion"
... | MockCompletionResponse |
python | ipython__ipython | tests/test_interactiveshell.py | {
"start": 1351,
"end": 1787
} | class ____(KeyboardInterrupt):
pass
def test_stream_performance(capsys) -> None:
"""It should be fast to execute."""
src = "for i in range(250_000): print(i)"
start = time.perf_counter()
ip.run_cell(src)
end = time.perf_counter()
# We try to read as otherwise on failure, pytest will print ... | DerivedInterrupt |
python | huggingface__transformers | tests/models/llava/test_modeling_llava.py | {
"start": 1471,
"end": 5649
} | class ____:
def __init__(
self,
parent,
ignore_index=-100,
image_token_index=0,
projector_hidden_act="gelu",
seq_length=7,
vision_feature_select_strategy="default",
vision_feature_layer=-1,
text_config={
"model_type": "llama",
... | LlavaVisionText2TextModelTester |
python | ansible__ansible | lib/ansible/module_utils/urls.py | {
"start": 25337,
"end": 55872
} | class ____:
def __init__(self, headers=None, use_proxy=True, force=False, timeout=10, validate_certs=True,
url_username=None, url_password=None, http_agent=None, force_basic_auth=False,
follow_redirects='urllib2', client_cert=None, client_key=None, cookies=None, unix_socket=None,
... | Request |
python | getsentry__sentry | src/sentry/shared_integrations/response/text.py | {
"start": 95,
"end": 339
} | class ____(BaseApiResponse):
def __init__(self, text: str, *args: Any, **kwargs: Any) -> None:
self.text = text
super().__init__(*args, **kwargs)
@property
def body(self) -> Any:
return self.text
| TextApiResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 492354,
"end": 493082
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for CheckStep."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("CheckStepEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sg... | CheckStepConnection |
python | doocs__leetcode | solution/0700-0799/0725.Split Linked List in Parts/Solution.py | {
"start": 151,
"end": 747
} | class ____:
def splitListToParts(
self, head: Optional[ListNode], k: int
) -> List[Optional[ListNode]]:
n = 0
cur = head
while cur:
n += 1
cur = cur.next
cnt, mod = divmod(n, k)
ans = [None] * k
cur = head
for i in range(k):... | Solution |
python | ipython__ipython | IPython/core/display.py | {
"start": 15032,
"end": 16126
} | class ____(DisplayObject):
"""Embed an SVG into the display.
Note if you just want to view a svg image via a URL use `:class:Image` with
a url=URL keyword argument.
"""
_read_flags = 'rb'
# wrap data in a property, which extracts the <svg> tag, discarding
# document headers
_data: Opti... | SVG |
python | mlflow__mlflow | tests/utils/test_annotations.py | {
"start": 719,
"end": 954
} | class ____:
"""
A deprecated class.
"""
def __init__(self):
pass
def greet(self):
"""
Greets the user.
"""
return "Hello"
@deprecated(since="1.0.0")
@dataclass
| DeprecatedClass |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 216544,
"end": 221636
} | class ____:
def test_change_role(self, db_request, monkeypatch):
project = ProjectFactory.create(name="foobar")
user = UserFactory.create(username="testuser")
role = RoleFactory.create(user=user, project=project, role_name="Owner")
new_role_name = "Maintainer"
user_2 = UserF... | TestChangeProjectRole |
python | python__mypy | mypy/nodes.py | {
"start": 84014,
"end": 84957
} | class ____(Expression):
"""Generator expression ... for ... in ... [ for ... in ... ] [ if ... ]."""
__slots__ = ("left_expr", "sequences", "condlists", "is_async", "indices")
__match_args__ = ("left_expr", "indices", "sequences", "condlists")
left_expr: Expression
sequences: list[Expression]
... | GeneratorExpr |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ROI.py | {
"start": 95918,
"end": 96859
} | class ____(LineSegmentROI):
def paint(self, p, *args):
LineSegmentROI.paint(self, p, *args)
h1 = self.handles[0]['item'].pos()
h2 = self.handles[1]['item'].pos()
p1 = p.transform().map(h1)
p2 = p.transform().map(h2)
vec = Point(h2) - Point(h1)
length = vec.le... | RulerROI |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/map_test.py | {
"start": 69078,
"end": 72299
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.v2_only_combinations(),
checkpoint_test_base.default_test_combinations(),
combinations.combine(
dat... | MapGlobalShuffleCheckpointTest |
python | spack__spack | lib/spack/spack/util/gcs.py | {
"start": 1034,
"end": 5053
} | class ____:
"""GCS Bucket Object
Create a wrapper object for a GCS Bucket. Provides methods to wrap spack
related tasks, such as destroy.
"""
def __init__(self, url, client=None):
"""Constructor for GCSBucket objects
Args:
url (str): The url pointing to the GCS bucket to ... | GCSBucket |
python | allegroai__clearml | clearml/backend_api/services/v2_20/pipelines.py | {
"start": 209,
"end": 2994
} | class ____(Request):
"""
Start a pipeline
:param task: ID of the task on which the pipeline will be based
:type task: str
:param queue: Queue ID in which the created pipeline task will be enqueued
:type queue: str
:param args: Task arguments, name/value to be placed in the hyperparameters
... | StartPipelineRequest |
python | ray-project__ray | rllib/algorithms/ppo/ppo_catalog.py | {
"start": 1097,
"end": 7751
} | class ____(Catalog):
"""The Catalog class used to build models for PPO.
PPOCatalog provides the following models:
- ActorCriticEncoder: The encoder used to encode the observations.
- Pi Head: The head used to compute the policy logits.
- Value Function Head: The head used to compute the... | PPOCatalog |
python | lazyprogrammer__machine_learning_examples | bayesian_ml/1/nb.py | {
"start": 265,
"end": 4428
} | class ____:
def fit(self, X, Y):
self.pyy = []
self.tinfo = []
N, D = X.shape
for c in (0, 1):
pyy_c = (1.0 + np.sum(Y == c)) / (N + 1.0 + 1.0)
self.pyy.append(pyy_c)
# for each dimension, we need to store the data we need to calculate
# the posterior predictive distribution
... | NB |
python | has2k1__plotnine | plotnine/scales/scale_continuous.py | {
"start": 969,
"end": 16500
} | class ____(
scale[
RangeContinuous,
ContinuousBreaksUser,
ContinuousLimitsUser,
# subclasses are still generic and must specify the
# type of the guide
GuideTypeT,
]
):
"""
Base class for all continuous scales
Notes
-----
If using the class di... | scale_continuous |
python | doocs__leetcode | solution/0500-0599/0582.Kill Process/Solution.py | {
"start": 0,
"end": 349
} | class ____:
def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:
def dfs(i: int):
ans.append(i)
for j in g[i]:
dfs(j)
g = defaultdict(list)
for i, p in zip(pid, ppid):
g[p].append(i)
ans = []
dfs(... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/workflow/workflow_events.py | {
"start": 411,
"end": 544
} | class ____(Warning):
"""Warning raised when the conversion from a dictionary to a Pydantic model fails"""
| PydanticConversionWarning |
python | google__jax | jax/_src/sharding_impls.py | {
"start": 46521,
"end": 48711
} | class ____:
"""Sets a concrete mesh in a thread-local context.
``jax.set_mesh`` has dual behavior. You can use it as a global setter or as a
context manager.
When a mesh is in context via ``jax.set_mesh``, you can use pass
raw PartitionSpecs to all APIs that accept sharding as an argument.
Using ``jax.set... | set_mesh |
python | bottlepy__bottle | bottle.py | {
"start": 78563,
"end": 78610
} | class ____(BottleException):
pass
| PluginError |
python | python-openxml__python-docx | tests/opc/test_pkgreader.py | {
"start": 17298,
"end": 18860
} | class ____:
def it_can_load_from_xml(self, parse_xml_, _SerializedRelationship_):
# mockery ----------------------
baseURI, rels_item_xml, rel_elm_1, rel_elm_2 = (
Mock(name="baseURI"),
Mock(name="rels_item_xml"),
Mock(name="rel_elm_1"),
Mock(name="rel... | Describe_SerializedRelationships |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_data_factory.py | {
"start": 2651,
"end": 12948
} | class ____:
@pytest.fixture(autouse=True)
def setup_test_cases(self, create_mock_connection):
self.mock_ti = MagicMock()
self.mock_context = {"ti": self.mock_ti}
self.config = {
"task_id": TASK_ID,
"azure_data_factory_conn_id": AZURE_DATA_FACTORY_CONN_ID,
... | TestAzureDataFactoryRunPipelineOperator |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 3806,
"end": 6018
} | class ____:
def test_flag_existed_and_was_active(self):
waffle.get_waffle_flag_model().objects.create(name='foo', everyone=True)
with override_flag('foo', active=True):
assert waffle.flag_is_active(req(), 'foo')
with override_flag('foo', active=False):
assert not wa... | OverrideFlagTestsMixin |
python | scrapy__scrapy | tests/test_spider_start.py | {
"start": 465,
"end": 5597
} | class ____:
async def _test_spider(
self, spider: type[Spider], expected_items: list[Any] | None = None
) -> None:
actual_items = []
expected_items = [] if expected_items is None else expected_items
def track_item(item, response, spider):
actual_items.append(item)
... | TestMain |
python | realpython__materials | python-yaml/formatter/server.py | {
"start": 416,
"end": 1439
} | class ____(BaseModel):
# Boolean flags:
allow_unicode: bool = False
canonical: bool = False
default_flow_style: bool = False
explicit_end: bool = False
explicit_start: bool = False
sort_keys: bool = True
# Valued parameters:
indent: Optional[int] = None
width: Optional[int] = No... | Parameters |
python | pypa__hatch | tests/backend/utils/test_context.py | {
"start": 3972,
"end": 5356
} | class ____:
def test_set(self, isolation):
context = Context(isolation)
with EnvVars({"BAR": "foobarbaz"}):
assert context.format("foo {env:BAR}") == "foo foobarbaz"
def test_default(self, isolation):
context = Context(isolation)
assert context.format("foo {env:BAR... | TestEnvVars |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 2112,
"end": 2303
} | class ____(Token):
id = '<tag>'
def __init__(self, value, start_mark, end_mark):
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
| TagToken |
python | mlflow__mlflow | mlflow/store/artifact/unity_catalog_oss_models_artifact_repo.py | {
"start": 1858,
"end": 7422
} | class ____(ArtifactRepository):
"""
Performs storage operations on artifacts controlled by a Unity Catalog model registry
Temporary scoped tokens for the appropriate cloud storage locations are fetched from the
remote backend and used to download model artifacts.
The artifact_uri is expected to be... | UnityCatalogOSSModelsArtifactRepository |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.