language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | doocs__leetcode | solution/2000-2099/2096.Step-By-Step Directions From a Binary Tree Node to Another/Solution2.py | {
"start": 194,
"end": 1146
} | class ____:
def getDirections(
self, root: Optional[TreeNode], startValue: int, destValue: int
) -> str:
def dfs(node: Optional[TreeNode], x: int, path: List[str]):
if node is None:
return False
if node.val == x:
return True
pat... | Solution |
python | apache__airflow | airflow-core/tests/unit/utils/test_log_handlers.py | {
"start": 32158,
"end": 59090
} | class ____:
def test_log_retrieval_valid(self, create_task_instance):
log_url_ti = create_task_instance(
dag_id="dag_for_testing_filename_rendering",
task_id="task_for_testing_filename_rendering",
run_type=DagRunType.SCHEDULED,
logical_date=DEFAULT_DATE,
... | TestLogUrl |
python | scrapy__scrapy | tests/test_feedexport.py | {
"start": 8004,
"end": 9111
} | class ____:
def get_test_spider(self, settings=None):
class TestSpider(scrapy.Spider):
name = "test_spider"
crawler = get_crawler(settings_dict=settings)
return TestSpider.from_crawler(crawler)
def test_default_temp_dir(self):
b = MyBlockingFeedStorage()
st... | TestBlockingFeedStorage |
python | doocs__leetcode | solution/0700-0799/0745.Prefix and Suffix Search/Solution2.py | {
"start": 0,
"end": 614
} | class ____:
def __init__(self):
self.children = [None] * 26
self.indexes = []
def insert(self, word, i):
node = self
for c in word:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.... | Trie |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 22934,
"end": 23214
} | class ____(NotFoundError):
"""
Blas (http://www.netlib.org/blas/) libraries not found.
Directories to search for the libraries can be specified in the
numpy/distutils/site.cfg file (section [blas]) or by setting
the BLAS environment variable."""
| BlasNotFoundError |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 49641,
"end": 51310
} | class ____(Request):
"""
Delete metadata from model
:param model: ID of the model
:type model: str
:param keys: The list of metadata keys to delete
:type keys: Sequence[str]
"""
_service = "models"
_action = "delete_metadata"
_version = "2.23"
_schema = {
"definitio... | DeleteMetadataRequest |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/binary_inplace_test.py | {
"start": 2657,
"end": 3303
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype_one, dtype_two, op_func):
self.inputs = {
"input_one": torch.randn(M, N, K, device=device).to(dtype=dtype_one),
"input_two": torch.randn(M, N, K, device=device).to(dtype=dtype_two),
}
self.... | InpBinaryOpBenchmark |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 41428,
"end": 93053
} | class ____:
def __init__(self, total: int):
self.n = 0
self.total = total
self.running = False
self.enable = sys.stdout.isatty()
self.pretty_spec: str = ""
self.pre = ""
def _clear(self):
if self.enable and self.running:
sys.stdout.write("\033... | FancyProgress |
python | fsspec__filesystem_spec | fsspec/callbacks.py | {
"start": 5697,
"end": 5860
} | class ____(Callback):
"""
This implementation of Callback does exactly nothing
"""
def call(self, *args, **kwargs):
return None
| NoOpCallback |
python | PrefectHQ__prefect | src/integrations/prefect-redis/prefect_redis/client.py | {
"start": 301,
"end": 3814
} | class ____(PrefectBaseSettings):
model_config = build_settings_config(
(
"redis",
"messaging",
),
frozen=True,
)
host: str = Field(default="localhost")
port: int = Field(default=6379)
db: int = Field(default=0)
username: str = Field(default="defau... | RedisMessagingSettings |
python | joke2k__faker | faker/providers/color/de_CH/__init__.py | {
"start": 123,
"end": 336
} | class ____(BaseProvider):
all_colors: OrderedDictType[str, str] = OrderedDict(
(color_name.replace("ß", "ss"), color_hexcode) for color_name, color_hexcode in BaseProvider.all_colors.items()
)
| Provider |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/conv3d_transpose_test.py | {
"start": 1139,
"end": 9588
} | class ____(test.TestCase):
def testConv3DTransposeSingleStride(self):
with self.cached_session():
strides = [1, 1, 1, 1, 1]
# Input, output: [batch, depth, height, width, channel]
x_shape = [2, 5, 6, 4, 3]
y_shape = [2, 5, 6, 4, 2]
# Filter: [kernel_depth, kernel_height, kernel_wi... | Conv3DTransposeTest |
python | facebookresearch__faiss | contrib/torch/quantization.py | {
"start": 388,
"end": 999
} | class ____:
def __init__(self, d, code_size):
"""
d: dimension of vectors
code_size: nb of bytes of the code (per vector)
"""
self.d = d
self.code_size = code_size
def train(self, x):
"""
takes a n-by-d array and performs training
"""
... | Quantizer |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 60739,
"end": 64085
} | class ____(SensitivitySpecificityBase):
"""Computes best specificity where sensitivity is >= specified value.
`Sensitivity` measures the proportion of actual positives that are correctly
identified as such (tp / (tp + fn)).
`Specificity` measures the proportion of actual negatives that are correctly
identifi... | SpecificityAtSensitivity |
python | doocs__leetcode | solution/0700-0799/0731.My Calendar II/Solution2.py | {
"start": 215,
"end": 1673
} | class ____:
def __init__(self):
self.root = Node(1, 10**9 + 1)
def modify(self, l: int, r: int, v: int, node: Node = None):
if l > r:
return
if node is None:
node = self.root
if node.l >= l and node.r <= r:
node.v += v
node.add += ... | SegmentTree |
python | apache__airflow | airflow-core/tests/unit/always/test_secrets_local_filesystem.py | {
"start": 17094,
"end": 18612
} | class ____:
def test_should_read_variable(self, tmp_path):
path = tmp_path / "testfile.var.env"
path.write_text("KEY_A=VAL_A")
backend = LocalFilesystemBackend(variables_file_path=os.fspath(path))
assert backend.get_variable("KEY_A") == "VAL_A"
assert backend.get_variable("KE... | TestLocalFileBackend |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 17460,
"end": 18469
} | class ____(Literal):
"""All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` is true).
"""
field... | Const |
python | mlflow__mlflow | tests/genai/judges/optimizers/test_dspy_base.py | {
"start": 1308,
"end": 16648
} | class ____(DSPyAlignmentOptimizer):
"""Concrete implementation for testing."""
def _dspy_optimize(
self,
program: "dspy.Module",
examples: Collection["dspy.Example"],
metric_fn: Callable[["dspy.Example", Any, Any | None], bool],
) -> "dspy.Module":
mock_program = Moc... | ConcreteDSPyOptimizer |
python | python-openxml__python-docx | src/docx/oxml/xmlchemy.py | {
"start": 19445,
"end": 21041
} | class ____(_BaseChildElement):
"""Defines an optional child element for MetaOxmlElement."""
def populate_class_members(self, element_cls: MetaOxmlElement, prop_name: str) -> None:
"""Add the appropriate methods to `element_cls`."""
super(ZeroOrOne, self).populate_class_members(element_cls, prop... | ZeroOrOne |
python | pytorch__pytorch | torch/nn/utils/_expanded_weights/group_norm_expanded_weights.py | {
"start": 393,
"end": 3576
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
expanded_args, expanded_kwargs = standard_kwargs(
kwarg_names, expanded_args_and_kwargs
)
input, num_groups = expanded_args
... | GroupNormPerSampleGrad |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 3589,
"end": 6181
} | class ____:
scenarii: list[tuple[str, str, bytes | None]] = [
# TLS to TLS: send non-empty referrer
(
"https://example.com/page.html",
"https://not.example.com/",
b"https://example.com/page.html",
),
(
"https://example.com/page.html",
... | MixinNoReferrerWhenDowngrade |
python | coleifer__peewee | peewee.py | {
"start": 97867,
"end": 98006
} | class ____(object):
__slots__ = ()
def __enter__(self): return self
def __exit__(self, exc_type, exc_val, exc_tb): pass
| _NoopLock |
python | great-expectations__great_expectations | great_expectations/render/renderer/content_block/bullet_list_content_block.py | {
"start": 217,
"end": 568
} | class ____(ExpectationStringRenderer):
_rendered_component_type = RenderedBulletListContent
_content_block_type = "bullet_list"
_default_element_styling = {
"default": {"classes": ["badge", "badge-secondary"]},
"params": {"column": {"classes": ["badge", "badge-primary"]}},
}
| ExpectationSuiteBulletListContentBlockRenderer |
python | networkx__networkx | networkx/classes/coreviews.py | {
"start": 6897,
"end": 7530
} | class ____(UnionAdjacency):
"""A read-only union of two dict MultiAdjacencies.
The two input dict-of-dict-of-dict-of-dicts represent the union of
`G.succ` and `G.pred` for MultiDiGraphs. Return values are UnionAdjacency.
The inner level of dict is read-write. But the outer levels are read-only.
Se... | UnionMultiAdjacency |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 24003,
"end": 24133
} | class ____(MixinNoReferrer, TestRefererMiddleware):
req_meta = {"referrer_policy": POLICY_NO_REFERRER}
| TestRequestMetaNoReferrer |
python | encode__django-rest-framework | rest_framework/schemas/coreapi.py | {
"start": 20010,
"end": 21400
} | class ____(ViewInspector):
"""
Allows providing a list of coreapi.Fields,
plus an optional description.
"""
def __init__(self, fields, description='', encoding=None):
"""
Parameters:
* `fields`: list of `coreapi.Field` instances.
* `description`: String description f... | ManualSchema |
python | pytorch__pytorch | test/inductor/test_remote_cache.py | {
"start": 247,
"end": 428
} | class ____(RemoteCacheBackend):
def _get(self, key):
raise AssertionError("testget")
def _put(self, key, data):
raise AssertionError("testput")
| FailingBackend |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 203030,
"end": 203128
} | class ____(
_NumMultiRangeTests, _MultiRangeTypeRoundTrip
):
pass
| NumMultiRangeRoundTripTest |
python | huggingface__transformers | src/transformers/models/mgp_str/modeling_mgp_str.py | {
"start": 11759,
"end": 12578
} | class ____(PreTrainedModel):
config: MgpstrConfig
base_model_prefix = "mgp_str"
_no_split_modules = []
@torch.no_grad()
def _init_weights(self, module: nn.Module) -> None:
"""Initialize the weights"""
std = self.config.initializer_range
if isinstance(module, MgpstrEmbeddings... | MgpstrPreTrainedModel |
python | pennersr__django-allauth | allauth/headless/mfa/views.py | {
"start": 9763,
"end": 10117
} | class ____(AuthenticationStageAPIView):
input_class = TrustInput
stage_class = TrustStage
def post(self, request, *args, **kwargs):
trust = self.input.cleaned_data["trust"]
response = self.respond_next_stage()
if trust:
trust_browser(request, self.stage.login.user, respo... | TrustView |
python | getsentry__sentry | src/sentry/core/endpoints/organization_member_invite/index.py | {
"start": 1723,
"end": 2097
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["member:read", "member:write", "member:admin"],
# We will do an additional check to see if a user can invite members. If
# not, then POST creates an invite request, not an invite.
"POST": ["member:read", "member:write", "membe... | MemberInvitePermission |
python | numpy__numpy | numpy/_core/defchararray.py | {
"start": 10811,
"end": 37817
} | class ____(ndarray):
"""
chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
strides=None, order=None)
Provides a convenient view on arrays of string and unicode values.
.. note::
The `chararray` class exists for backwards compatibility with
Numarray, it is n... | chararray |
python | django__django | django/db/models/lookups.py | {
"start": 12919,
"end": 13373
} | class ____(Lookup):
"""Lookup defined by operators on PostgreSQL."""
postgres_operator = None
def as_postgresql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = tuple(lhs_params) ... | PostgresOperatorLookup |
python | huggingface__transformers | src/transformers/modeling_layers.py | {
"start": 1089,
"end": 3814
} | class ____(nn.Module):
"""Base class for layers with gradient checkpointing.
This class enables gradient checkpointing functionality for a layer. By default, gradient checkpointing is disabled
(`gradient_checkpointing = False`). When `model.set_gradient_checkpointing()` is called, gradient checkpointing is... | GradientCheckpointingLayer |
python | google__jax | tests/pallas/pallas_jumble_test.py | {
"start": 1792,
"end": 2508
} | class ____(jtu.JaxTestCase):
INTERPRET = False
def setUp(self):
if jtu.test_device_matches(["cpu"]) and not self.INTERPRET:
self.skipTest("On CPU the test works only in interpret mode")
if jtu.test_device_matches(
["cuda"]
) and not jtu.is_cuda_compute_capability_at_least("8.0"):
se... | PallasBaseTest |
python | plotly__plotly.py | plotly/graph_objs/icicle/_textfont.py | {
"start": 233,
"end": 17114
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.textfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizes... | Textfont |
python | ray-project__ray | python/ray/_private/accelerators/accelerator.py | {
"start": 740,
"end": 5743
} | class ____(ABC):
"""This class contains all the functions needed for supporting
an accelerator family in Ray."""
@staticmethod
@abstractmethod
def get_resource_name() -> str:
"""Get the name of the resource representing this accelerator family.
Returns:
The resource nam... | AcceleratorManager |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 8819,
"end": 8856
} | class ____(Terminator):
pass
| Branch |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIn1.py | {
"start": 3322,
"end": 3806
} | class ____(TypedDict):
y: str
T1 = TypeVar("T1", TD1, TD2)
def func12(v: T1):
if "x" in v:
# This should technically be TD1* | TD2*, but the
# current narrowing logic implements a not-entirely-safe
# narrowing behavior. We can fix this once PEP 728
# is accepted.
reve... | TD2 |
python | geekcomputers__Python | Word_Dictionary/dictionary.py | {
"start": 32,
"end": 1606
} | class ____:
def __init__(self):
self.node = {}
def add_word(self, word: str) -> None:
node = self.node
for ltr in word:
if ltr not in node:
node[ltr] = {}
node = node[ltr]
node["is_word"] = True
def word_exists(self, word: str) -> boo... | Dictionary |
python | redis__redis-py | redis/sentinel.py | {
"start": 2715,
"end": 2804
} | class ____(SentinelManagedConnection, SSLConnection):
pass
| SentinelManagedSSLConnection |
python | pytorch__pytorch | test/distributed/test_c10d_gloo.py | {
"start": 60484,
"end": 85730
} | class ____(
test_c10d_common.CommonDistributedDataParallelTest, MultiProcessTestCase
):
def setUp(self):
super().setUp()
self._spawn_processes()
def _get_process_group(self):
store = self._get_store()
c10d.init_process_group(
backend="gloo", store=store, rank=sel... | DistributedDataParallelTest |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 26370,
"end": 26475
} | class ____(TestModel):
key = TextField()
value = IntegerField()
misc = TextField(null=True)
| MMC |
python | numba__llvmlite | llvmlite/binding/newpassmanagers.py | {
"start": 3541,
"end": 12993
} | class ____():
def __init__(self):
if type(self) is NewPassManager:
raise TypeError("Cannot instantiate NewPassManager directly")
def run(self,IR, pb):
if isinstance(self, ModulePassManager):
ffi.lib.LLVMPY_RunNewModulePassManager(self, IR, pb)
else:
... | NewPassManager |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 14509,
"end": 15160
} | class ____(GroupType):
"""
This group type is only used for fingerprinting MN+1 DB Performance Issues.
No field other than `type_id` are referenced, so changes will not have an affect.
The MN+1 detector uses the PerformanceNPlusOneGroupType, so reference that GroupType instead.
"""
type_id = 10... | PerformanceMNPlusOneDBQueriesGroupType |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 66044,
"end": 71564
} | class ____(test.TestCase):
def _test(self, input_shape, dtype, **kwargs):
# Use negative numbers to make sure there isn't any zero padding getting
# used.
x = -np.arange(np.prod(input_shape), dtype=dtype).reshape(input_shape) - 1
y1 = pool_direct(input=x, **kwargs)
y2 = nn_ops.pool(input=x, **kwa... | PoolingTest |
python | walkccc__LeetCode | solutions/3199. Count Triplets with Even XOR Set Bits I/3199.py | {
"start": 0,
"end": 650
} | class ____:
def tripletCount(self, a: list[int], b: list[int], c: list[int]) -> int:
evenA, oddA = self._getEvenOddBitCount(a)
evenB, oddB = self._getEvenOddBitCount(b)
evenC, oddC = self._getEvenOddBitCount(c)
return evenA * oddB * oddC + oddA * evenB * oddC + oddA * oddB * evenC + evenA * evenB * ev... | Solution |
python | ansible__ansible | lib/ansible/utils/version.py | {
"start": 3107,
"end": 7736
} | class ____(Version):
"""Version comparison class that implements Semantic Versioning 2.0.0
Based off of ``distutils.version.Version``
"""
version_re = SEMVER_RE
def __init__(self, vstring=None):
self.vstring = vstring
self.major = None
self.minor = None
self.patch ... | SemanticVersion |
python | python__mypy | mypy/message_registry.py | {
"start": 569,
"end": 17200
} | class ____(NamedTuple):
value: str
code: ErrorCode | None = None
def format(self, *args: object, **kwargs: object) -> ErrorMessage:
return ErrorMessage(self.value.format(*args, **kwargs), code=self.code)
def with_additional_msg(self, info: str) -> ErrorMessage:
return ErrorMessage(self... | ErrorMessage |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/batch_test.py | {
"start": 14370,
"end": 17813
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 2, 3, 4])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, ... | BatchRandomAccessTest |
python | etianen__django-reversion | tests/test_app/tests/test_admin.py | {
"start": 10461,
"end": 10541
} | class ____(admin.TabularInline):
model = TestModelInline
| TestModelInlineAdmin |
python | streamlit__streamlit | lib/tests/streamlit/elements/button_group_test.py | {
"start": 5671,
"end": 7348
} | class ____:
@parameterized.expand([("single",), ("multi",)])
def test_serialize(self, selection_mode: SelectionMode):
option_indices = [5, 6, 7]
serde = ButtonGroupSerde[int](option_indices, [], selection_mode)
res = serde.serialize(6)
assert res == [1]
@parameterized.expand... | TestSingleOrMultiSelectSerde |
python | tornadoweb__tornado | tornado/test/runtests.py | {
"start": 3475,
"end": 7459
} | class ____(io.IOBase):
def __init__(self, real):
self.real = real
self.byte_count = 0
def write(self, data):
self.byte_count += len(data)
return self.real.write(data)
def flush(self):
return self.real.flush()
def main():
# Be strict about most warnings (This i... | CountingStderr |
python | PyCQA__pylint | tests/functional/m/match_class_pattern.py | {
"start": 360,
"end": 435
} | class ____:
__match_args__ = ("x", 1) # [invalid-match-args-definition]
| D |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_subset.py | {
"start": 2222,
"end": 18485
} | class ____(NamedTuple):
partitions_subsets_by_asset_key: Mapping[AssetKey, PartitionsSubset] = {}
non_partitioned_asset_keys: AbstractSet[AssetKey] = set()
@property
def asset_keys(self) -> AbstractSet[AssetKey]:
return {
key
for key, subset in self.partitions_subsets_by... | AssetGraphSubset |
python | crytic__slither | slither/core/solidity_types/user_defined_type.py | {
"start": 399,
"end": 3065
} | class ____(Type):
def __init__(self, t: Union["Enum", "Contract", "Structure"]) -> None:
from slither.core.declarations.structure import Structure
from slither.core.declarations.enum import Enum
from slither.core.declarations.contract import Contract
assert isinstance(t, (Contract, ... | UserDefinedType |
python | allegroai__clearml | clearml/utilities/process/mp.py | {
"start": 8088,
"end": 8747
} | class ____(object):
__thread_pool = None
__thread_pool_pid = None
@classmethod
def get(cls) -> ThreadCalls:
if os.getpid() != cls.__thread_pool_pid:
cls.__thread_pool = ThreadCalls()
cls.__thread_pool_pid = os.getpid()
return cls.__thread_pool
@classmethod
... | SingletonThreadPool |
python | kamyu104__LeetCode-Solutions | Python/handshakes-that-dont-cross.py | {
"start": 29,
"end": 641
} | class ____(object):
def numberOfWays(self, num_people):
"""
:type num_people: int
:rtype: int
"""
MOD = 10**9+7
def inv(x, m): # Euler's Theorem
return pow(x, m-2, m) # O(logMOD) = O(1)
def nCr(n, k, m):
if n-k < k:
r... | Solution |
python | ApeWorX__ape | src/ape_node/provider.py | {
"start": 14473,
"end": 15523
} | class ____(PluginConfig):
# Make sure you are running the right networks when you try for these
mainnet: dict = {}
holesky: dict = {}
sepolia: dict = {}
# Make sure to run via `geth --dev` (or similar)
local: dict = {**DEFAULT_SETTINGS.copy(), "chain_id": DEFAULT_TEST_CHAIN_ID, "block_time": 0}
... | EthereumNetworkConfig |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 305384,
"end": 307478
} | class ____(DataFormat):
"""
DsvDataFormat schema wrapper.
Parameters
----------
delimiter : str
The delimiter between records. The delimiter must be a single character (i.e., a
single 16-bit code unit); so, ASCII delimiters are fine, but emoji delimiters are
not.
parse :... | DsvDataFormat |
python | huggingface__transformers | src/transformers/pipelines/zero_shot_audio_classification.py | {
"start": 991,
"end": 6702
} | class ____(Pipeline):
"""
Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
provide an audio and a set of `candidate_labels`.
<Tip warning={true}>
The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update ... | ZeroShotAudioClassificationPipeline |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Robot_arm/DDPG.py | {
"start": 1488,
"end": 4403
} | class ____(object):
def __init__(self, sess, action_dim, action_bound, learning_rate, t_replace_iter):
self.sess = sess
self.a_dim = action_dim
self.action_bound = action_bound
self.lr = learning_rate
self.t_replace_iter = t_replace_iter
self.t_replace_counter = 0
... | Actor |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/bincount_op_test.py | {
"start": 7991,
"end": 14643
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.parameters([{
"dtype": np.int32,
}, {
"dtype": np.int64,
}])
def test_bincount_all_count(self, dtype):
np.random.seed(42)
size = 1000
inp = np.random.randint(0, size, (4096), dtype=dtype)
np_out = np.bi... | BincountOpTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 60158,
"end": 60684
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def testConcatSlice(self):
r1 = test_ops.stub_resource_handle_op(container="a", shared_name="b")
r2 = test_ops.stub_resource_handle_op(container="a", shared_name="c")
c = array_ops_stack.stack([r1, r2])
s = array_ops.... | ConcatSliceResourceTest |
python | falconry__falcon | examples/recipes/output_csv_text_asgi.py | {
"start": 38,
"end": 444
} | class ____:
async def on_get(self, req, resp):
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(('fruit', 'quantity'))
writer.writerow(('apples', 13))
writer.writerow(('oranges', 37))
resp.content_type = falcon.MEDIA_CS... | Report |
python | doocs__leetcode | lcof2/剑指 Offer II 007. 数组中和为 0 的三个数/Solution.py | {
"start": 0,
"end": 822
} | class ____:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
ans = []
for i in range(n - 2):
if nums[i] > 0:
break
if i and nums[i] == nums[i - 1]:
continue
j, k = i + 1, n - 1
... | Solution |
python | scrapy__scrapy | tests/test_http2_client_protocol.py | {
"start": 5970,
"end": 26894
} | class ____:
scheme = "https"
host = "localhost"
key_file = Path(__file__).parent / "keys" / "localhost.key"
certificate_file = Path(__file__).parent / "keys" / "localhost.crt"
@pytest.fixture
def site(self, tmp_path):
r = File(str(tmp_path))
r.putChild(b"get-data-html-small", Ge... | TestHttps2ClientProtocol |
python | getsentry__sentry | src/sentry/integrations/github/webhook.py | {
"start": 27296,
"end": 31323
} | class ____(GitHubWebhook):
"""https://developer.github.com/v3/activity/events/types/#pullrequestevent"""
@property
def event_type(self) -> IntegrationWebhookEventType:
return IntegrationWebhookEventType.PULL_REQUEST
def _handle(
self,
integration: RpcIntegration,
event:... | PullRequestEventWebhook |
python | astropy__astropy | astropy/coordinates/transformations/affine.py | {
"start": 553,
"end": 9181
} | class ____(CoordinateTransform):
"""Base class for common functionality between the ``AffineTransform``-type
subclasses.
This base class is needed because `~astropy.coordinates.AffineTransform`
and the matrix transform classes share the ``__call__()`` method, but
differ in how they generate the aff... | BaseAffineTransform |
python | doocs__leetcode | lcof2/剑指 Offer II 055. 二叉搜索树迭代器/Solution2.py | {
"start": 192,
"end": 763
} | class ____:
def __init__(self, root: TreeNode):
self.stack = []
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
cur = self.stack.pop()
node = cur.right
while node:
self.stack.append(node)
node = ... | BSTIterator |
python | tornadoweb__tornado | tornado/test/netutil_test.py | {
"start": 3988,
"end": 5331
} | class ____(unittest.TestCase):
def test_import(self):
TIMEOUT = 5
# Test for a deadlock when importing a module that runs the
# ThreadedResolver at import-time. See resolve_test.py for
# full explanation.
command = [sys.executable, "-c", "import tornado.test.resolve_test_hel... | ThreadedResolverImportTest |
python | mlflow__mlflow | mlflow/entities/trace_location.py | {
"start": 425,
"end": 716
} | class ____(_MlflowObject, ABC):
"""
Base class for trace location classes.
"""
@abstractmethod
def to_dict(self) -> dict[str, Any]: ...
@classmethod
@abstractmethod
def from_dict(cls, d: dict[str, Any]) -> "TraceLocationBase": ...
@dataclass
| TraceLocationBase |
python | wandb__wandb | landfill/functional_tests/prodigy/prodigy_connect.py | {
"start": 151,
"end": 425
} | class ____:
def get_dataset(self, dataset):
# load sample dataset in JSON format
file_name = dataset + ".json"
with open("prodigy_test_resources/" + file_name) as f:
data = json.load(f)
return data
return []
| Database |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 9607,
"end": 10167
} | class ____:
def test_key_size(self):
cipher = SEED(b"\x00" * 16)
assert cipher.key_size == 128
def test_invalid_key_size(self):
with pytest.raises(ValueError):
SEED(b"\x00" * 17)
def test_invalid_key_type(self):
with pytest.raises(TypeError, match="key must be b... | TestSEED |
python | kamyu104__LeetCode-Solutions | Python/checking-existence-of-edge-length-limited-paths-ii.py | {
"start": 4275,
"end": 5133
} | class ____(object):
def __init__(self, length):
"""
:type length: int
"""
self.__snaps = collections.defaultdict(lambda:sortedcontainers.SortedList([(0, 0)]))
def set(self, index, val, snap_id):
"""
:type index: int
:type val: int
:rtype: None
... | SnapshotArray |
python | huggingface__transformers | src/transformers/models/segformer/modeling_segformer.py | {
"start": 24927,
"end": 29001
} | class ____(SegformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.segformer = SegformerModel(config)
self.decode_head = SegformerDecodeHead(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def for... | SegformerForSemanticSegmentation |
python | pytorch__pytorch | test/ao/sparsity/test_data_scheduler.py | {
"start": 836,
"end": 6722
} | class ____(TestCase):
def _get_data(self):
tensor1, param1, emb1 = (
torch.randn(5, 5),
nn.Parameter(torch.randn(10, 10)),
nn.Embedding(50, 5),
)
data_list = [("tensor1", tensor1), ("param1", param1), ("emb1", emb1)]
defaults = {
"spars... | TestBaseDataScheduler |
python | pypa__setuptools | setuptools/_distutils/dist.py | {
"start": 2143,
"end": 46563
} | class ____:
"""The core of the Distutils. Most of the work hiding behind 'setup'
is really done within a Distribution instance, which farms the work out
to the Distutils commands specified on the command line.
Setup scripts will almost never instantiate Distribution directly,
unless the 'setup()' ... | Distribution |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 1941,
"end": 3482
} | class ____:
def test_manage_account(self, monkeypatch):
user_service = pretend.stub()
name = pretend.stub()
request = pretend.stub(
find_service=lambda *a, **kw: user_service,
user=pretend.stub(name=name, has_primary_verified_email=False),
help_url=pretend... | TestManageUnverifiedAccount |
python | mlflow__mlflow | mlflow/tracing/otel/translation/base.py | {
"start": 314,
"end": 5188
} | class ____:
"""
Base class for OTEL schema translators.
Each OTEL semantic convention (OpenInference, Traceloop, GenAI, etc.)
should extend this class and override class attributes if needed.
"""
SPAN_KIND_ATTRIBUTE_KEY: str | None = None
SPAN_KIND_TO_MLFLOW_TYPE: dict[str, str] | None = N... | OtelSchemaTranslator |
python | tensorflow__tensorflow | tensorflow/compiler/tests/fake_quant_ops_test.py | {
"start": 8627,
"end": 12759
} | class ____(xla_test.XLATestCase):
"""Test cases for FakeQuantWithMinMaxVars operation."""
# 8 bits, wide range.
def testOp_with8BitsNoScalingNoNudging(self):
self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0)
def testOp_with8BitsScalingAndNudgingDown(self):
self._TestOp(0.5, 128.0, 8, False, 0.0, 127... | FakeQuantWithMinMaxVarsTest |
python | scipy__scipy | scipy/sparse/linalg/_eigen/tests/test_svds.py | {
"start": 34449,
"end": 35858
} | class ____(SVDSCommonTests):
def setup_method(self):
self.solver = 'arpack'
@pytest.mark.parametrize("ncv", list(range(-1, 8)) + [4.5, "5"])
def test_svds_input_validation_ncv_1(self, ncv):
rng = np.random.default_rng(0)
A = rng.random((6, 7))
k = 3
if ncv in {4, 5}... | Test_SVDS_ARPACK |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/mapper.py | {
"start": 169199,
"end": 169957
} | class ____(Dict["ColumnElement[Any]", "MapperProperty[Any]"]):
"""Error reporting helper for mapper._columntoproperty."""
__slots__ = ("mapper",)
def __init__(self, mapper):
# TODO: weakref would be a good idea here
self.mapper = mapper
def __missing__(self, column):
prop = se... | _ColumnMapping |
python | pytorch__pytorch | test/functorch/test_vmap.py | {
"start": 231136,
"end": 237111
} | class ____(Namespace.TestVmapBase):
def _vmap_test(self, *args, **kwargs):
return _vmap_test(self, *args, **kwargs)
# dims should be something like [5, None, 10], with None indicating that a
# random ragged structure should be used
def _create_nt(self, dims, device):
sizes = [
... | TestVmapNestedTensor |
python | neetcode-gh__leetcode | python/0946-validate-stack-sequences.py | {
"start": 0,
"end": 315
} | class ____(object):
def validateStackSequences(self, pushed, popped):
i = 0
stack = []
for n in pushed:
stack.append(n)
while i < len(popped) and stack and popped[i] == stack[-1]:
stack.pop()
i += 1
return not stack
| Solution |
python | getsentry__sentry | src/sentry/seer/autofix/constants.py | {
"start": 597,
"end": 774
} | class ____(enum.StrEnum):
OFF = "off"
SUPER_LOW = "super_low"
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
ALWAYS = "always"
| AutofixAutomationTuningSettings |
python | django-extensions__django-extensions | tests/test_modificationdatetime_fields.py | {
"start": 227,
"end": 1160
} | class ____(TestCase):
def test_update_model_with_modification_field(self):
m = ModelModificationDateTimeField.objects.create()
current_updated_time = m.modified
m.field_to_update = False
m.save()
self.assertNotEqual(m.modified, current_updated_time)
def test_custom_modif... | ModificationDatetimeFieldTest |
python | TheAlgorithms__Python | data_structures/arrays/index_2d_array_in_1d.py | {
"start": 868,
"end": 3133
} | class ____:
matrix: list[list[int]]
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(Index2DArrayIterator([[5], [-523], [-1], [34], [0]]))
(5, -523, -1, 34, 0)
>>> tuple(Index2DArrayIterator([[5, -523, -1], [34, 0]]))
(5, -523, -1, 34, 0)
>>> tuple(Index2DArray... | Index2DArrayIterator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_comment03.py | {
"start": 315,
"end": 972
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("comment03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workboo... | TestCompareXLSXFiles |
python | kubernetes-client__python | kubernetes/client/api/apps_api.py | {
"start": 543,
"end": 5174
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | AppsApi |
python | ray-project__ray | python/ray/experimental/multiprocessing/pool.py | {
"start": 39,
"end": 107
} | class ____(multiprocessing.Pool):
pass # moved to util package
| Pool |
python | bottlepy__bottle | bottle.py | {
"start": 141949,
"end": 142180
} | class ____(ServerAdapter):
""" Fast server written in C: https://github.com/jonashaag/bjoern """
def run(self, handler):
from bjoern import run
run(handler, self.host, self.port, reuse_port=True)
| BjoernServer |
python | django-haystack__django-haystack | haystack/backends/elasticsearch5_backend.py | {
"start": 852,
"end": 16880
} | class ____(ElasticsearchSearchBackend):
def __init__(self, connection_alias, **connection_options):
super().__init__(connection_alias, **connection_options)
self.content_field_name = None
def clear(self, models=None, commit=True):
"""
Clears the backend of all documents/objects ... | Elasticsearch5SearchBackend |
python | langchain-ai__langchain | libs/langchain/langchain_classic/storage/file_system.py | {
"start": 221,
"end": 5764
} | class ____(ByteStore):
"""`BaseStore` interface that works on the local file system.
Examples:
Create a `LocalFileStore` instance and perform operations on it:
```python
from langchain_classic.storage import LocalFileStore
# Instantiate the LocalFileStore with the root path
... | LocalFileStore |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/menus.py | {
"start": 8389,
"end": 9690
} | class ____(ConditionalContainer):
# NOTE: We use a pretty big z_index by default. Menus are supposed to be
# above anything else. We also want to make sure that the content is
# visible at the point where we draw this menu.
def __init__(
self,
max_height: int | None = None,
... | CompletionsMenu |
python | getsentry__responses | responses/tests/test_responses.py | {
"start": 27451,
"end": 50096
} | class ____:
"""
Test that pytest fixtures work well with 'activate' decorator
"""
def test_function(self, my_fruit, fruit_basket):
assert my_fruit in fruit_basket
assert my_fruit == "apple"
test_function_decorated = responses.activate(test_function)
def test_activate_mock_interac... | TestFixtures |
python | django__django | django/contrib/auth/migrations/0002_alter_permission_name_max_length.py | {
"start": 43,
"end": 346
} | class ____(migrations.Migration):
dependencies = [
("auth", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="permission",
name="name",
field=models.CharField(max_length=255, verbose_name="name"),
),
]
| Migration |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/savedsearch.py | {
"start": 261,
"end": 614
} | class ____(serializers.Serializer):
type = serializers.IntegerField(required=True)
name = serializers.CharField(required=True)
query = serializers.CharField(required=True, min_length=1)
sort = serializers.ChoiceField(
choices=SortOptions.as_choices(), default=SortOptions.DATE, required=False
... | BaseOrganizationSearchSerializer |
python | django__django | tests/custom_lookups/tests.py | {
"start": 5119,
"end": 5291
} | class ____(SQLFuncMixin, models.Transform):
def __init__(self, name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
| SQLFuncTransform |
python | RaRe-Technologies__gensim | gensim/test/test_indirect_confirmation.py | {
"start": 527,
"end": 2931
} | class ____(unittest.TestCase):
def setUp(self):
# Set up toy example for better understanding and testing
# of this module. See the modules for the mathematical formulas
self.topics = [np.array([1, 2])]
# Result from s_one_set segmentation:
self.segmentation = [[(1, np.array(... | TestIndirectConfirmation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.