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 | wireservice__csvkit | tests/test_utilities/test_in2csv.py | {
"start": 202,
"end": 13554
} | class ____(CSVKitTestCase, EmptyFileTests):
Utility = In2CSV
default_args = ['-f', 'csv']
def assertConverted(self, input_format, input_filename, output_filename, additional_args=[]):
output = self.get_output(['-f', input_format, input_filename] + additional_args)
with open(output_filename... | TestIn2CSV |
python | huggingface__transformers | src/transformers/models/zamba/modeling_zamba.py | {
"start": 13400,
"end": 28138
} | class ____(nn.Module):
"""
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
∆, B, C are input-dependent (this is a key difference between Mamba and ... | ZambaMambaMixer |
python | ray-project__ray | rllib/models/tf/tf_action_dist.py | {
"start": 4031,
"end": 7832
} | class ____(TFActionDistribution):
"""MultiCategorical distribution for MultiDiscrete action spaces."""
def __init__(
self,
inputs: List[TensorType],
model: ModelV2,
input_lens: Union[List[int], np.ndarray, Tuple[int, ...]],
action_space=None,
):
# skip TFActi... | MultiCategorical |
python | kubernetes-client__python | kubernetes/client/models/v1_storage_class.py | {
"start": 383,
"end": 14396
} | 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... | V1StorageClass |
python | pytorch__pytorch | torch/fx/tensor_type.py | {
"start": 197,
"end": 1010
} | class ____:
"""
TensorType defines a type for tensors, which consists of a list of dimensions.
Example:
class M(torch.nn.Module):
def forward(self, x:TensorType((1,2,3, Dyn)), y:TensorType((1,2,3, Dyn))):
return torch.add(x, y)
"""
def __init__(self, dim):
... | TensorType |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/common/utils.py | {
"start": 7217,
"end": 9860
} | class ____(enum.Enum):
# Categorizing known failures, to ease later follow-up investigation.
# Some are crosshair issues, some hypothesis issues, others truly ok-to-xfail tests.
symbolic_outside_context = "CrosshairInternal error (using value outside context)"
nested_given = "nested @given decorators do... | Why |
python | pytorch__pytorch | torch/distributed/fsdp/api.py | {
"start": 16365,
"end": 17024
} | class ____(StateDictConfig):
"""
``ShardedStateDictConfig`` is a config class meant to be used with
``StateDictType.SHARDED_STATE_DICT``.
Attributes:
_use_dtensor (bool): If ``True``, then FSDP saves the state dict values
as ``DTensor``, and if ``False``, then FSDP saves them as
... | ShardedStateDictConfig |
python | getsentry__sentry | src/sentry/web/client_config.py | {
"start": 5722,
"end": 19353
} | class ____:
def __init__(
self,
request: Request | None = None,
org_context: RpcUserOrganizationContext | None = None,
) -> None:
self.request = request
if request is not None:
self.user: User | AnonymousUser | None = request.user
self.session: Ses... | _ClientConfig |
python | walkccc__LeetCode | solutions/3043. Find the Length of the Longest Common Prefix/3043.py | {
"start": 84,
"end": 538
} | class ____:
def __init__(self):
self.root = TrieNode()
def insert(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) -> int:
prefixLength = 0
node = self.root
for c in... | Trie |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py | {
"start": 1797,
"end": 1933
} | class ____(AirflowException):
"""An exception that indicates a failure in getting the list of datasets."""
| PowerBIDatasetListException |
python | Netflix__metaflow | metaflow/_vendor/packaging/requirements.py | {
"start": 544,
"end": 3264
} | class ____:
"""Parse a requirement.
Parse a given requirement string into its parts, such as name, specifier,
URL, and extras. Raises InvalidRequirement on a badly-formed requirement
string.
"""
# TODO: Can we test whether something is contained within a requirement?
# If so how do w... | Requirement |
python | bokeh__bokeh | src/bokeh/sphinxext/_internal/bokeh_directive.py | {
"start": 2048,
"end": 2754
} | class ____(SphinxDirective):
def parse(self, rst_text, annotation):
result = ViewList()
for line in rst_text.split("\n"):
result.append(line, annotation)
node = nodes.paragraph()
node.document = self.state.document
nested_parse_with_titles(self.state, result, nod... | BokehDirective |
python | walkccc__LeetCode | solutions/274. H-Index/274.py | {
"start": 0,
"end": 419
} | class ____:
def hIndex(self, citations: list[int]) -> int:
n = len(citations)
accumulate = 0
count = [0] * (n + 1)
for citation in citations:
count[min(citation, n)] += 1
# To find the maximum h-index, loop from the back to the front.
# i := the candidate's h-index
for i, c in reve... | Solution |
python | django__django | tests/admin_views/models.py | {
"start": 14549,
"end": 14611
} | class ____(Plot):
class Meta:
proxy = True
| PlotProxy |
python | walkccc__LeetCode | solutions/1680. Concatenation of Consecutive Binary Numbers/1680-2.py | {
"start": 0,
"end": 268
} | class ____:
def concatenatedBinary(self, n: int) -> int:
MOD = 1_000_000_007
ans = 0
numberOfBits = 0
for i in range(1, n + 1):
if i.bit_count() == 1:
numberOfBits += 1
ans = ((ans << numberOfBits) + i) % MOD
return ans
| Solution |
python | keras-team__keras | keras/src/saving/saving_lib_test.py | {
"start": 36280,
"end": 42623
} | class ____(testing.TestCase):
def test_custom_object_without_from_config(self):
temp_filepath = os.path.join(
self.get_temp_dir(), "custom_fn_model.keras"
)
inputs = keras.Input(shape=(4, 4))
outputs = keras.layers.Dense(1, activation=GrowthFactor(0.5))(inputs)
m... | SavingBattleTest |
python | getsentry__sentry | src/sentry/sentry_apps/utils/webhooks.py | {
"start": 275,
"end": 345
} | class ____(SentryAppActionType):
CREATED = "created"
| ErrorActionType |
python | ansible__ansible | lib/ansible/plugins/lookup/pipe.py | {
"start": 1823,
"end": 2789
} | class ____(LookupBase):
def run(self, terms, variables=None, **kwargs):
ret = []
for term in terms:
# https://docs.python.org/3/library/subprocess.html#popen-constructor
#
# The shell argument (which defaults to False) specifies whether to use the
# ... | LookupModule |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_threaded_ray_installer.py | {
"start": 794,
"end": 5109
} | class ____(unittest.TestCase):
def setUp(self):
self.base_provider = MockProvider()
self.config = AutoscalingConfig(load_test_config("test_ray_complex.yaml"))
self.runner = MockProcessRunner()
self.ray_installer = RayInstaller(self.base_provider, self.config, self.runner)
sel... | ThreadedRayInstallerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 23203,
"end": 24636
} | class ____(_StringType, sqltypes.CHAR):
"""MySQL CHAR type, for fixed-length character data."""
__visit_name__ = "CHAR"
def __init__(self, length: Optional[int] = None, **kwargs: Any):
"""Construct a CHAR.
:param length: Maximum data length, in characters.
:param binary: Optional... | CHAR |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_type.py | {
"start": 208,
"end": 284
} | class ____(GQLResult):
project: Optional[ArtifactTypeProject]
| ArtifactType |
python | TheAlgorithms__Python | data_structures/binary_tree/binary_tree_node_sum.py | {
"start": 400,
"end": 656
} | class ____:
"""
A Node has a value variable and pointers to Nodes to its left and right.
"""
def __init__(self, value: int) -> None:
self.value = value
self.left: Node | None = None
self.right: Node | None = None
| Node |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 50495,
"end": 61425
} | class ____(torch.fx.Interpreter):
"""Interpreter that inserts type promotion for each node."""
def __init__(
self,
module: torch.fx.GraphModule,
type_promotion_table: TypePromotionTable,
) -> None:
super().__init__(module)
self.type_promotion_table = type_promotion_t... | _TypePromotionInterpreter |
python | mwaskom__seaborn | tests/test_distributions.py | {
"start": 28160,
"end": 35842
} | class ____:
def test_long_vectors(self, long_df):
ax1 = kdeplot(data=long_df, x="x", y="y")
x = long_df["x"]
x_values = [x, x.to_numpy(), x.to_list()]
y = long_df["y"]
y_values = [y, y.to_numpy(), y.to_list()]
for x, y in zip(x_values, y_values):
f, a... | TestKDEPlotBivariate |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_area02.py | {
"start": 315,
"end": 1422
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_area02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | django-guardian__django-guardian | guardian/models/models.py | {
"start": 6946,
"end": 7210
} | class ____(GroupObjectPermissionBase, BaseGenericObjectPermission):
class Meta(GroupObjectPermissionBase.Meta, BaseGenericObjectPermission.Meta):
abstract = True
unique_together = ["group", "permission", "object_pk"]
| GroupObjectPermissionAbstract |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 6507,
"end": 6670
} | class ____(_SimpleAutomotiveTestMixin):
"""Test hu_HU automotive provider methods"""
license_plate_pattern: Pattern = re.compile(r"[A-Z]{3}-\d{3}")
| TestHuHu |
python | getsentry__sentry | tests/sentry/replays/conftest.py | {
"start": 89,
"end": 529
} | class ____:
def save(self, data: dict[str, Any]) -> None:
request_url = settings.SENTRY_SNUBA + "/tests/entities/replays/insert"
response = requests.post(request_url, json=[data])
assert response.status_code == 200
return None
@pytest.fixture
def replay_store() -> ReplayStore:
... | ReplayStore |
python | pallets__werkzeug | src/werkzeug/_internal.py | {
"start": 303,
"end": 1364
} | class ____:
def __repr__(self) -> str:
return "no value"
def __reduce__(self) -> str:
return "_missing"
_missing = _Missing()
def _wsgi_decoding_dance(s: str) -> str:
return s.encode("latin1").decode(errors="replace")
def _wsgi_encoding_dance(s: str) -> str:
return s.encode().deco... | _Missing |
python | python-pillow__Pillow | src/PIL/PngImagePlugin.py | {
"start": 3163,
"end": 3768
} | class ____(IntEnum):
OP_NONE = 0
"""
No disposal is done on this frame before rendering the next frame.
See :ref:`Saving APNG sequences<apng-saving>`.
"""
OP_BACKGROUND = 1
"""
This frame’s modified region is cleared to fully transparent black before rendering
the next frame.
See... | Disposal |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 22165,
"end": 22414
} | class ____(InetTestBase):
"""Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_SCTP)
| SCTPStreamBase |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 42332,
"end": 42495
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("SECRET", "VISIBLE")
| TeamPrivacy |
python | realpython__materials | python-doctest/user.py | {
"start": 451,
"end": 910
} | class ____:
def __init__(self, name, favorite_colors):
self.name = name
self._favorite_colors = set(favorite_colors)
@property
def favorite_colors(self):
"""Return the user's favorite colors.
Usage examples:
>>> john = User("John", {"#797EF6", "#4ADEDE", "#1AA7EC"})... | User_Two |
python | getsentry__sentry-python | sentry_sdk/integrations/unraisablehook.py | {
"start": 284,
"end": 1753
} | class ____(Integration):
identifier = "unraisablehook"
@staticmethod
def setup_once():
# type: () -> None
sys.unraisablehook = _make_unraisable(sys.unraisablehook)
def _make_unraisable(old_unraisablehook):
# type: (Callable[[sys.UnraisableHookArgs], Any]) -> Callable[[sys.UnraisableHo... | UnraisablehookIntegration |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/explorer.py | {
"start": 3100,
"end": 3231
} | class ____:
Context = 'context_menu'
Header = 'header_menu'
New = 'new_menu'
OpenWith = 'open_with_menu'
| DirViewMenus |
python | mkdocs__mkdocs | mkdocs/livereload/__init__.py | {
"start": 2257,
"end": 12888
} | class ____(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGIServer):
daemon_threads = True
poll_response_timeout = 60
def __init__(
self,
builder: Callable[[], None],
host: str,
port: int,
root: str,
mount_path: str = "/",
polling_interval: floa... | LiveReloadServer |
python | davidhalter__parso | parso/parser.py | {
"start": 1594,
"end": 2112
} | class ____(Exception):
"""
Exception to signal the parser is stuck and error recovery didn't help.
Basically this shouldn't happen. It's a sign that something is really
wrong.
"""
def __init__(self, msg, type_, value, start_pos):
Exception.__init__(self, "%s: type=%r, value=%r, start_po... | InternalParseError |
python | pydantic__pydantic | pydantic/types.py | {
"start": 35528,
"end": 35822
} | class ____(BaseModel):
uuid3: UUID3
Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org'))
```
"""
UUID4 = Annotated[UUID, UuidVersion(4)]
"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 4.
```python
import uuid
from pydantic import UUID4, BaseModel
| Model |
python | django__django | tests/fixtures_regress/models.py | {
"start": 7758,
"end": 7930
} | class ____(BaseNKModel):
a = models.ForeignKey(M2MComplexCircular1A, models.CASCADE)
b = models.ForeignKey(M2MComplexCircular1B, models.CASCADE)
| M2MCircular1ThroughAB |
python | bottlepy__bottle | test/test_resources.py | {
"start": 336,
"end": 3129
} | class ____(unittest.TestCase):
def test_path_normalize(self):
for test in TEST_PATHS:
rm = ResourceManager()
rm.add_path(test)
self.assertEqual(rm.path, EXPECTED)
def test_path_create(self):
import shutil
import tempfile
tempdir = tempfile.mk... | TestResourceManager |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 16340,
"end": 16980
} | class ____(nn.Module):
"""
The residual connection is defined in ViltLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config: ViltConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, co... | ViltSelfOutput |
python | pypa__pip | tests/unit/test_network_auth.py | {
"start": 10537,
"end": 11908
} | class ____:
"""Represents the current supported API of keyring"""
class Credential:
def __init__(self, username: str, password: str) -> None:
self.username = username
self.password = password
def get_password(self, system: str, username: str) -> None:
pytest.fail("g... | KeyringModuleV2 |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/exception.py | {
"start": 504,
"end": 632
} | class ____(UnityException):
"""
Related to errors with receiving observations.
"""
pass
| UnityObservationException |
python | getsentry__sentry | src/sentry/snuba/outcomes.py | {
"start": 2729,
"end": 3397
} | class ____(Field):
def get_snuba_columns(self, raw_groupby: Sequence[str] | None = None) -> list[str]:
return ["times_seen"]
def extract_from_row(
self, row: Mapping[str, Any] | None, group: Mapping[str, Any] | None = None
) -> int:
if row is None:
return 0
retur... | TimesSeenField |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 110732,
"end": 114241
} | class ____(TorchHigherOrderOperatorVariable):
supports_input_mutation = True
supports_aliasing = True
# TODO - Go through all subclasses of WrapHigherOrderVariable to see if
# restore_side_effects can be ignored. For now, this is conservative.
restore_side_effects = True
def install_subgraph_in... | WrapHigherOrderVariable |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/utils/waiter.py | {
"start": 3544,
"end": 4136
} | class ____(str, Enum):
"""
Used to control the waiting behaviour within EMRClusterJobFlowOperator.
Choices:
- WAIT_FOR_COMPLETION - Will wait for the cluster to report "Running" state
- WAIT_FOR_STEPS_COMPLETION - Will wait for the cluster to report "Terminated" state
"""
WAIT_FOR_COMPLETI... | WaitPolicy |
python | allegroai__clearml | clearml/backend_api/services/v2_9/models.py | {
"start": 66505,
"end": 67385
} | class ____(Request):
"""
Gets model information
:param task: Task id
:type task: str
"""
_service = "models"
_action = "get_by_task_id"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task id", "type": ["string", "null"]}},
... | GetByTaskIdRequest |
python | tensorflow__tensorflow | tensorflow/python/util/nest_util.py | {
"start": 4569,
"end": 63404
} | class ____(object):
__slots__ = []
def __str__(self):
return "."
def __repr__(self):
return "."
_DOT = _DotString()
def is_nested(modality, structure):
"""Returns true if its input is a nested structure.
For Modality.CORE refer to
[tf.nest](https://www.tensorflow.org/api_docs/python/tf/nest)
... | _DotString |
python | getsentry__sentry-python | sentry_sdk/_lru_cache.py | {
"start": 104,
"end": 1229
} | class ____:
def __init__(self, max_size):
# type: (int) -> None
if max_size <= 0:
raise AssertionError(f"invalid max_size: {max_size}")
self.max_size = max_size
self._data = {} # type: dict[Any, Any]
self.hits = self.misses = 0
self.full = False
def ... | LRUCache |
python | realpython__materials | python-iterators-iterables/sequence_iter.py | {
"start": 380,
"end": 535
} | class ____:
def __init__(self, sequence):
self.sequence = sequence
def __iter__(self):
return SequenceIterator(self.sequence)
| Iterable |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style03.py | {
"start": 315,
"end": 1363
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style03.xlsx")
self.ignore_files = [
"xl/printerSettings/printerSettings1.bin",
"xl/worksheets/_rels/sheet1.x... | TestCompareXLSXFiles |
python | openai__openai-python | src/openai/types/responses/response_apply_patch_tool_call.py | {
"start": 400,
"end": 618
} | class ____(BaseModel):
diff: str
"""Diff to apply."""
path: str
"""Path of the file to create."""
type: Literal["create_file"]
"""Create a new file with the provided diff."""
| OperationCreateFile |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol22.py | {
"start": 942,
"end": 1126
} | class ____(Protocol[_T1, _T2]):
def m1(self, a: _T1, b: _T2) -> _T1 | _T2: ...
# This is right, as `_T1` and `_T2` are both covariant with the
# argument type and the return type.
| P3 |
python | ray-project__ray | python/ray/tests/unit/test_runtime_env_validation.py | {
"start": 3499,
"end": 5696
} | class ____:
def test_validate_not_a_list(self):
with pytest.raises(TypeError, match="must be a list of strings"):
parse_and_validate_py_modules(".")
def test_validate_bad_path(self):
with pytest.raises(ValueError, match="a valid path"):
parse_and_validate_py_modules(["/d... | TestValidatePyModules |
python | huggingface__transformers | src/transformers/models/encodec/modeling_encodec.py | {
"start": 9983,
"end": 11199
} | class ____(nn.Module):
"""
Residual block from SEANet model as used by EnCodec.
"""
def __init__(self, config: EncodecConfig, dim: int, dilations: list[int]):
super().__init__()
kernel_sizes = (config.residual_kernel_size, 1)
if len(kernel_sizes) != len(dilations):
r... | EncodecResnetBlock |
python | PrefectHQ__prefect | src/prefect/utilities/collections.py | {
"start": 6363,
"end": 23626
} | class ____(BaseException):
"""
A special exception used to stop recursive visits in `visit_collection`.
When raised, the expression is returned without modification and recursive visits
in that path will end.
"""
@overload
def visit_collection(
expr: Any,
visit_fn: Callable[[Any, dict[str... | StopVisiting |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_approval_response_param.py | {
"start": 260,
"end": 755
} | class ____(TypedDict, total=False):
id: Required[str]
"""The unique ID of the approval response."""
approval_request_id: Required[str]
"""The ID of the approval request being answered."""
approve: Required[bool]
"""Whether the request was approved."""
type: Required[Literal["mcp_approval_... | RealtimeMcpApprovalResponseParam |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/log/wasb_task_handler.py | {
"start": 7047,
"end": 10173
} | class ____(FileTaskHandler, LoggingMixin):
"""
WasbTaskHandler is a python log handler that handles and reads task instance logs.
It extends airflow FileTaskHandler and uploads to and reads from Wasb remote storage.
"""
trigger_should_wrap = True
def __init__(
self,
base_log_f... | WasbTaskHandler |
python | python-attrs__attrs | tests/dataclass_transform_example.py | {
"start": 172,
"end": 357
} | class ____:
with_converter: int = attr.field(converter=int)
reveal_type(DefineConverter.__init__) # noqa: F821
DefineConverter(with_converter=b"42")
@attr.frozen()
| DefineConverter |
python | pytorch__pytorch | torch/_dynamo/variables/dicts.py | {
"start": 56935,
"end": 58192
} | class ____(SetVariable):
def debug_repr(self) -> str:
if not self.items:
return "dict_keys([])"
else:
return (
"dict_keys([" + ",".join(k.vt.debug_repr() for k in self.items) + "])"
)
def install_dict_keys_match_guard(self) -> None:
# ... | DictKeySetVariable |
python | conda__conda | conda/notices/types.py | {
"start": 1593,
"end": 3615
} | class ____(NamedTuple):
url: str
name: str
json_data: dict | None
@property
def notices(self) -> Sequence[ChannelNotice]:
if self.json_data:
notices = self.json_data.get("notices", ())
return tuple(
ChannelNotice(
id=str(notice.ge... | ChannelNoticeResponse |
python | pyca__cryptography | tests/hazmat/primitives/test_sm4.py | {
"start": 2688,
"end": 3198
} | class ____:
test_cfb = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "SM4"),
["draft-ribose-cfrg-sm4-10-ctr.txt"],
lambda key, **kwargs: algorithms.SM4(binascii.unhexlify(key)),
lambda iv, **kwargs: modes.CTR(binascii.unhexlify(iv)),
)
@pytest.mark.s... | TestSM4ModeCTR |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-kdbai/llama_index/vector_stores/kdbai/base.py | {
"start": 652,
"end": 8086
} | class ____(BasePydanticVectorStore):
"""
The KDBAI Vector Store.
In this vector store we store the text, its embedding and
its metadata in a KDBAI vector store table. This implementation
allows the use of an already existing table.
Args:
table kdbai.Table: The KDB.AI table to use as st... | KDBAIVectorStore |
python | django-haystack__django-haystack | test_haystack/test_indexes.py | {
"start": 22572,
"end": 22730
} | class ____(indexes.ModelSearchIndex, indexes.Indexable):
class Meta:
model = MockModel
excludes = ["author", "foo"]
| ExcludesModelSearchIndex |
python | redis__redis-py | tests/test_http/test_http_client.py | {
"start": 315,
"end": 854
} | class ____:
def __init__(
self, *, status: int, headers: Dict[str, str], url: str, content: bytes
):
self.status = status
self.headers = headers
self._url = url
self._content = content
def read(self) -> bytes:
return self._content
def geturl(self) -> str... | FakeResponse |
python | huggingface__transformers | src/transformers/trainer_pt_utils.py | {
"start": 52079,
"end": 53963
} | class ____(LRScheduler):
"""
For Layer-wise optimizers such as GaLoRE optimizer, the optimization and scheduling step
are already done through the post gradient hooks. Therefore
the trick is to create a dummy scheduler that can take arbitrary
args and kwargs and return a no-op during training.
"... | LayerWiseDummyScheduler |
python | numba__numba | numba/core/compiler_machinery.py | {
"start": 2920,
"end": 3625
} | class ____(object):
"""This looks and behaves like LLVM's AnalysisUsage because its like that.
"""
def __init__(self):
self._required = set()
self._preserved = set()
def get_required_set(self):
return self._required
def get_preserved_set(self):
return self._preserv... | AnalysisUsage |
python | apache__airflow | providers/ydb/src/airflow/providers/ydb/hooks/ydb.py | {
"start": 1558,
"end": 3139
} | class ____:
"""YDB cursor wrapper."""
def __init__(self, delegatee: DbApiCursor, is_ddl: bool):
self.delegatee: DbApiCursor = delegatee
self.is_ddl: bool = is_ddl
def execute(self, sql: str, parameters: Mapping[str, Any] | None = None):
if parameters is not None:
raise ... | YDBCursor |
python | ray-project__ray | python/ray/serve/tests/test_list_outbound_deployments.py | {
"start": 842,
"end": 1288
} | class ____:
def __init__(self, handles_dict: dict, handles_list: list):
self.handles = handles_dict # {"a": handle_a, "b": handle_b}
self.handle_list = handles_list # [handle_a, handle_b]
async def __call__(self, x: int) -> int:
result_a = await self.handles["a"].remote(x)
res... | UpstreamWithNestedHandles |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 250362,
"end": 252901
} | class ____(unittest.TestCase):
def test_address(self):
port = socket_helper.find_unused_port()
with socket.create_server(("127.0.0.1", port)) as sock:
self.assertEqual(sock.getsockname()[0], "127.0.0.1")
self.assertEqual(sock.getsockname()[1], port)
if socket_helper.... | CreateServerTest |
python | ray-project__ray | python/ray/data/_internal/logical/operators/map_operator.py | {
"start": 7180,
"end": 8747
} | class ____(AbstractUDFMap):
"""Logical operator for map_batches."""
def __init__(
self,
input_op: LogicalOperator,
fn: UserDefinedFunction,
batch_size: Optional[int] = None,
batch_format: str = "default",
zero_copy_batch: bool = True,
fn_args: Optional[It... | MapBatches |
python | streamlit__streamlit | lib/streamlit/runtime/media_file_storage.py | {
"start": 736,
"end": 892
} | class ____(Enum):
# st.image, st.video, st.audio files
MEDIA = "media"
# st.download_button files
DOWNLOADABLE = "downloadable"
| MediaFileKind |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 5308,
"end": 7052
} | class ____(ABC, _EntitySubscription):
"""
An abstraction layer for all different entity subscriptions. It is important to note that
this abstraction layer was added because the subscription logic was too coupled to the
events and transactions entities, which was fine initially but now as we are adding m... | BaseEntitySubscription |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 2030,
"end": 5950
} | class ____:
item_class: type | None = None
def test_keep_single_value(self):
"""Loaded item should contain values from the initial item"""
input_item = self.item_class(name="foo")
il = ItemLoader(item=input_item)
loaded_item = il.load_item()
assert isinstance(loaded_item... | InitializationTestMixin |
python | django-extensions__django-extensions | django_extensions/admin/__init__.py | {
"start": 7064,
"end": 7179
} | class ____(
ForeignKeyAutocompleteAdminMixin, admin.TabularInline
):
pass
| ForeignKeyAutocompleteTabularInline |
python | ray-project__ray | python/ray/serve/_private/common.py | {
"start": 26225,
"end": 26325
} | class ____(str, Enum):
UNDEFINED = "UNDEFINED"
HTTP = "HTTP"
GRPC = "gRPC"
| RequestProtocol |
python | sqlalchemy__sqlalchemy | test/sql/test_sequences.py | {
"start": 979,
"end": 4750
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
__sparse_driver_backend__ = True
@testing.combinations(
(Sequence("foo_seq"), ""),
(Sequence("foo_seq", start=5), "START WITH 5"),
(Sequence("foo_seq", increment=2), "INCREMENT BY 2"),
(
... | SequenceDDLTest |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/bindings_screen_overrides_show.py | {
"start": 329,
"end": 679
} | class ____(App):
"""Regression test for https://github.com/Textualize/textual/issues/4382"""
BINDINGS = [
Binding("p", "app.pop_screen", "Binding hidden", show=False),
]
def on_mount(self) -> None:
self.push_screen(ShowBindingScreen())
if __name__ == "__main__":
app = HideBinding... | HideBindingApp |
python | apache__airflow | airflow-core/tests/unit/charts/log_groomer.py | {
"start": 914,
"end": 10387
} | class ____:
obj_name: str = ""
folder: str = ""
def test_log_groomer_collector_default_enabled(self):
if self.obj_name == "dag-processor":
values = {"dagProcessor": {"enabled": True}}
else:
values = None
docs = render_chart(
values=values, show_o... | LogGroomerTestBase |
python | spyder-ide__spyder | spyder/plugins/onlinehelp/widgets.py | {
"start": 1155,
"end": 2142
} | class ____:
PackageLabel = 'package_label'
UrlCombo = 'url_combo'
# =============================================================================
# Pydoc adjustments
# =============================================================================
# This is needed to prevent pydoc raise an ErrorDuringImport whe... | PydocBrowserToolbarItems |
python | sympy__sympy | setup.py | {
"start": 4746,
"end": 5544
} | class ____(Command):
"""Generate code with antlr4"""
description = "generate parser code from antlr grammars"
user_options = [] # setuptools complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)... | antlr |
python | ansible__ansible | test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py | {
"start": 1202,
"end": 10983
} | class ____(BaseInventoryPlugin, Cacheable):
NAME = 'exercise_cache'
test_cache_methods = [
'test_plugin_name',
'test_update_cache_if_changed',
'test_set_cache',
'test_load_whole_cache',
'test_iter',
'test_len',
'test_get_missing_key',
'test_get_e... | InventoryModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-pinterest/components.py | {
"start": 1239,
"end": 1828
} | class ____(BackoffStrategy):
_re = re.compile(r"Retry after\s+(\d+)\s+seconds", re.IGNORECASE)
def backoff_time(self, response_or_exception, attempt_count: int) -> float:
try:
if isinstance(response_or_exception, requests.Response):
data = response_or_exception.json()
... | PinterestAnalyticsBackoffStrategy |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 16884,
"end": 17073
} | class ____(nodes.strong, not_smartquotable):
"""Node that behaves like `strong`, but further text processors are not
applied (e.g. smartypants for HTML output).
"""
| literal_strong |
python | sqlalchemy__sqlalchemy | test/orm/test_versioning.py | {
"start": 30040,
"end": 33457
} | class ____(fixtures.MappedTest):
__sparse_driver_backend__ = True
__requires__ = ("sane_rowcount",)
@classmethod
def define_tables(cls, metadata):
Table(
"p",
metadata,
Column("id", String(10), primary_key=True),
Column("version_id", String(32), n... | AlternateGeneratorTest |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_branch_operator.py | {
"start": 1868,
"end": 1977
} | class ____(BaseBranchOperator):
def choose_branch(self, context):
return "branch_1"
| ChooseBranchOne |
python | google__jax | jax/_src/config.py | {
"start": 31996,
"end": 34960
} | class ____(Generic[_T]):
__slots__ = ("_name", "value", "_update_hook")
_name: str
value: _T
_update_hook: Callable[[Any], None] | None
def __init__(self, name: str, default: _T,
update_hook: Callable[[Any], None] | None = None):
self._name = name
self._update_hook = update_hook
... | Flag |
python | cython__cython | Cython/Compiler/Code.py | {
"start": 6765,
"end": 10295
} | class ____:
"""
An include file and/or verbatim C code to be included in the
generated sources.
"""
# attributes:
#
# pieces {order: unicode}: pieces of C code to be generated.
# For the included file, the key "order" is zero.
# For verbatim include code, th... | IncludeCode |
python | mlflow__mlflow | mlflow/types/type_hints.py | {
"start": 2818,
"end": 2895
} | class ____(NamedTuple):
dtype: COLSPEC_TYPES
required: bool
| ColSpecType |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/run_launcher.py | {
"start": 1770,
"end": 2115
} | class ____(BaseModel):
containerConfig: Optional[dict[str, Any]] = None
podSpecConfig: Optional[dict[str, Any]] = None
podTemplateSpecMetadata: Optional[dict[str, Any]] = None
jobSpecConfig: Optional[dict[str, Any]] = None
jobMetadata: Optional[dict[str, Any]] = None
model_config = ConfigDict(e... | RunK8sConfig |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-couchbase/llama_index/vector_stores/couchbase/base.py | {
"start": 32786,
"end": 33949
} | class ____(CouchbaseSearchVectorStore):
"""
Couchbase Vector Store (deprecated).
This class is deprecated, please use CouchbaseSearchVectorStore instead.
"""
def __init__(
self,
cluster: Any,
bucket_name: str,
scope_name: str,
collection_name: str,
i... | CouchbaseVectorStore |
python | giampaolo__psutil | tests/test_linux.py | {
"start": 65876,
"end": 66693
} | class ____(PsutilTestCase):
def test_it(self):
def open_mock(name, *args, **kwargs):
if name.endswith("/energy_now"):
return io.StringIO("60000000")
elif name.endswith("/power_now"):
return io.StringIO("0")
elif name.endswith("/energy_full"... | TestSensorsBatteryEmulated |
python | celery__celery | t/unit/backends/test_database.py | {
"start": 13394,
"end": 16612
} | class ____:
def test_after_fork(self):
s = SessionManager()
assert not s.forked
s._after_fork()
assert s.forked
@patch('celery.backends.database.session.create_engine')
def test_get_engine_forked(self, create_engine):
s = SessionManager()
s._after_fork()
... | test_SessionManager |
python | numba__numba | numba/core/codegen.py | {
"start": 38685,
"end": 39621
} | class ____(CPUCodeLibrary):
def get_pointer_to_function(self, name):
"""
Generate native code for function named *name* and return a pointer
to the start of the function (as an integer).
This function implicitly calls .finalize().
Returns
-------
pointer : ... | JITCodeLibrary |
python | huggingface__transformers | src/transformers/models/exaone4/modeling_exaone4.py | {
"start": 19829,
"end": 24041
} | class ____(Exaone4PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Exaon... | Exaone4ForCausalLM |
python | scipy__scipy | benchmarks/benchmarks/signal.py | {
"start": 5864,
"end": 6517
} | class ____(Benchmark):
param_names = ['up', 'down', 'axis']
params = [
[1, 4],
[1, 4],
[0, -1],
]
def setup(self, up, down, axis):
rng = np.random.default_rng(1234)
# sample a bunch of pairs of 2d arrays
pairs = []
for nfilt in [8, ]:
... | Upfirdn2D |
python | modin-project__modin | modin/tests/pandas/extensions/test_base_extensions.py | {
"start": 4836,
"end": 5672
} | class ____:
"""
Make sure to test that we override special "dunder" methods like __len__
correctly. python calls these methods with DataFrame.__len__(obj)
rather than getattr(obj, "__len__")().
source: https://docs.python.org/3/reference/datamodel.html#special-lookup
"""
@pytest.mark.parame... | TestDunders |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/__init__.py | {
"start": 3685,
"end": 4206
} | class ____:
"""Class with documented class and instance attributes."""
#: Doc comment for class attribute InstAttCls.ca1.
#: It can have multiple lines.
ca1 = 'a'
ca2 = 'b' #: Doc comment for InstAttCls.ca2. One line only.
ca3 = 'c'
"""Docstring for class attribute InstAttCls.ca3."""
... | InstAttCls |
python | automl__auto-sklearn | autosklearn/pipeline/components/classification/mlp.py | {
"start": 667,
"end": 10434
} | class ____(IterativeComponent, AutoSklearnClassificationAlgorithm):
def __init__(
self,
hidden_layer_depth,
num_nodes_per_layer,
activation,
alpha,
learning_rate_init,
early_stopping,
solver,
batch_size,
n_iter_no_change,
tol,
... | MLPClassifier |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/physical_operator.py | {
"start": 10987,
"end": 32399
} | class ____(Operator):
"""Abstract class for physical operators.
An operator transforms one or more input streams of RefBundles into a single
output stream of RefBundles.
Physical operators are stateful and non-serializable; they live on the driver side
of the Dataset only.
Here's a simple exa... | PhysicalOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.