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 | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 30041,
"end": 33222
} | class ____(state_types.Transform):
collective_axes: tuple[Hashable, ...]
def transform_shape(self, shape):
return shape
def transform_dtype(self, dtype):
return dtype
def untransform_index(
self, idxs: tuple[Index, ...]
) -> tuple[tuple[Index, ...], state_types.Transform]:
return idxs, se... | MulticastRef |
python | MongoEngine__mongoengine | tests/fields/test_email_field.py | {
"start": 119,
"end": 3994
} | class ____(MongoDBTestCase):
def test_generic_behavior(self):
class User(Document):
email = EmailField()
user = User(email="ross@example.com")
user.validate()
user = User(email="ross@example.co.uk")
user.validate()
user = User(
email=("Kofq@... | TestEmailField |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/sort_children.py | {
"start": 164,
"end": 445
} | class ____(Label):
DEFAULT_CSS = """
Number {
width: 1fr;
}
"""
def __init__(self, number: int) -> None:
self.number = number
super().__init__(classes=f"number{number}")
def render(self) -> str:
return str(self.number)
| Number |
python | pytest-dev__pytest | src/_pytest/debugging.py | {
"start": 9686,
"end": 10336
} | class ____:
def pytest_exception_interact(
self, node: Node, call: CallInfo[Any], report: BaseReport
) -> None:
capman = node.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture(... | PdbInvoke |
python | pytorch__pytorch | test/export/test_tools.py | {
"start": 498,
"end": 1889
} | class ____(TestCase):
def test_report_exportability_basic(self):
class Module(torch.nn.Module):
def forward(self, x, y):
return x[0] + y
f = Module()
inp = ([torch.ones(1, 3)], torch.ones(1, 3))
report = report_exportability(f, inp)
self.assertTr... | TestExportTools |
python | OmkarPathak__pygorithm | pygorithm/geometry/line2.py | {
"start": 149,
"end": 23192
} | class ____(object):
"""
Define a two-dimensional directed line segment defined by two points.
This class is mostly used as a way to cache information that is
regularly required when working on geometrical problems.
.. caution::
Lines should be used as if they were completely immutable to... | Line2 |
python | ray-project__ray | release/long_running_tests/workloads/many_actor_tasks.py | {
"start": 988,
"end": 2021
} | class ____(object):
def __init__(self):
self.value = 0
def method(self):
self.value += 1
return np.zeros(1024, dtype=np.uint8)
actors = [
Actor._remote([], {}, num_cpus=0.1, resources={str(i % num_nodes): 0.1})
for i in range(num_nodes * 5)
]
iteration = 0
start_time = time.t... | Actor |
python | pytorch__pytorch | test/dynamo/test_autograd_function.py | {
"start": 42390,
"end": 52544
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[]", L_y_: "f32[]"):
l_x_ = L_x_
l_y_ = L_y_
fwd_body_0 = self.fwd_body_0
bwd_body_0 = self.bwd_body_0
autograd_function_apply = torch.ops.higher_order.autograd_function_apply(fwd_body_0, bwd_body_0, l_x_, l_y_, args_t... | GraphModule |
python | tensorflow__tensorflow | tensorflow/python/data/ops/readers.py | {
"start": 18690,
"end": 19464
} | class ____(dataset_ops.DatasetV1Adapter):
"""A `Dataset` comprising records from one or more TFRecord files."""
def __init__(self,
filenames,
compression_type=None,
buffer_size=None,
num_parallel_reads=None,
name=None):
wrapped = TFReco... | TFRecordDatasetV1 |
python | doocs__leetcode | solution/3400-3499/3439.Reschedule Meetings for Maximum Free Time I/Solution.py | {
"start": 0,
"end": 486
} | class ____:
def maxFreeTime(
self, eventTime: int, k: int, startTime: List[int], endTime: List[int]
) -> int:
nums = [startTime[0]]
for i in range(1, len(endTime)):
nums.append(startTime[i] - endTime[i - 1])
nums.append(eventTime - endTime[-1])
ans = s = 0
... | Solution |
python | pytorch__pytorch | test/test_ops_jit.py | {
"start": 1411,
"end": 14790
} | class ____(JitCommonTestCase):
exact_dtype = True
# Tests that the forward and backward passes of operations produce the
# same values for the cross-product of op variants (function, method, inplace)
# and runtimes (eager, traced, scripted).
# TODO WARNING: inplace x {traced, scripted} not curr... | TestJit |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/etcd_rendezvous.py | {
"start": 1635,
"end": 2598
} | class ____(Exception):
pass
# Default timeout for the rendezvous.
_DEFAULT_TIMEOUT: int = 600 # 10 minutes
# Additional waiting time after reaching the minimum number of nodes
# in case the rendezvous is elastic (min != max).
_DEFAULT_LAST_CALL_TIMEOUT: int = 30 # 30 seconds
# Various constants used internall... | EtcdRendezvousRetryImmediately |
python | PrefectHQ__prefect | src/prefect/events/schemas/automations.py | {
"start": 12235,
"end": 14167
} | class ____(CompositeTrigger):
"""A composite trigger that requires some number of triggers to have fired
within the given time period in a specific order"""
type: Literal["sequence"] = "sequence"
def describe_for_cli(self, indent: int = 0) -> str:
"""Return a human-readable description of this... | SequenceTrigger |
python | encode__django-rest-framework | rest_framework/utils/serializer_helpers.py | {
"start": 2863,
"end": 3479
} | class ____(BoundField):
def as_form_field(self):
value = self.value
# When HTML form input is used and the input is not valid
# value will be a JSONString, rather than a JSON primitive.
if not getattr(value, 'is_json_string', False):
with contextlib.suppress(TypeError, Va... | JSONBoundField |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/metadata.py | {
"start": 644,
"end": 733
} | class ____(DistlibException):
"""A required metadata is missing"""
| MetadataMissingError |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_emr_serverless.py | {
"start": 2623,
"end": 14085
} | class ____:
@mock.patch.object(EmrServerlessHook, "get_waiter")
@mock.patch.object(EmrServerlessHook, "conn")
def test_execute_successfully_with_wait_for_completion(self, mock_conn, mock_waiter):
mock_waiter().wait.return_value = True
mock_conn.create_application.return_value = {
... | TestEmrServerlessCreateApplicationOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass2.py | {
"start": 228,
"end": 326
} | class ____(A, param_a=123):
pass
# This should generate two errors because param_a is missing.
| B |
python | kamyu104__LeetCode-Solutions | Python/implement-trie-prefix-tree.py | {
"start": 193,
"end": 1245
} | class ____(object):
def __init__(self):
self.root = TrieNode()
# @param {string} word
# @return {void}
# Inserts a word into the trie.
def insert(self, word):
cur = self.root
for c in word:
if not c in cur.leaves:
cur.leaves[c] = TrieNode()
... | Trie |
python | getsentry__sentry-python | sentry_sdk/profiler/continuous_profiler.py | {
"start": 15731,
"end": 18276
} | class ____(ContinuousScheduler):
"""
This scheduler is based on the thread scheduler but adapted to work with
gevent. When using gevent, it may monkey patch the threading modules
(`threading` and `_thread`). This results in the use of greenlets instead
of native threads.
This is an issue becaus... | GeventContinuousScheduler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 5929,
"end": 6258
} | class ____(StatementRole, ReturnsRowsRole):
__slots__ = ()
_role_name = "SELECT construct or equivalent text() construct"
def subquery(self) -> Subquery:
raise NotImplementedError(
"All SelectStatementRole objects should implement a "
".subquery() method."
)
| SelectStatementRole |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataplex.py | {
"start": 10041,
"end": 11217
} | class ____:
@mock.patch(HOOK_STR)
@mock.patch(LAKE_STR)
def test_execute(self, lake_mock, hook_mock):
op = DataplexCreateLakeOperator(
task_id="create_dataplex_lake",
project_id=PROJECT_ID,
region=REGION,
lake_id=LAKE_ID,
body=BODY_LAKE,
... | TestDataplexCreateLakeOperator |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-bedrock/tests/test_bedrock_async.py | {
"start": 341,
"end": 447
} | class ____:
async def read(self):
return json.dumps(EXP_RESPONSE).encode()
| AsyncMockStreamReader |
python | sphinx-doc__sphinx | sphinx/builders/dummy.py | {
"start": 324,
"end": 1007
} | class ____(Builder):
name = 'dummy'
epilog = __('The dummy builder generates no files.')
allow_parallel = True
def init(self) -> None:
pass
def get_outdated_docs(self) -> set[str]:
return self.env.found_docs
def get_target_uri(self, docname: str, typ: str | None = None) -> st... | DummyBuilder |
python | ansible__ansible | test/units/module_utils/common/test_dict_transformations.py | {
"start": 3544,
"end": 3948
} | class ____:
def test_dict_merge_invalid_dict(self):
""" if b is not a dict, return b """
res = dict_merge({}, None)
assert res is None
def test_merge_sub_dicts(self):
"""merge sub dicts """
a = {'a': {'a1': 1}}
b = {'a': {'b1': 2}}
c = {'a': {'a1': 1, 'b... | TestCaseAzureIncidental |
python | numba__numba | numba/parfors/parfor.py | {
"start": 81710,
"end": 90878
} | class ____:
"""
Convert supported Numpy functions, as well as arrayexpr nodes, to
parfor nodes.
"""
def __init__(self, pass_states):
self.pass_states = pass_states
self.rewritten = []
def run(self, blocks):
pass_states = self.pass_states
topo_order = find_topo_or... | ConvertNumpyPass |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 4229,
"end": 5462
} | class ____(unittest.TestCase):
def test_missing_arguments(self):
application = Application()
self.assertRaises(
KeyError,
HTTPServer,
application,
ssl_options={"keyfile": "/__missing__.crt"},
)
def test_missing_key(self):
"""A miss... | BadSSLOptionsTest |
python | ray-project__ray | python/ray/train/v2/_internal/callbacks/backend_setup.py | {
"start": 285,
"end": 1056
} | class ____(WorkerGroupCallback):
def __init__(self, backend_config: BackendConfig):
self._backend_config = backend_config
self._backend = backend_config.backend_cls()
def after_worker_group_start(self, worker_group: WorkerGroup):
self._backend.on_start(worker_group, self._backend_config... | BackendSetupCallback |
python | kamyu104__LeetCode-Solutions | Python/number-of-subarrays-that-match-a-pattern-ii.py | {
"start": 35,
"end": 1071
} | class ____(object):
def countMatchingSubarrays(self, nums, pattern):
"""
:type nums: List[int]
:type pattern: List[int]
:rtype: int
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
... | Solution |
python | walkccc__LeetCode | solutions/1073. Adding Two Negabinary Numbers/1073.py | {
"start": 0,
"end": 378
} | class ____:
def addNegabinary(self, arr1: list[int], arr2: list[int]) -> list[int]:
ans = []
carry = 0
while carry != 0 or arr1 or arr2:
if arr1:
carry += arr1.pop()
if arr2:
carry += arr2.pop()
ans.append(carry & 1)
carry = -(carry >> 1)
while len(ans) > 1 an... | Solution |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 7365,
"end": 9285
} | class ____:
async def test_scheduled_time_copied_from_scheduled_to_pending(
self,
session,
run_type,
initialize_orchestration,
):
initial_state_type = states.StateType.SCHEDULED
proposed_state_type = states.StateType.PENDING
intended_transition = (initial_... | TestCopyScheduledTime |
python | huggingface__transformers | tests/models/codegen/test_modeling_codegen.py | {
"start": 17813,
"end": 20406
} | class ____(unittest.TestCase):
@cached_property
def cached_tokenizer(self):
return AutoTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
@cached_property
def cached_model(self):
return CodeGenForCausalLM.from_pretrained("Salesforce/codegen-350M-mono")
@slow
def test_lm_... | CodeGenModelLanguageGenerationTest |
python | zarr-developers__zarr-python | src/zarr/core/metadata/v3.py | {
"start": 5950,
"end": 6717
} | class ____(TypedDict):
"""
A typed dictionary model for zarr v3 metadata.
"""
zarr_format: Literal[3]
node_type: Literal["array"]
data_type: str | NamedConfig[str, Mapping[str, object]]
shape: tuple[int, ...]
chunk_grid: NamedConfig[str, Mapping[str, object]]
chunk_key_encoding: Nam... | ArrayMetadataJSON_V3 |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/uninitialized_attributes.py | {
"start": 0,
"end": 58
} | class ____:
attr1: int #: docstring
attr2: str
| Base |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_diag_test.py | {
"start": 1268,
"end": 10303
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enable... | LinearOperatorDiagTest |
python | ray-project__ray | release/nightly_tests/multimodal_inference_benchmarks/audio_transcription/ray_data_main.py | {
"start": 1635,
"end": 3316
} | class ____:
def __init__(self):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.dtype = torch.float16
self.model_id = TRANSCRIPTION_MODEL
self.model = AutoModelForSpeechSeq2Seq.from_pretrained(
self.model_id,
torch_dtype=self.dtype,
... | Transcriber |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 17798,
"end": 18455
} | class ____(Node):
# Part of a C declaration.
#
# Processing during analyse_declarations phase:
#
# analyse
# Returns (name, type) pair where name is the
# CNameDeclaratorNode of the name being declared
# and type is the type it is being declared as.
#
# calling_... | CDeclaratorNode |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 5509,
"end": 5848
} | class ____(Iterator[int]):
# Note: *Iterable*, not *Iterator*, returned!
def __iter__(self) -> Iterable[int]:
... # Y034 "__iter__" methods in classes like "BadIterator4" usually return "self" at runtime. Consider using "typing_extensions.Self" in "BadIterator4.__iter__", e.g. "def __iter__(self) -> Se... | BadIterator4 |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 218408,
"end": 225729
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@test_util.disable_xla(
"b/141236442: "
"non_max_suppression with dynamic output shape unsupported.")
def testSelectFromThreeClustersV1(self):
with ops.Graph().as_default():
boxes_np = [[0, 0, ... | NonMaxSuppressionPaddedTest |
python | jazzband__django-formtools | tests/wizard/test_forms.py | {
"start": 2561,
"end": 11406
} | class ____(TestCase):
def test_form_init(self):
testform = TestWizard.get_initkwargs([Step1, Step2])
self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2})
testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)])
self.assertEqual(testform['form_list'], {... | FormTests |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 63990,
"end": 64153
} | class ____(_ConfigBase):
generative: Union[GenerativeSearches, str]
model: Dict[str, Any]
GenerativeConfig = _GenerativeConfig
@dataclass
| _GenerativeConfig |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 18941,
"end": 19072
} | class ____(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return False
| BasicObjectPerm |
python | getsentry__sentry | src/sentry/models/releases/release_project.py | {
"start": 471,
"end": 1464
} | class ____(BaseManager["ReleaseProject"]):
@staticmethod
def _on_post(project, trigger):
from sentry.dynamic_sampling import ProjectBoostedReleases
project_boosted_releases = ProjectBoostedReleases(project.id)
# We want to invalidate the project config only if dynamic sampling is enable... | ReleaseProjectModelManager |
python | jpadilla__pyjwt | tests/test_api_jwk.py | {
"start": 7421,
"end": 11352
} | class ____:
@crypto_required
def test_should_load_keys_from_jwk_data_dict(self):
algo = RSAAlgorithm(RSAAlgorithm.SHA256)
with open(key_path("jwk_rsa_pub.json")) as keyfile:
pub_key = algo.from_jwk(keyfile.read())
key_data_str = algo.to_jwk(pub_key)
key_data = json.... | TestPyJWKSet |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 17661,
"end": 18028
} | class ____(TypedDict, total=False):
"""A single row from search results.
Only includes fields that were actually returned in the search.
The 'id' field is always present.
"""
id: str # Always present
document: Optional[str]
embedding: Optional[List[float]]
metadata: Optional[Dict[str,... | SearchResultRow |
python | astropy__astropy | astropy/io/ascii/latex.py | {
"start": 15923,
"end": 17353
} | class ____(LatexHeader):
r"""In a `deluxetable
<http://fits.gsfc.nasa.gov/standard30/deluxetable.sty>`_ some header
keywords differ from standard LaTeX.
This header is modified to take that into account.
"""
header_start = r"\tablehead"
splitter_class = AASTexHeaderSplitter
def start_... | AASTexHeader |
python | doocs__leetcode | solution/0600-0699/0605.Can Place Flowers/Solution.py | {
"start": 0,
"end": 303
} | class ____:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
flowerbed = [0] + flowerbed + [0]
for i in range(1, len(flowerbed) - 1):
if sum(flowerbed[i - 1 : i + 2]) == 0:
flowerbed[i] = 1
n -= 1
return n <= 0
| Solution |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 132707,
"end": 133873
} | class ____:
def test_plurals(self):
assert self.locale._format_timeframe("now", 0) == "nu"
assert self.locale._format_timeframe("second", 1) == "een seconde"
assert self.locale._format_timeframe("seconds", 30) == "30 seconden"
assert self.locale._format_timeframe("minute", 1) == "een... | TestDutchLocale |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 226103,
"end": 227563
} | class ____(TestCase):
class Foo:
def __init__(self, value):
self.value = value
self.iface = {"typestr": "f8"}
def __float__(self):
return float(self.value)
@property
def __array_interface__(self):
return self.iface
f = Foo(0.5)
... | TestArrayInterface |
python | Netflix__metaflow | metaflow/plugins/kubernetes/kube_utils.py | {
"start": 246,
"end": 4140
} | class ____(MetaflowException):
headline = "Kubernetes error"
def parse_cli_options(flow_name, run_id, user, my_runs, echo):
if user and my_runs:
raise CommandException("--user and --my-runs are mutually exclusive.")
if run_id and my_runs:
raise CommandException("--run_id and --my-runs are... | KubernetesException |
python | tensorflow__tensorflow | tensorflow/python/ops/gradients_test.py | {
"start": 26996,
"end": 27335
} | class ____(test_util.TensorFlowTestCase):
def testPreventGradient(self):
with ops.Graph().as_default():
inp = constant(1.0, shape=[100, 32], name="in")
out = array_ops.prevent_gradient(inp)
with self.assertRaisesRegex(LookupError, "explicitly disabled"):
_ = gradients.gradients(out, inp... | PreventGradientTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 7380,
"end": 8395
} | class ____(KeyValueParser):
"""Composite argument parser for network remote key/value pairs."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]:
"""Return a dictionary of key names and value parsers."""
return dict(
provider=ChoicesParser(REMOTE_PROVIDERS),
... | NetworkRemoteKeyValueParser |
python | keras-team__keras | keras/src/ops/math.py | {
"start": 4901,
"end": 6379
} | class ____(Operation):
def __init__(self, k, sorted=True, *, name=None):
super().__init__(name=name)
self.k = k
self.sorted = sorted
def compute_output_spec(self, x):
output_shape = list(x.shape)
output_shape[-1] = self.k
# Return a tuple (values, indices).
... | TopK |
python | coleifer__peewee | tests/sqliteq.py | {
"start": 577,
"end": 698
} | class ____(TestModel):
name = TextField(unique=True)
class Meta:
table_name = 'threaded_db_test_user'
| User |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 18025,
"end": 18229
} | class ____(HTTPException):
"""*423* `Locked`
Used if the resource that is being accessed is locked.
"""
code = 423
description = "The resource that is being accessed is locked."
| Locked |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_return_annotation_extends.py | {
"start": 279,
"end": 316
} | class ____(Test1_C1):
pass
| Test1_C2 |
python | astropy__astropy | astropy/table/column.py | {
"start": 2785,
"end": 12670
} | class ____(np.ndarray):
"""
Boolean mask array that is always False.
This is used to create a stub ``mask`` property which is a boolean array of
``False`` used by default for mixin columns and corresponding to the mixin
column data shape. The ``mask`` looks like a normal numpy array but an
exc... | FalseArray |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 911083,
"end": 912052
} | class ____(sgqlc.types.relay.Connection):
"""A list of reactions that have been left on the subject."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count", "viewer_has_reacted")
edges = sgqlc.types.Field(sgqlc.types.list_of("ReactionEdge"), graphql_name="edges")
... | ReactionConnection |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 296293,
"end": 297857
} | class ____(TypedDict, total=False):
"""
:class:`altair.VariableParameter` ``TypedDict`` wrapper.
Parameters
----------
name
A unique name for the variable parameter. Parameter names should be valid JavaScript
identifiers: they should contain only alphanumeric characters (or "$", or ... | VariableParameterKwds |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 28520,
"end": 141078
} | class ____:
def test_default_auto_detection(self, hatch, helpers, temp_dir, config_file):
config_file.model.template.plugins["default"]["src-layout"] = False
config_file.save()
project_name = "My.App"
with temp_dir.as_cwd():
result = hatch("new", project_name)
... | TestBuildStandard |
python | getsentry__sentry | src/sentry/utils/auth.py | {
"start": 1728,
"end": 3051
} | class ____:
"""
The value returned from to_dict is stored in the django session cookie, with the org id being the key.
"""
SSO_SESSION_KEY = "sso_s"
SSO_LOGIN_TIMESTAMP = "ts"
def __init__(self, organization_id: int, time: datetime) -> None:
self.organization_id = organization_id
... | SsoSession |
python | google__jax | jax/_src/pallas/pipelining/schedule_api.py | {
"start": 2066,
"end": 11398
} | class ____:
"""Constructs an asynchronous pipeline stage."""
def __init__(self, max_in_flight: int):
self.start_func = None
self.end_func = None
self.max_in_flight = max_in_flight
def def_start(self, func):
self.start_func = func
return self
def def_end(self, func):
self.end_func = fu... | AsyncStage |
python | walkccc__LeetCode | solutions/802. Find Eventual Safe States/802.py | {
"start": 85,
"end": 570
} | class ____:
def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:
states = [State.INIT] * len(graph)
def hasCycle(u: int) -> bool:
if states[u] == State.VISITING:
return True
if states[u] == State.VISITED:
return False
states[u] = State.VISITING
if any(hasC... | Solution |
python | openai__openai-python | src/openai/types/static_file_chunking_strategy_object.py | {
"start": 278,
"end": 424
} | class ____(BaseModel):
static: StaticFileChunkingStrategy
type: Literal["static"]
"""Always `static`."""
| StaticFileChunkingStrategyObject |
python | Netflix__metaflow | metaflow/plugins/metadata_providers/spin.py | {
"start": 140,
"end": 472
} | class ____(LocalMetadataProvider):
TYPE = "spin"
DATASTORE_DIR = DATASTORE_SPIN_LOCAL_DIR # ".metaflow_spin"
@classmethod
def _get_storage_class(cls):
from metaflow.plugins.datastores.spin_storage import SpinStorage
return SpinStorage
def version(self):
return "spin"
| SpinMetadataProvider |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py | {
"start": 7303,
"end": 7693
} | class ____:
"""test_finds_missing_raises_from_setter_sphinx
Example of a setter having missing raises documentation in
the Sphinx style docstring of the property
"""
@property
def foo(self): # [missing-raises-doc]
"""docstring ...
:type: int
"""
return 10
... | Foo |
python | huggingface__transformers | src/transformers/models/chinese_clip/modeling_chinese_clip.py | {
"start": 33977,
"end": 39309
} | class ____(ChineseCLIPPreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
all you need](https://huggingface.co... | ChineseCLIPTextModel |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 27133,
"end": 27675
} | class ____(models.Model):
"""
Historic table with one to one relationship to non-historic table.
In this case it should simply behave like OneToOneField because
the origin model (this one) cannot be historic, so one to one field
lookups are always "current".
"""
name = models.CharField(max... | TestHistoricParticipantToOrganizationOneToOne |
python | networkx__networkx | networkx/classes/reportviews.py | {
"start": 28848,
"end": 31634
} | class ____(OutEdgeDataView):
"""An EdgeDataView for outward edges of MultiDiGraph; See EdgeDataView"""
__slots__ = ("keys",)
def __getstate__(self):
return {
"viewer": self._viewer,
"nbunch": self._nbunch,
"keys": self.keys,
"data": self._data,
... | OutMultiEdgeDataView |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 60422,
"end": 60569
} | class ____(_PrintableStructure):
_fields_ = [
('type', _nvmlBridgeChipType_t),
('fwVersion', c_uint),
]
| c_nvmlBridgeChipInfo_t |
python | simonw__datasette | datasette/utils/__init__.py | {
"start": 29327,
"end": 30839
} | class ____:
def __init__(self, data):
# data is a dictionary of key => [list, of, values] or a list of [["key", "value"]] pairs
if isinstance(data, dict):
for key in data:
assert isinstance(
data[key], (list, tuple)
), "dictionary data ... | MultiParams |
python | getsentry__sentry | src/sentry/api/serializers/models/project.py | {
"start": 35235,
"end": 36610
} | class ____(ProjectWithTeamResponseDict):
latestRelease: LatestReleaseDict | None
options: dict[str, Any]
digestsMinDelay: int
digestsMaxDelay: int
subjectPrefix: str
allowedDomains: list[str]
resolveAge: int
dataScrubber: bool
dataScrubberDefaults: bool
safeFields: list[str]
... | DetailedProjectResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-surveymonkey/source_surveymonkey/components.py | {
"start": 364,
"end": 2164
} | class ____(SubstreamPartitionRouter):
"""
A SurveyIdPartitionRouter is specifically tailored for survey data, addressing the limitations of the current solution,
SubstreamPartitionRouter, which only offers one option for partitioning via access to the parent stream with input.
The SurveyIdPartitionRoute... | SurveyIdPartitionRouter |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/protocol.py | {
"start": 255,
"end": 430
} | class ____(typing.TypedDict):
id: str
name: str
last_activity: str
execution_state: str
connections: int
connection_info: KernelConnectionInfo
| KernelInfo |
python | PyCQA__pylint | tests/checkers/unittest_design.py | {
"start": 351,
"end": 1844
} | class ____(CheckerTestCase):
CHECKER_CLASS = design_analysis.MisdesignChecker
@set_config(
ignored_parents=(".Dddd",),
max_parents=1,
)
def test_too_many_ancestors_ignored_parents_are_skipped(self) -> None:
"""Make sure that classes listed in ``ignored-parents`` aren't counted
... | TestDesignChecker |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 31764,
"end": 33532
} | class ____(Sam3PreTrainedModel):
def __init__(self, config: Sam3ViTConfig):
super().__init__(config)
self.config = config
self.embeddings = Sam3ViTEmbeddings(config)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.layers = nn.ModuleList(
... | Sam3ViTModel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchSequence2.py | {
"start": 779,
"end": 2425
} | class ____:
pass
type UA = (
A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16
)
type UB = (
B1 | B2 | B3 | B4 | B5 | B6 | B7 | B8 | B9 | B10 | B11 | B12 | B13 | B14 | B15 | B16
)
def test(a: UA, b: UB) -> bool:
t = a, b
match t:
case A1(), B1():
... | B16 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 23295,
"end": 24514
} | class ____(RecordTransformation):
"""
A record transformation that flattens the `associations` field in HubSpot records.
This transformation takes a nested dictionary under the `associations` key and extracts the IDs
of associated objects. The extracted lists of IDs are added as new top-level fields in ... | HubspotFlattenAssociationsTransformation |
python | apache__airflow | airflow-core/tests/unit/jobs/test_triggerer_job.py | {
"start": 10458,
"end": 25098
} | class ____:
def test_run_inline_trigger_canceled(self, session) -> None:
trigger_runner = TriggerRunner()
trigger_runner.triggers = {
1: {"task": MagicMock(spec=asyncio.Task), "name": "mock_name", "events": 0}
}
mock_trigger = MagicMock(spec=BaseTrigger)
mock_trig... | TestTriggerRunner |
python | crytic__slither | slither/tools/upgradeability/checks/initialization.py | {
"start": 1483,
"end": 2607
} | class ____(AbstractCheck):
ARGUMENT = "init-missing"
IMPACT = CheckClassification.INFORMATIONAL
HELP = "Initializable is missing"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#initializable-is-missing"
WIKI_TITLE = "Initializable is missing"
# region wiki_description
... | InitializablePresent |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws_tests/pipes_tests/fake_lambda.py | {
"start": 1806,
"end": 4720
} | class ____:
def invoke(self, **kwargs):
# emulate lambda constraints with a subprocess invocation
# * json serialized "Payload" result
# * 4k log output as base64 "LogResult"
with tempfile.TemporaryDirectory() as tempdir:
in_path = os.path.join(tempdir, "in.json")
... | FakeLambdaClient |
python | great-expectations__great_expectations | great_expectations/validator/validator.py | {
"start": 2816,
"end": 4597
} | class ____:
# Note: Dependent "metric_name" (key) is different from "metric_name" in dependency "MetricConfiguration" (value). # noqa: E501 # FIXME CoP
metric_configurations: Dict[str, MetricConfiguration] = field(default_factory=dict)
result_format: Dict[str, Any] = field(default_factory=dict)
def se... | ValidationDependencies |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 16355,
"end": 16990
} | class ____(NamedTuple):
"""Field that can be configured by the user with a default value."""
id: str
"""The unique identifier of the field."""
options: Mapping[str, Any]
"""The options for the field."""
default: str
"""The default value for the field."""
name: str | None = None
"""T... | ConfigurableFieldSingleOption |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/projection_queries/snippets.py | {
"start": 615,
"end": 1037
} | class ____(ndb.Model):
title = ndb.StringProperty()
author = ndb.StringProperty()
tags = ndb.StringProperty(repeated=True)
def print_author_tags():
query = Article.query()
articles = query.fetch(20, projection=[Article.author, Article.tags])
for article in articles:
print(article.autho... | Article |
python | ethereum__web3.py | web3/providers/persistent/async_ipc.py | {
"start": 873,
"end": 4998
} | class ____(PersistentConnectionProvider):
logger = logging.getLogger("web3.providers.AsyncIPCProvider")
_reader: asyncio.StreamReader | None = None
_writer: asyncio.StreamWriter | None = None
_decoder: json.JSONDecoder = json.JSONDecoder()
def __init__(
self,
ipc_path: str | Path |... | AsyncIPCProvider |
python | huggingface__transformers | src/transformers/models/zamba2/modular_zamba2.py | {
"start": 52961,
"end": 53015
} | class ____(ZambaForCausalLM):
pass
| Zamba2ForCausalLM |
python | Farama-Foundation__Gymnasium | gymnasium/envs/phys2d/cartpole.py | {
"start": 703,
"end": 1233
} | class ____:
"""Parameters for the jax CartPole environment."""
gravity: float = 9.8
masscart: float = 1.0
masspole: float = 0.1
total_mass: float = masspole + masscart
length: float = 0.5
polemass_length: float = masspole + length
force_mag: float = 10.0
tau: float = 0.02
theta_... | CartPoleParams |
python | huggingface__transformers | src/transformers/models/imagegpt/modeling_imagegpt.py | {
"start": 12849,
"end": 16038
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
hidden_size = config.hidden_size
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
self.ln_1 = ImageGPTLayerNorm(hidden_size, eps=config.layer_norm_epsi... | ImageGPTBlock |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_decorators_3.py | {
"start": 366,
"end": 480
} | class ____:
x: UUID
@validate_call(config={'arbitrary_types_allowed': True})
def test(user: Sequence):
...
| C |
python | ray-project__ray | doc/source/ray-overview/examples/mcp-ray-serve/multi_mcp_ray_serve.py | {
"start": 791,
"end": 3515
} | class ____:
_PODMAN_ARGS: List[str] = []
_ENV: Dict[str, str] = {}
def __init__(self):
self._ready = asyncio.create_task(self._startup())
async def _startup(self):
params = StdioServerParameters(
command="podman",
args=self._PODMAN_ARGS,
env=self._EN... | _BaseMCP |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/gpu_test.py | {
"start": 1255,
"end": 2793
} | class ____(
data_service_test_base.TestBase,
parameterized.TestCase,
):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
pinned=[False, True],
data_transfer_protocol=["grpc", "local"],
... | TfDataServiceGpuTest |
python | pytorch__pytorch | tools/linter/adapters/nativefunctions_linter.py | {
"start": 1268,
"end": 3641
} | class ____(NamedTuple):
path: str | None
line: int | None
char: int | None
code: str
severity: LintSeverity
name: str
original: str | None
replacement: str | None
description: str | None
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="native fu... | LintMessage |
python | jazzband__tablib | src/tablib/formats/_dbf.py | {
"start": 157,
"end": 1918
} | class ____:
title = 'dbf'
extensions = ('csv',)
DEFAULT_ENCODING = 'utf-8'
@classmethod
def export_set(cls, dataset):
"""Returns DBF representation of a Dataset"""
new_dbf = dbfnew.dbf_new()
temp_file, temp_uri = tempfile.mkstemp()
# create the appropriate fields b... | DBFFormat |
python | FactoryBoy__factory_boy | tests/djapp/models.py | {
"start": 341,
"end": 491
} | class ____(models.Model):
foo = models.CharField(max_length=20, primary_key=True)
bar = models.CharField(max_length=20, blank=True)
| NonIntegerPk |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/block.py | {
"start": 2260,
"end": 2344
} | class ____(_ImageBlockNotRequired):
type: Literal["Image"]
url: str
| ImageBlock |
python | wandb__wandb | wandb/vendor/pygments/lexers/css.py | {
"start": 31076,
"end": 31513
} | class ____(CssLexer):
"""
For `LESS <http://lesscss.org/>`_ styleshets.
.. versionadded:: 2.1
"""
name = 'LessCss'
aliases = ['less']
filenames = ['*.less']
mimetypes = ['text/x-less-css']
tokens = {
'root': [
(r'@\w+', Name.Variable),
inherit,
... | LessCssLexer |
python | falconry__falcon | tests/test_utils.py | {
"start": 2255,
"end": 2737
} | class ____(media.URLEncodedFormHandler):
def __init__(self):
super().__init__()
self.deserialize_count = 0
def deserialize(self, *args, **kwargs):
result = super().deserialize(*args, **kwargs)
self.deserialize_count += 1
return result
async def deserialize_async(sel... | TrackingFormHandler |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 83040,
"end": 84321
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("auto_ml.AutoMLHook"))
def test_execute(self, mock_hook):
page_token = "page_token"
page_size = 42
filter = "filter"
read_mask = "read_mask"
op = ListAutoMLTrainingJobOperator(
task_id=TASK_ID,
gcp_con... | TestVertexAIListAutoMLTrainingJobOperator |
python | pytorch__pytorch | functorch/dim/__init__.py | {
"start": 45215,
"end": 53308
} | class ____:
"""
Helper class for organizing dimensions in dot products.
"""
def __init__(self) -> None:
self.dims: list[DimEntry] = []
self.total_size = 1
def append(self, dim_entry: Any) -> None:
"""Add a dimension entry to this part."""
self.dims.append(dim_entry)... | DotPart |
python | django__django | django/contrib/sessions/models.py | {
"start": 91,
"end": 164
} | class ____(BaseSessionManager):
use_in_migrations = True
| SessionManager |
python | redis__redis-py | redis/asyncio/multidb/healthcheck.py | {
"start": 768,
"end": 1325
} | class ____(ABC):
"""
Health checks execution policy.
"""
@property
@abstractmethod
def health_check_probes(self) -> int:
"""Number of probes to execute health checks."""
pass
@property
@abstractmethod
def health_check_delay(self) -> float:
"""Delay between h... | HealthCheckPolicy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.