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 | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 97126,
"end": 98260
} | class ____(fixtures.TestBase):
def test_modules_are_loaded(self):
to_restore = []
for m in ("xml.dom", "wsgiref.simple_server"):
to_restore.append((m, sys.modules.pop(m, None)))
try:
mr = preloaded._ModuleRegistry()
ret = mr.preload_module(
... | TestModuleRegistry |
python | pytorch__pytorch | torch/_numpy/_dtypes.py | {
"start": 2625,
"end": 2740
} | class ____(complexfloating):
name = "complex128"
typecode = "D"
torch_dtype = torch.complex128
| complex128 |
python | plotly__plotly.py | plotly/graph_objs/scattercarpet/selected/_textfont.py | {
"start": 233,
"end": 2451
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattercarpet.selected"
_path_str = "scattercarpet.selected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of selected points.
The 'color' property is a color and may be spe... | Textfont |
python | ray-project__ray | python/ray/tests/accelerators/mock_dpctl_2.py | {
"start": 0,
"end": 124
} | class ____:
def __init__(self, info):
pass
@property
def device_count(self):
return 4
| SyclContext |
python | ansible__ansible | lib/ansible/plugins/action/raw.py | {
"start": 792,
"end": 1762
} | class ____(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
if self._task.environment and any(self._task.environment):
self._display.warning('raw module does not support the environment keyword')
... | ActionModule |
python | jina-ai__jina | jina/serve/runtimes/servers/composite.py | {
"start": 3437,
"end": 4195
} | class ____(CompositeBaseServer):
"""Composite Server implementation"""
def __init__(
self,
**kwargs,
):
"""Initialize the gateway
:param kwargs: keyword args
"""
super().__init__(**kwargs)
from jina.parsers.helper import _get_gateway_class
se... | CompositeServer |
python | dagster-io__dagster | python_modules/libraries/dagster-deltalake-pandas/dagster_deltalake_pandas/deltalake_pandas_type_handler.py | {
"start": 333,
"end": 813
} | class ____(DeltalakeBaseArrowTypeHandler[pd.DataFrame]):
def from_arrow(
self, obj: pa.RecordBatchReader, target_type: type[pd.DataFrame]
) -> pd.DataFrame:
return obj.read_pandas()
def to_arrow(self, obj: pd.DataFrame) -> tuple[pa.RecordBatchReader, dict[str, Any]]:
return pa.Table... | DeltaLakePandasTypeHandler |
python | scipy__scipy | benchmarks/benchmarks/linalg_logm.py | {
"start": 164,
"end": 785
} | class ____(Benchmark):
params = [
['float64', 'complex128'],
[64, 256],
['gen', 'her', 'pos']
]
param_names = ['dtype', 'n', 'structure']
def setup(self, dtype, n, structure):
n = int(n)
dtype = np.dtype(dtype)
A = np.random.rand(n, n)
if dtype =... | Logm |
python | dagster-io__dagster | python_modules/libraries/dagster-mysql/dagster_mysql_tests/test_event_log.py | {
"start": 759,
"end": 5329
} | class ____(TestEventLogStorage):
__test__ = True
@pytest.fixture(name="instance", scope="function")
def instance(self, conn_string):
MySQLEventLogStorage.create_clean_storage(conn_string)
with instance_for_test(
overrides={"storage": {"mysql": {"mysql_url": conn_string}}}
... | TestMySQLEventLogStorage |
python | kamyu104__LeetCode-Solutions | Python/sum-of-matrix-after-queries.py | {
"start": 46,
"end": 516
} | class ____(object):
def matrixSumQueries(self, n, queries):
"""
:type n: int
:type queries: List[List[int]]
:rtype: int
"""
lookup = [[False]*n for _ in xrange(2)]
cnt = [0]*2
result = 0
for t, i, v in reversed(queries):
if lookup[t... | Solution |
python | python__mypy | mypy/semanal_enum.py | {
"start": 1283,
"end": 10197
} | class ____:
def __init__(self, options: Options, api: SemanticAnalyzerInterface) -> None:
self.options = options
self.api = api
def process_enum_call(self, s: AssignmentStmt, is_func_scope: bool) -> bool:
"""Check if s defines an Enum; if yes, store the definition in symbol table.
... | EnumCallAnalyzer |
python | huggingface__transformers | tests/utils/test_versions_utils.py | {
"start": 889,
"end": 3487
} | class ____(TestCasePlus):
def test_core(self):
# lt + different version strings
require_version_core("numpy<1000.4.5")
require_version_core("numpy<1000.4")
require_version_core("numpy<1000")
# le
require_version_core("numpy<=1000.4.5")
require_version_core(f"... | DependencyVersionCheckTest |
python | huggingface__transformers | tests/models/deepseek_v2/test_modeling_deepseek_v2.py | {
"start": 1201,
"end": 1798
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = DeepseekV2Model
def __init__(
self,
parent,
n_routed_experts=8,
kv_lora_rank=32,
q_lora_rank=16,
qk_nope_head_dim=64,
qk_rope_head_dim=64,
):
super().__init__... | DeepseekV2ModelTester |
python | gevent__gevent | src/gevent/tests/test__exc_info.py | {
"start": 449,
"end": 1377
} | class ____(greentest.TestCase):
def test1(self):
error = RawException('hello')
expected_error = ExpectedError('expected exception in hello')
try:
raise error
except RawException:
self.expect_one_error()
g = gevent.spawn(hello, expected_error)
... | Test |
python | geekcomputers__Python | singly_linked_list.py | {
"start": 94,
"end": 2620
} | class ____:
def __init__(self):
self.head = None
def length(self):
curr = self.head
count = 0
while curr.next != None:
count += 1
curr = curr.next
return count
def add_node(self, data):
new_node = Node(data)
if self.head is No... | LinkedList |
python | FactoryBoy__factory_boy | tests/test_fuzzy.py | {
"start": 184,
"end": 470
} | class ____(unittest.TestCase):
def test_simple_call(self):
d = fuzzy.FuzzyAttribute(lambda: 10)
res = utils.evaluate_declaration(d)
self.assertEqual(10, res)
res = utils.evaluate_declaration(d)
self.assertEqual(10, res)
| FuzzyAttributeTestCase |
python | nryoung__algorithms | tests/test_searching.py | {
"start": 5123,
"end": 5484
} | class ____(unittest.TestCase):
"""
Tests KMP search on string "ABCDE FG ABCDEABCDEF"
"""
def test_kmpsearch(self):
self.string = "ABCDE FG ABCDEABCDEF"
rv1 = kmp_search.search(self.string, "ABCDEA")
rv2 = kmp_search.search(self.string, "ABCDER")
self.assertIs(rv1[0], 9)
... | TestKMPSearch |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/auto_fr.py | {
"start": 113,
"end": 808
} | class ____(App):
CSS = """
Screen {
align: center middle;
border: solid cyan;
}
#container {
width: 30;
height: auto;
border: solid green;
overflow-y: auto;
}
#child {
height: 1fr;
border: solid red;
}
... | FRApp |
python | eth-brownie__brownie | brownie/_config.py | {
"start": 4796,
"end": 4862
} | class ____(ConfigContainer, metaclass=_Singleton): ...
@final
| Config |
python | sympy__sympy | sympy/core/tests/test_expr.py | {
"start": 27347,
"end": 80071
} | class ____(Mul):
pass
def test_as_independent():
assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
... | CustomMul |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/base_streams.py | {
"start": 9491,
"end": 13373
} | class ____(FBMarketingStream, CheckpointMixin, ABC):
"""Base class for incremental streams"""
cursor_field = "updated_time"
def __init__(self, start_date: Optional[datetime], end_date: Optional[datetime], **kwargs):
super().__init__(**kwargs)
self._start_date = AirbyteDateTime.from_datetim... | FBMarketingIncrementalStream |
python | neetcode-gh__leetcode | python/0791-custom-sort-string.py | {
"start": 0,
"end": 532
} | class ____:
def customSortString(self, order: str, s: str) -> str:
char_count_of_s = {}
for i in s:
char_count_of_s[i] = char_count_of_s.get(i, 0) + 1
satisfied_string = ""
for char in order:
if char in char_count_of_s:
satisfied_strin... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/function7.py | {
"start": 588,
"end": 723
} | class ____:
def write(self, a: str, b: str):
pass
def make_writer2(w: _Writer2):
pass
make_writer2(Writer2())
| Writer2 |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/synapse.py | {
"start": 10438,
"end": 16064
} | class ____(BaseAzureSynapseHook):
"""
A hook to interact with Azure Synapse Pipeline.
:param azure_synapse_conn_id: The :ref:`Azure Synapse connection id<howto/connection:synapse>`.
:param azure_synapse_workspace_dev_endpoint: The Azure Synapse Workspace development endpoint.
"""
default_conn_... | AzureSynapsePipelineHook |
python | ethereum__web3.py | web3/method.py | {
"start": 7800,
"end": 8570
} | class ____:
def __init__(
self,
method: Method[Callable[..., Any]],
old_name: str | None = None,
new_name: str | None = None,
msg: str | None = None,
) -> None:
self.method = method
self.old_name = old_name
self.new_name = new_name
self.msg... | DeprecatedMethod |
python | fluentpython__example-code | 14-it-generator/isis2json/subfield.py | {
"start": 1767,
"end": 2809
} | class ____(object):
''' Represent an Isis field, with subfields, using
Python native datastructures
>>> author = CompositeString('John Tenniel^xillustrator',
... subkeys='x')
>>> unicode(author)
u'John Tenniel^xillustrator'
'''
def __init__(self, isis_raw, subkeys=None, encoding=DE... | CompositeString |
python | weaviate__weaviate-python-client | weaviate/collections/classes/generative.py | {
"start": 5925,
"end": 7290
} | class ____(_GenerativeConfigRuntime):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.DATABRICKS, frozen=True, exclude=True
)
endpoint: AnyHttpUrl
frequency_penalty: Optional[float]
log_probs: Optional[bool]
max_tokens: Optional[int]
model: Opt... | _GenerativeDatabricks |
python | doocs__leetcode | solution/0500-0599/0510.Inorder Successor in BST II/Solution.py | {
"start": 177,
"end": 513
} | class ____:
def inorderSuccessor(self, node: "Node") -> "Optional[Node]":
if node.right:
node = node.right
while node.left:
node = node.left
return node
while node.parent and node.parent.right is node:
node = node.parent
return ... | Solution |
python | spack__spack | lib/spack/spack/util/compression.py | {
"start": 16987,
"end": 17166
} | class ____(CompressedFileTypeInterface):
_MAGIC_NUMBER_LZW = b"\x1f\x9d"
_MAGIC_NUMBER_LZH = b"\x1f\xa0"
extension = "Z"
name = "compress'd data"
| ZCompressedFileType |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_estimator_checks.py | {
"start": 3848,
"end": 4143
} | class ____(BaseEstimator):
def __init__(self, key=0):
self.key = key
def fit(self, X, y=None):
X, y = validate_data(self, X, y)
return self
def predict(self, X):
X = check_array(X)
self.key = 1000
return np.ones(X.shape[0])
| ChangesDict |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 2175,
"end": 2263
} | class ____(HashAlgorithm):
name = "sha1"
digest_size = 20
block_size = 64
| SHA1 |
python | keras-team__keras | keras/src/ops/linalg_test.py | {
"start": 311,
"end": 6624
} | class ____(testing.TestCase):
def test_cholesky(self):
x = KerasTensor([None, 20, 20])
out = linalg.cholesky(x)
self.assertEqual(out.shape, (None, 20, 20))
x = KerasTensor([None, None, 20])
with self.assertRaises(ValueError):
linalg.cholesky(x)
x = Keras... | LinalgOpsDynamicShapeTest |
python | langchain-ai__langchain | libs/core/langchain_core/document_loaders/base.py | {
"start": 618,
"end": 3614
} | class ____(ABC): # noqa: B024
"""Interface for Document Loader.
Implementations should implement the lazy-loading method using generators
to avoid loading all documents into memory at once.
`load` is provided just for user convenience and should not be overridden.
"""
# Sub-classes should no... | BaseLoader |
python | ansible__ansible | test/units/module_utils/facts/test_ansible_collector.py | {
"start": 11046,
"end": 11464
} | class ____(collector.BaseFactCollector):
name = 'concat_collected'
def collect(self, module=None, collected_facts=None):
collected_facts = collected_facts or {}
fact_dict = {}
con_cat_list = []
for key, value in collected_facts.items():
con_cat_list.append(value)
... | ConCatFactCollector |
python | psf__black | src/black/ranges.py | {
"start": 16588,
"end": 20594
} | class ____:
"""1-based lines mapping from original source to modified source.
Lines [original_start, original_end] from original source
are mapped to [modified_start, modified_end].
The ranges are inclusive on both ends.
"""
original_start: int
original_end: int
modified_start: int
... | _LinesMapping |
python | scrapy__scrapy | tests/test_pipeline_media.py | {
"start": 7971,
"end": 14314
} | class ____(TestBaseMediaPipeline):
pipeline_class = MockedMediaPipeline
def _errback(self, result):
self.pipe._mockcalled.append("request_errback")
return result
@inlineCallbacks
def test_result_succeed(self):
rsp = Response("http://url1")
req = Request(
"ht... | TestMediaPipeline |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 7968,
"end": 8236
} | class ____(Message):
message = "'...'.format(...) has unused named argument(s): %s"
def __init__(self, filename, loc, extra_keywords):
Message.__init__(self, filename, loc)
self.message_args = (extra_keywords,)
| StringDotFormatExtraNamedArguments |
python | wandb__wandb | wandb/sdk/artifacts/_generated/project_artifacts.py | {
"start": 553,
"end": 748
} | class ____(GQLResult):
artifact_collection: Optional[
ProjectArtifactsProjectArtifactTypeArtifactCollection
] = Field(alias="artifactCollection")
| ProjectArtifactsProjectArtifactType |
python | pypa__warehouse | tests/unit/oidc/models/test_github.py | {
"start": 28619,
"end": 30855
} | class ____:
def test_reify_does_not_exist_yet(self, db_request):
pending_publisher = PendingGitHubPublisherFactory.create()
assert (
db_request.db.query(github.GitHubPublisher)
.filter_by(
repository_name=pending_publisher.repository_name,
repo... | TestPendingGitHubPublisher |
python | numba__numba | numba/tests/test_np_randomgen.py | {
"start": 5988,
"end": 53649
} | class ____(MemoryLeakMixin, TestCase):
def check_numpy_parity(self, distribution_func,
bitgen_type=None, seed=None,
test_size=None, test_dtype=None,
ulp_prec=5):
distribution_func = numba.njit(distribution_func)
if see... | TestRandomGenerators |
python | kamyu104__LeetCode-Solutions | Python/analyze-user-website-visit-pattern.py | {
"start": 71,
"end": 666
} | class ____(object):
def mostVisitedPattern(self, username, timestamp, website):
"""
:type username: List[str]
:type timestamp: List[int]
:type website: List[str]
:rtype: List[str]
"""
lookup = collections.defaultdict(list)
A = zip(timestamp, username, ... | Solution |
python | indygreg__python-build-standalone | cpython-windows/build.py | {
"start": 6579,
"end": 66041
} | class ____(Exception):
"""Represents a missing search string when replacing content in a file."""
def static_replace_in_file(p: pathlib.Path, search, replace):
"""Replace occurrences of a string in a file.
The updated file contents are written out in place.
"""
with p.open("rb") as fh:
d... | NoSearchStringError |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/attributes/duplicates.py | {
"start": 60,
"end": 260
} | class ____():
example1: int
example2: int
def __init__(self):
self.example1 = 1
self.example2 = 2
# Test for https://github.com/pylint-dev/pylint/issues/8522
| DuplicateFields |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 54146,
"end": 58613
} | class ____(ElectraPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"generator_lm_head.weight": "electra.embeddings.word_embeddings.weight"}
def __init__(self, config):
super().__init__(config)
if not config.is_decoder:
logger.warning("If you want to use `ElectraForCausalLM`... | ElectraForCausalLM |
python | catalyst-team__catalyst | catalyst/callbacks/metrics/classification.py | {
"start": 269,
"end": 3873
} | class ____(BatchMetricCallback):
"""Multiclass PrecisionRecallF1Support metric callback.
Args:
input_key: input key to use for metric calculation, specifies our `y_pred`
target_key: output key to use for metric calculation, specifies our `y_true`
num_classes: number of classes
z... | PrecisionRecallF1SupportCallback |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 24187,
"end": 27566
} | class ____(FocalNetPreTrainedModel):
def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
use_mask_token (`bool`, *optional*, defaults to `False`):
Wheth... | FocalNetModel |
python | Netflix__metaflow | metaflow/unbounded_foreach.py | {
"start": 86,
"end": 387
} | class ____(object):
"""
Plugins that wish to support `UnboundedForeach` need their special
input(s) subclass this class.
This is used by the runtime to detect the difference between bounded
and unbounded foreach, based on the variable passed to `foreach`.
"""
| UnboundedForeachInput |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 48379,
"end": 49294
} | class ____(themeable):
"""
y-axis major-tick length
Parameters
----------
theme_element : float | complex
Value in points. A negative value creates the ticks
inside the plot panel. A complex value (e.g. `3j`)
creates ticks that span both in and out of the panel.
"""
... | axis_ticks_length_major_y |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_pathconverter.py | {
"start": 8194,
"end": 8794
} | class ____(TestAbsolute):
"""Test absolute paths with file:// scheme."""
extension = ["pymdownx.pathconverter"]
extension_configs = {
"pymdownx.pathconverter": {
"base_path": "/Some/fake/path",
"absolute": True,
"file_scheme": True,
}
}
def test_... | TestAbsoluteFileScheme |
python | pdm-project__pdm | src/pdm/termui.py | {
"start": 2922,
"end": 3141
} | class ____(enum.IntEnum):
QUIET = -1
NORMAL = 0
DETAIL = 1
DEBUG = 2
LOG_LEVELS = {
Verbosity.NORMAL: logging.WARN,
Verbosity.DETAIL: logging.INFO,
Verbosity.DEBUG: logging.DEBUG,
}
| Verbosity |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_grad_test.py | {
"start": 3520,
"end": 12302
} | class ____(test_lib.TestCase):
pass # Filled in below
def _GetMatrixBinaryFunctorGradientTest(functor_,
dtype_,
shape_,
float32_tol_fudge=1.0,
**kwargs_):
... | MatrixBinaryFunctorGradientTest |
python | sanic-org__sanic | sanic/models/futures.py | {
"start": 756,
"end": 852
} | class ____(NamedTuple):
listener: ListenerType
event: str
priority: int
| FutureListener |
python | kamyu104__LeetCode-Solutions | Python/brace-expansion.py | {
"start": 1309,
"end": 2769
} | class ____(object):
def expand(self, S): # nested is fine
"""
:type S: str
:rtype: List[str]
"""
def form_words(options):
words = []
total = 1
for opt in options:
total *= len(opt)
for i in xrange(total):
... | Solution2 |
python | ray-project__ray | python/ray/tests/test_batch_node_provider_unit.py | {
"start": 773,
"end": 3619
} | class ____(BatchingNodeProvider):
"""Mock implementation of a BatchingNodeProvider."""
def __init__(
self,
provider_config: Dict[str, Any],
cluster_name: str,
) -> None:
BatchingNodeProvider.__init__(self, provider_config, cluster_name)
# Fake cluster manager state:
... | MockBatchingNodeProvider |
python | ray-project__ray | python/ray/_private/authentication/grpc_authentication_client_interceptor.py | {
"start": 2892,
"end": 4774
} | class ____(
aiogrpc.UnaryUnaryClientInterceptor,
aiogrpc.UnaryStreamClientInterceptor,
aiogrpc.StreamUnaryClientInterceptor,
aiogrpc.StreamStreamClientInterceptor,
):
"""Async gRPC client interceptor that adds authentication metadata."""
def _intercept_call_details(self, client_call_details):
... | AsyncAuthenticationMetadataClientInterceptor |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/modular_deepseek_vl_hybrid.py | {
"start": 19302,
"end": 36545
} | class ____(DeepseekVLImageProcessor):
r"""
Constructs a DEEPSEEK_VL_HYBRID image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
`do_resize` parame... | DeepseekVLHybridImageProcessor |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 85181,
"end": 87017
} | class ____(CIntType):
to_py_function = "__Pyx_PyBool_FromLong"
from_py_function = "__Pyx_PyObject_IsTrue"
exception_check = 1 # for C++ bool
default_format_spec = ''
def can_coerce_to_pystring(self, env, format_spec=None):
return not format_spec or super().can_coerce_to_pystring(env, form... | CBIntType |
python | skorch-dev__skorch | skorch/tests/test_hf.py | {
"start": 42583,
"end": 54533
} | class ____:
# Note: Since we mock away the HfApi, we cannot be sure that these tests
# wouldn't miss certain types of bugs. Alternatively, we could not use the
# mock but in this case, we would create real uploads (and need to have a
# valid token), which we want to avoid. Other than that, we could try ... | TestHfHubStorage |
python | ansible__ansible | lib/ansible/plugins/action/set_stats.py | {
"start": 894,
"end": 2476
} | class ____(ActionBase):
TRANSFERS_FILES = False
_VALID_ARGS = frozenset(('aggregate', 'data', 'per_host'))
_requires_connection = False
# TODO: document this in non-empty set_stats.py module
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
... | ActionModule |
python | doocs__leetcode | solution/0100-0199/0104.Maximum Depth of Binary Tree/Solution.py | {
"start": 192,
"end": 397
} | class ____:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
l, r = self.maxDepth(root.left), self.maxDepth(root.right)
return 1 + max(l, r)
| Solution |
python | huggingface__transformers | src/transformers/models/vitdet/modeling_vitdet.py | {
"start": 21059,
"end": 23063
} | class ____(nn.Module):
def __init__(self, config: VitDetConfig) -> None:
super().__init__()
self.config = config
depth = config.num_hidden_layers
# stochastic depth decay rule
drop_path_rate = [x.item() for x in torch.linspace(0, config.drop_path_rate, depth, device="cpu")]
... | VitDetEncoder |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 1365,
"end": 2998
} | class ____(collections.abc.Mapping):
"""
Project a set of keys over a mapping
>>> sample = {'a': 1, 'b': 2, 'c': 3}
>>> prj = Projection(['a', 'c', 'd'], sample)
>>> dict(prj)
{'a': 1, 'c': 3}
Projection also accepts an iterable or callable or pattern.
>>> iter_prj = Projection(iter('... | Projection |
python | wandb__wandb | wandb/automations/_generated/create_generic_webhook_integration.py | {
"start": 542,
"end": 819
} | class ____(GQLResult):
integration: Union[
CreateGenericWebhookIntegrationCreateGenericWebhookIntegrationIntegrationIntegration,
WebhookIntegrationFields,
] = Field(discriminator="typename__")
| CreateGenericWebhookIntegrationCreateGenericWebhookIntegration |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/traversal_context.py | {
"start": 2911,
"end": 5737
} | class ____(ContextData):
config_type: ConfigType
do_post_process: bool
@staticmethod
def from_config_type(
config_type: ConfigType,
stack: EvaluationStackEntry,
do_post_process: bool,
) -> "TraversalContext":
return TraversalContext(
config_schema_snapsho... | TraversalContext |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9984
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary.marker.colorbar.title"
_path_str = "scatterternary.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"v... | Font |
python | django__django | django/core/management/commands/diffsettings.py | {
"start": 285,
"end": 3564
} | class ____(BaseCommand):
help = """Displays differences between the current settings.py and Django's
default settings."""
requires_system_checks = []
def add_arguments(self, parser):
parser.add_argument(
"--all",
action="store_true",
help=(
'... | Command |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/views/user.py | {
"start": 3902,
"end": 4055
} | class ____(MultiResourceUserMixin, UserOAuthModelView):
"""Customize permission names for FAB's builtin UserOAuthModelView."""
| CustomUserOAuthModelView |
python | huggingface__transformers | src/transformers/models/mpnet/tokenization_mpnet.py | {
"start": 1150,
"end": 9013
} | class ____(TokenizersBackend):
r"""
Construct a MPNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those meth... | MPNetTokenizer |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 63969,
"end": 65382
} | class ____(gdb.Command):
'Look up the given python variable name, and print it'
def __init__(self):
gdb.Command.__init__ (self,
"py-locals",
gdb.COMMAND_DATA,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tt... | PyLocals |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/system.py | {
"start": 6255,
"end": 6789
} | class ____(NamedTuple):
"""The data about a run that is available during both orchestration and execution.
This object does not contain any information that requires access to user code, such as the
pipeline definition and resources.
"""
job: IJob
dagster_run: DagsterRun
instance: "Dagster... | PlanData |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/client.py | {
"start": 1876,
"end": 2494
} | class ____(Exception):
def __init__(self, *args, **kwargs):
k8s_api_exception = check.inst_param(
kwargs.pop("k8s_api_exception"), "k8s_api_exception", Exception
)
original_exc_info = check.tuple_param(kwargs.pop("original_exc_info"), "original_exc_info")
check.invariant... | DagsterK8sUnrecoverableAPIError |
python | python-jsonschema__jsonschema | jsonschema/exceptions.py | {
"start": 8231,
"end": 8832
} | class ____(Exception):
"""
A validator was asked to validate an instance against an unknown type.
"""
def __init__(self, type, instance, schema):
self.type = type
self.instance = instance
self.schema = schema
def __str__(self):
prefix = 16 * " "
return dede... | UnknownType |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py | {
"start": 2885,
"end": 2933
} | class ____(TypedDict):
a: ReadOnly[float]
| TD12 |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 82152,
"end": 84675
} | class ____(UserDefinedObjectVariable):
"""
Represents user defined objects that are subclasses of dict/OrderedDict.
Internally, it uses a ConstDictVariable to represent the dict part of the
variable tracker. For everything else, it falls back to
UserDefinedObjectVariable.
"""
def __init__(... | UserDefinedDictVariable |
python | PrefectHQ__prefect | src/prefect/client/schemas/sorting.py | {
"start": 2184,
"end": 2384
} | class ____(AutoEnum):
"""Defines variables sorting options."""
CREATED_DESC = "CREATED_DESC"
UPDATED_DESC = "UPDATED_DESC"
NAME_DESC = "NAME_DESC"
NAME_ASC = "NAME_ASC"
| VariableSort |
python | kamyu104__LeetCode-Solutions | Python/longest-increasing-path-in-a-matrix.py | {
"start": 1633,
"end": 2694
} | class ____(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
def longestpath(matrix, i, j, max_lengths):
if max_lengths[i][j]:
return max_len... | Solution2 |
python | redis__redis-py | redis/exceptions.py | {
"start": 1540,
"end": 1663
} | class ____(LockError):
"Error trying to extend or release a lock that is not owned (anymore)"
pass
| LockNotOwnedError |
python | catalyst-team__catalyst | catalyst/contrib/data/sampler_inbatch.py | {
"start": 561,
"end": 1666
} | class ____(ABC):
"""An abstraction of inbatch triplet sampler."""
@abstractmethod
def _check_input_labels(self, labels: List[int]) -> None:
"""
Check if the batch labels list is valid for the sampler.
We expect you to implement this method to guarantee correct
performance o... | IInbatchTripletSampler |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 84675,
"end": 87148
} | class ____(UserDefinedObjectVariable):
"""
Represents user defined objects that are subclasses of set.
Internally, it uses a SetVariable to represent the set part of the
variable tracker. For everything else, it falls back to
UserDefinedObjectVariable.
"""
def __init__(self, value, set_vt=... | UserDefinedSetVariable |
python | tensorflow__tensorflow | tensorflow/python/eager/small_constants_optimizer_test.py | {
"start": 1382,
"end": 5962
} | class ____(test.TestCase):
@test_util.run_v2_only
def test_grappler_optimization(self):
@polymorphic_function.function
def brancher(inp):
x = constant_op.constant(1)
for _ in range(1000):
if inp:
x = x + constant_op.constant(1)
else:
x = x + constant_op.const... | FunctionTest |
python | encode__django-rest-framework | tests/test_validation.py | {
"start": 8049,
"end": 8215
} | class ____(TestCase):
def test_regex_repr(self):
serializer_repr = repr(RegexSerializer())
assert serializer_repr == expected_repr
| TestRegexSerializer |
python | plotly__plotly.py | plotly/express/_core.py | {
"start": 2070,
"end": 116298
} | class ____(object):
__slots__ = [
"template",
"width",
"height",
"color_discrete_sequence",
"color_discrete_map",
"color_continuous_scale",
"symbol_sequence",
"symbol_map",
"line_dash_sequence",
"line_dash_map",
"pattern_shape_s... | PxDefaults |
python | coleifer__peewee | playhouse/pool.py | {
"start": 12397,
"end": 12598
} | class ____(PooledDatabase):
def _is_closed(self, conn):
try:
conn.total_changes
except:
return True
else:
return False
| _PooledSqliteDatabase |
python | huggingface__transformers | tests/models/clip/test_modeling_clip.py | {
"start": 20004,
"end": 23324
} | class ____(CLIPModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (CLIPModel,) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": CLIPModel, "image-feature-extraction": CLIPVisionModel} if is_torch_available() else {}
)
additional_model_... | CLIPModelTest |
python | falconry__falcon | falcon/errors.py | {
"start": 90238,
"end": 92447
} | class ____(HTTPBadRequest):
"""400 Bad Request.
One of the headers in the request is invalid.
`msg` and `header_name` are the only positional arguments allowed,
the other arguments are defined as keyword-only.
Args:
msg (str): A description of why the value is invalid.
header_name... | HTTPInvalidHeader |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 5914,
"end": 6349
} | class ____(graphene.ObjectType):
op = graphene.NonNull(GrapheneObjectStoreOperationType)
class Meta:
interfaces = (GrapheneDisplayableEvent,)
name = "ObjectStoreOperationResult"
def resolve_metadataEntries(self, _graphene_info: ResolveInfo):
from dagster_graphql.implementation.even... | GrapheneObjectStoreOperationResult |
python | numba__numba | numba/cuda/compiler.py | {
"start": 2387,
"end": 3193
} | class ____(LoweringPass):
_name = "cuda_backend"
def __init__(self):
LoweringPass.__init__(self)
def run_pass(self, state):
"""
Back-end: Packages lowering output in a compile result
"""
lowered = state['cr']
signature = typing.signature(state.return_type, ... | CUDABackend |
python | explosion__spaCy | spacy/tests/parser/test_ner.py | {
"start": 28882,
"end": 29176
} | class ____:
def __init__(self, nlp, start, end, name="my_blocker"):
self.start = start
self.end = end
self.name = name
def __call__(self, doc):
doc.set_ents([], blocked=[doc[self.start : self.end]], default="unmodified")
return doc
| BlockerComponent1 |
python | PrefectHQ__prefect | src/prefect/cli/cloud/ip_allowlist.py | {
"start": 3779,
"end": 9283
} | class ____(BaseModel):
raw: str
parsed: IPvAnyNetwork
def parse_ip_network_argument(val: str) -> IPNetworkArg:
return IPNetworkArg(
raw=val,
parsed=val,
)
IP_ARGUMENT = Annotated[
IPNetworkArg,
typer.Argument(
parser=parse_ip_network_argument,
help="An IP addr... | IPNetworkArg |
python | kubernetes-client__python | kubernetes/client/models/v1_http_get_action.py | {
"start": 383,
"end": 7067
} | 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... | V1HTTPGetAction |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/screen_switch.py | {
"start": 130,
"end": 405
} | class ____(Screen):
BINDINGS = [("b", "switch_to_b", "Switch to screen B")]
def compose(self) -> ComposeResult:
yield Header()
yield Static("A")
yield Footer()
def action_switch_to_b(self):
self.app.switch_screen(ScreenB())
| ScreenA |
python | pennersr__django-allauth | allauth/mfa/internal/flows/trust.py | {
"start": 370,
"end": 2791
} | class ____:
fingerprint: str
at: int
def create_config_fingerprint(user: AbstractBaseUser) -> str:
"""
If the user changes anything about his security setup, we want to invalidate
any trust that was issued before.
"""
salt = "allauth.mfa.trust"
parts: List[str] = []
parts.append(st... | IssuedTrust |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/str.py | {
"start": 888,
"end": 1322
} | class ____(SeriesDefault):
"""Builder for default-to-pandas methods which is executed under `str` accessor."""
@classmethod
def frame_wrapper(cls, df):
"""
Get `str` accessor of the passed frame.
Parameters
----------
df : pandas.DataFrame
Returns
-... | StrDefault |
python | kamyu104__LeetCode-Solutions | Python/minimum-moves-to-make-array-complementary.py | {
"start": 33,
"end": 1005
} | class ____(object):
def minMoves(self, nums, limit):
"""
:type nums: List[int]
:type limit: int
:rtype: int
"""
diff = [0]*(2*(limit+1))
for i in xrange(len(nums)//2):
left, right = nums[i], nums[-1-i]
diff[min(left, right)+1] -= 1 ... | Solution |
python | huggingface__transformers | src/transformers/models/swiftformer/modeling_swiftformer.py | {
"start": 11951,
"end": 13779
} | class ____(nn.Module):
def __init__(self, config: SwiftFormerConfig) -> None:
super().__init__()
self.config = config
embed_dims = config.embed_dims
downsamples = config.downsamples
layer_depths = config.depths
# Transformer model
network = []
for i ... | SwiftFormerEncoder |
python | ansible__ansible | packaging/release.py | {
"start": 3739,
"end": 4436
} | class ____:
"""Display interface for sending output to the console."""
CLEAR = "\033[0m"
RED = "\033[31m"
BLUE = "\033[34m"
PURPLE = "\033[35m"
CYAN = "\033[36m"
def fatal(self, message: t.Any) -> None:
"""Print a fatal message to the console."""
self.show(f"FATAL: {message... | Display |
python | sympy__sympy | sympy/liealgebras/type_f.py | {
"start": 91,
"end": 4423
} | class ____(Standard_Cartan):
def __new__(cls, n):
if n != 4:
raise ValueError("n should be 4")
return Standard_Cartan.__new__(cls, "F", 4)
def dimension(self):
"""Dimension of the vector space V underlying the Lie algebra
Examples
========
>>> from... | TypeF |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 34692,
"end": 34834
} | class ____(serializers.ModelSerializer):
class Meta:
model = UniqueForMonthModel
fields = '__all__'
| UniqueForMonthSerializer |
python | scipy__scipy | scipy/sparse/linalg/_special_sparse_arrays.py | {
"start": 27558,
"end": 30268
} | class ____(LinearOperator):
"""
Construct a stiffness matrix in various formats of Mikota pair.
The stiffness matrix `K` is square real tri-diagonal symmetric
positive definite with integer entries.
Parameters
----------
shape : tuple of int
The shape of the matrix.
dtype : dty... | MikotaK |
python | ray-project__ray | rllib/examples/_old_api_stack/models/fast_model.py | {
"start": 406,
"end": 1779
} | class ____(TFModelV2):
"""An example for a non-Keras ModelV2 in tf that learns a single weight.
Defines all network architecture in `forward` (not `__init__` as it's
usually done for Keras-style TFModelV2s).
"""
def __init__(self, obs_space, action_space, num_outputs, model_config, name):
... | FastModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.