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
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/map_ops_test.py
{ "start": 1255, "end": 16715 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testEmptyTensorMapSize(self): m = map_ops.empty_tensor_map() s = map_ops.tensor_map_size(m) self.assertAllEqual(s, 0) def testTensorMapInsert(self): m = map_ops.empty_tensor_map() k = constant_op.constant(1.0) v = consta...
MapOpsTest
python
PyCQA__pylint
tests/functional/r/regression/regression_property_no_member_2641.py
{ "start": 441, "end": 690 }
class ____(Person): def __init__(self, name, age, tel): super().__init__(name, age) self.tel = tel @Person.name.setter def name(self, value): super(self.__class__, self.__class__).name.fset(self, "override")
Myself
python
plotly__plotly.py
plotly/graph_objs/layout/map/layer/_symbol.py
{ "start": 235, "end": 7816 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.map.layer" _path_str = "layout.map.layer.symbol" _valid_props = {"icon", "iconsize", "placement", "text", "textfont", "textposition"} @property def icon(self): """ Sets the symbol icon image (map.layer.layout.icon-imag...
Symbol
python
django__django
tests/app_loading/tests.py
{ "start": 2607, "end": 3071 }
class ____(SimpleTestCase): def setUp(self): from .not_installed import models self.not_installed_module = models def test_get_model_only_returns_installed_models(self): with self.assertRaises(LookupError): apps.get_model("not_installed", "NotInstalledModel") def test_...
GetModelsTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/control_flow/map_fn_test.py
{ "start": 2197, "end": 10572 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def testMap_Simple(self): nums = [1, 2, 3, 4, 5, 6] elems = constant_op.constant(nums, name="data") r = map_fn.map_fn( lambda x: math_ops.multiply(math_ops.add(x, 3), 2), elems) self.assertAllEqual( np.array([(x + 3)...
MapFnTest
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2.py
{ "start": 82511, "end": 92191 }
class ____(object): """Handles caching of transformations while building the model. `FeatureColumn` specifies how to digest an input column to the network. Some feature columns require data transformations. This class caches those transformations. Some features may be used in more than one place. For exampl...
FeatureTransformationCache
python
doocs__leetcode
solution/0300-0399/0391.Perfect Rectangle/Solution.py
{ "start": 0, "end": 1007 }
class ____: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: area = 0 minX, minY = rectangles[0][0], rectangles[0][1] maxX, maxY = rectangles[0][2], rectangles[0][3] cnt = defaultdict(int) for r in rectangles: area += (r[2] - r[0]) * (r[3] - r[1])...
Solution
python
facebookresearch__faiss
tests/test_swig_wrapper.py
{ "start": 5813, "end": 6070 }
class ____(unittest.TestCase): def test_doxygen_comments(self): maxheap_array = faiss.float_maxheap_array_t() self.assertTrue("a template structure for a set of [min|max]-heaps" in maxheap_array.__doc__)
TestDoxygen
python
getsentry__sentry
src/sentry/auth/providers/saml2/okta/provider.py
{ "start": 325, "end": 753 }
class ____(SAML2Provider): name = "Okta" key = "okta" def get_saml_setup_pipeline(self) -> list[AuthView]: return [SelectIdP()] def attribute_mapping(self) -> dict[str, str]: return { Attributes.IDENTIFIER: "identifier", Attributes.USER_EMAIL: "email", ...
OktaSAML2Provider
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 19803, "end": 20446 }
class ____(BaseModel, Generic[T]): foo: Foo Foo.model_rebuild() """ ) finally: del sys.modules['eval_type_backport'] assert module.Foo.model_fields['bar'].annotation == typing.Optional[module.Bar[str]] assert module.Foo.model_fields['bar2'].annotation == typing.Union[int, module.Ba...
Bar
python
html5lib__html5lib-python
html5lib/tests/tree_construction.py
{ "start": 570, "end": 813 }
class ____(pytest.File): def collect(self): tests = TestData(str(self.fspath), "data") for i, test in enumerate(tests): yield TreeConstructionTest.from_parent(self, name=str(i), testdata=test)
TreeConstructionFile
python
allegroai__clearml
clearml/backend_api/services/v2_13/queues.py
{ "start": 28958, "end": 30627 }
class ____(Request): """ Delete metadata from queue :param queue: ID of the queue :type queue: str :param keys: The list of metadata keys to delete :type keys: Sequence[str] """ _service = "queues" _action = "delete_metadata" _version = "2.13" _schema = { "definitio...
DeleteMetadataRequest
python
pytest-dev__pytest
src/_pytest/config/__init__.py
{ "start": 11924, "end": 33872 }
class ____(PluginManager): """A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with additional pytest-specific functionality: * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and ``pytest_plugins`` global variables found in plugins being loaded. * ``conftest.py`` ...
PytestPluginManager
python
mlflow__mlflow
tests/store/tracking/test_abstract_store.py
{ "start": 245, "end": 14067 }
class ____(AbstractStore, ABC): """Mock implementation of AbstractStore for testing.""" def __init__(self): super().__init__() self.metrics = [] def get_metric_history(self, run_id, metric_key, max_results=None, page_token=None): return [m for m in self.metrics if m.run_id == run_i...
MockAbstractStore
python
getsentry__sentry
src/sentry/api/endpoints/organization_trace_item_stats.py
{ "start": 783, "end": 1053 }
class ____(serializers.Serializer): query = serializers.CharField(required=False) statsType = serializers.ListField( child=serializers.ChoiceField(list(SUPPORTED_STATS_TYPES)), required=True ) @region_silo_endpoint
OrganizationTraceItemsStatsSerializer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol33.py
{ "start": 454, "end": 565 }
class ____(Generic[T, U], Protocol): def f(self) -> T | U: ... def g(self) -> "BProto[T, U]": ...
BProto
python
jazzband__django-pipeline
pipeline/collector.py
{ "start": 186, "end": 3535 }
class ____: request = None def __init__(self, storage=None): if storage is None: storage = staticfiles_storage self.storage = storage def _get_modified_time(self, storage, prefixed_path): if django.VERSION[:2] >= (1, 10): return storage.get_modified_time(pre...
Collector
python
numba__numba
numba/tests/test_typeof.py
{ "start": 12331, "end": 20837 }
class ____(TestCase): """ Tests for _dispatcher.compute_fingerprint() Each fingerprint must denote values of only one Numba type (this is the condition for correctness), but values of a Numba type may be denoted by several distinct fingerprints (it only makes the cache less efficient). """ ...
TestFingerprint
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_theme09.py
{ "start": 350, "end": 2146 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_theme09.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Wo...
TestCompareXLSXFiles
python
scipy__scipy
benchmarks/benchmarks/linalg.py
{ "start": 6634, "end": 7891 }
class ____(Benchmark): param_names = ['size'] params = [[4, 128]] def setup(self, size): self.x = np.arange(1, size + 1).astype(float) self.small_blocks = [np.ones([2, 2])] * (size//2) self.big_blocks = [np.ones([size//2, size//2]), np.ones([size//2, size/...
SpecialMatrices
python
geekcomputers__Python
Password Generator/pass_gen.py
{ "start": 38, "end": 764 }
class ____: @staticmethod def gen_sequence( conditions, ): # must have conditions (in a list format), for each member of the list possible_characters possible_characters = [ str.ascii_lowercase, str.ascii_uppercase, str.digits, str.punctuatio...
PasswordGenerator
python
pypa__pipenv
pipenv/patched/pip/_internal/resolution/resolvelib/candidates.py
{ "start": 12205, "end": 14476 }
class ____(Candidate): is_installed = True source_link = None def __init__( self, dist: BaseDistribution, template: InstallRequirement, factory: "Factory", ) -> None: self.dist = dist self._ireq = _make_install_req_from_dist(dist, template) self._...
AlreadyInstalledCandidate
python
matplotlib__matplotlib
galleries/examples/event_handling/lasso_demo.py
{ "start": 735, "end": 2482 }
class ____: def __init__(self, ax, data): # The information of whether a point has been selected or not is stored in the # collection's array (0 = out, 1 = in), which then gets colormapped to blue # (out) and red (in). self.collection = RegularPolyCollection( 6, sizes=(10...
LassoManager
python
ipython__ipython
IPython/core/inputtransformer2.py
{ "start": 16645, "end": 20701 }
class ____(TokenTransformBase): """Transformer for help syntax: obj? and obj??""" # This needs to be higher priority (lower number) than EscapedCommand so # that inspecting magics (%foo?) works. priority = 5 def __init__(self, start, q_locn): super().__init__(start) self.q_line = q_...
HelpEnd
python
huggingface__transformers
tests/models/seamless_m4t/test_tokenization_seamless_m4t.py
{ "start": 19651, "end": 22139 }
class ____(unittest.TestCase): """ A class that regroups important test to make sure that we properly handle the special tokens. """ @classmethod def setUpClass(cls): extractor = SentencePieceExtractor(SAMPLE_VOCAB) _, vocab_scores, merges = extractor.extract() tokenizer = ...
CommonSpmIntegrationTests
python
google__jax
tests/pallas/pallas_test.py
{ "start": 42766, "end": 46624 }
class ____(PallasBaseTest): def test_vector_input_output_aliasing(self): # Input needs to be big so it doesn't fit in VMEM size = 1024 if jtu.is_device_cuda(): # Reduce the size on CUDA to avoid OOM. size = 256 x = jnp.ones((32, size, size)) expected = x + 1 def kernel(x_ref, y_r...
PallasCallInputOutputAliasingTest
python
tensorflow__tensorflow
tensorflow/python/tpu/feature_column.py
{ "start": 16914, "end": 22214 }
class ____(_TPUBaseEmbeddingColumn, fc._EmbeddingColumn): """Core Embedding Column.""" def __new__(cls, categorical_column, dimension, combiner='mean', layer_creator=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, ...
_TPUEmbeddingColumn
python
kamyu104__LeetCode-Solutions
Python/maximum-score-from-removing-stones.py
{ "start": 29, "end": 415 }
class ____(object): def maximumScore(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ # assumed c is the max size # case1: a+b > c # => (a+b-c)//2 + c = (a+b+c)//2 < a+b # case2: a+b <= c # => a+b <= (a...
Solution
python
mlflow__mlflow
mlflow/metrics/genai/prompts/v1.py
{ "start": 12489, "end": 16766 }
class ____: definition = ( "Answer correctness is evaluated on the accuracy of the provided output based on the " "provided targets, which is the ground truth. Scores can be assigned based on the degree " "of semantic similarity and factual correctness of the provided output to the provided ...
AnswerCorrectnessMetric
python
pytorch__pytorch
torch/jit/_script.py
{ "start": 64289, "end": 65230 }
class ____: def __init__(self, cols: list[_ScriptProfileColumn], source_range: list[int]): self.cols = cols self.source_range = source_range def dump_string(self): outputs: list[str] = [] cells: list[tuple[str, dict[int, str]]] = [] header_buffer = "" for col in ...
_ScriptProfileTable
python
pandas-dev__pandas
pandas/io/sas/sas_xport.py
{ "start": 6254, "end": 15064 }
class ____(SASReader): __doc__ = _xport_reader_doc def __init__( self, filepath_or_buffer: FilePath | ReadBuffer[bytes], index=None, encoding: str | None = "ISO-8859-1", chunksize: int | None = None, compression: CompressionOptions = "infer", ) -> None: ...
XportReader
python
PyCQA__pylint
tests/functional/b/bad_exception_cause.py
{ "start": 155, "end": 947 }
class ____(Exception): """ subclass """ def test(): """ docstring """ raise IndexError from 1 # [bad-exception-cause] raise IndexError from None raise IndexError from ZeroDivisionError raise IndexError from object() # [bad-exception-cause] raise IndexError from ExceptionSubclass raise I...
ExceptionSubclass
python
run-llama__llama_index
llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-couchbase/llama_index/storage/kvstore/couchbase/base.py
{ "start": 397, "end": 13238 }
class ____(BaseKVStore): """Couchbase Key-Value store.""" def __init__( self, cluster: Cluster, bucket_name: str, scope_name: str, async_cluster: Optional[AsyncCluster] = None, ) -> None: """ Initializes a CouchbaseKVStore. Args: ...
CouchbaseKVStore
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_shared_strings01.py
{ "start": 315, "end": 1131 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("shared_strings01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self....
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/xlm/configuration_xlm.py
{ "start": 780, "end": 10333 }
class ____(PreTrainedConfig): """ This is the configuration class to store the configuration of a [`XLMModel`]. It is used to instantiate a XLM model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration ...
XLMConfig
python
PyCQA__pylint
tests/functional/i/invalid/invalid_index_returned.py
{ "start": 517, "end": 580 }
class ____: """Index through the metaclass."""
ThirdGoodIndex
python
pytorch__pytorch
torch/distributed/tensor/_api.py
{ "start": 2173, "end": 4238 }
class ____(torch.autograd.Function): @staticmethod def forward( # type: ignore[override] ctx, input: "DTensor", grad_placements: Sequence[Placement] | None, ): ctx.dtensor_spec = input._spec ctx.grad_placements = grad_placements local_tensor = input._local_te...
_ToTorchTensor
python
kamyu104__LeetCode-Solutions
Python/merge-k-sorted-lists.py
{ "start": 265, "end": 1172 }
class ____(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ def mergeTwoLists(l1, l2): curr = dummy = ListNode(0) while l1 and l2: if l1.val < l2.val: curr.next = l1 ...
Solution
python
huggingface__transformers
src/transformers/models/deformable_detr/modeling_deformable_detr.py
{ "start": 1681, "end": 4546 }
class ____(nn.Module): def forward( self, value: Tensor, value_spatial_shapes: Tensor, value_spatial_shapes_list: list[tuple], level_start_index: Tensor, sampling_locations: Tensor, attention_weights: Tensor, im2col_step: int, ): batch_size...
MultiScaleDeformableAttention
python
apache__airflow
providers/databricks/tests/unit/databricks/operators/test_databricks.py
{ "start": 101606, "end": 103633 }
class ____: def test_is_instance_of_databricks_task_base_operator(self): task_config = { "sql_task": { "query": { "query_id": "c9cf6468-babe-41a6-abc3-10ac358c71ee", }, "warehouse_id": "cf414a2206dfb397", } }...
TestDatabricksTaskOperator
python
ray-project__ray
python/ray/data/_internal/planner/exchange/interfaces.py
{ "start": 2921, "end": 5320 }
class ____: """ An interface to schedule exchange tasks (`exchange_spec`) for multi-nodes execution. """ def __init__(self, exchange_spec: ExchangeTaskSpec): """ Args: exchange_spec: The implementation of exchange tasks to execute. """ self._exchange_spec...
ExchangeTaskScheduler
python
getsentry__sentry
src/sentry/web/frontend/group_plugin_action.py
{ "start": 508, "end": 1429 }
class ____(ProjectView): required_scope = "event:read" def handle( self, request: HttpRequest, organization, project, group_id, slug ) -> HttpResponseBase: group = get_object_or_404(Group, pk=group_id, project=project) try: plugin = plugins.get(slug) if is_p...
GroupPluginActionView
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/asyncpg.py
{ "start": 10692, "end": 10796 }
class ____(json.JSONB): def result_processor(self, dialect, coltype): return None
AsyncpgJSONB
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 6734, "end": 7069 }
class ____(graphene.InputObjectType): assetKey = graphene.NonNull(GrapheneAssetKeyInput) partitions = graphene.InputField(GraphenePartitionsSelector) class Meta: description = """This type represents a partitions selection for an asset.""" name = "PartitionsByAssetSelector"
GraphenePartitionsByAssetSelector
python
ionelmc__pytest-benchmark
src/pytest_benchmark/logger.py
{ "start": 206, "end": 2236 }
class ____: QUIET, NORMAL, VERBOSE = range(3) def __init__(self, level=NORMAL, config=None): self.level = level self.term = TerminalWriter(file=sys.stderr) self.suspend_capture = None self.resume_capture = None if config: capman = config.pluginmanager.getplug...
Logger
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 443739, "end": 444295 }
class ____(TupleNode): # CyFunction's __defaults__ tuple def __init__(self, pos, defaults, defaults_struct): args = [] for arg in defaults: if not arg.default.is_literal: arg = DefaultNonLiteralArgNode(pos, arg, defaults_struct) else: arg ...
DefaultsTupleNode
python
facebook__pyre-check
client/configuration/scheduler_policies.py
{ "start": 571, "end": 741 }
class ____: minimum_chunks_per_worker: int preferred_chunk_size: int minimum_chunk_size: Optional[int] = None @dataclasses.dataclass(frozen=True)
FixedChunkSize
python
crytic__slither
slither/detectors/variables/uninitialized_local_variables.py
{ "start": 454, "end": 4804 }
class ____(AbstractDetector): ARGUMENT = "uninitialized-local" HELP = "Uninitialized local variables" IMPACT = DetectorClassification.MEDIUM CONFIDENCE = DetectorClassification.MEDIUM WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-local-variables" WIKI_TIT...
UninitializedLocalVars
python
pydantic__pydantic
pydantic/fields.py
{ "start": 61998, "end": 66600 }
class ____(_repr.Representation): """A descriptor for private attributes in class models. !!! warning You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.) Attributes: defa...
ModelPrivateAttr
python
doocs__leetcode
solution/2500-2599/2578.Split With Minimum Sum/Solution.py
{ "start": 0, "end": 397 }
class ____: def splitNum(self, num: int) -> int: cnt = Counter() n = 0 while num: cnt[num % 10] += 1 num //= 10 n += 1 ans = [0] * 2 j = 0 for i in range(n): while cnt[j] == 0: j += 1 cnt[j] -...
Solution
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 1861, "end": 2399 }
class ____(NamedTuple): """ The namedtuple type returned by ``MathTextParser("path").parse(...)``. Attributes ---------- width, height, depth : float The global metrics. glyphs : list The glyphs including their positions. rect : list The list of rectangles. """ ...
VectorParse
python
python__mypy
mypy/test/data.py
{ "start": 10420, "end": 17260 }
class ____(pytest.Item): """Holds parsed data-driven test cases, and handles directory setup and teardown.""" # Override parent member type parent: DataFileCollector input: list[str] output: list[str] # Output for the first pass output_inline_start: int output2: dict[int, list[str]] # Ou...
DataDrivenTestCase
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_custom_job.py
{ "start": 2985, "end": 7527 }
class ____: def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): self.hook = CustomJobHook(gcp_conn_id=TEST_GCP_CONN_ID) @mock.patch(CUSTOM_JOB_STRING.format("CustomJobHook.get_pipeline_servi...
TestCustomJobWithDefaultProjectIdHook
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 39977, "end": 41428 }
class ____(Uploader): def __init__( self, mirror: spack.mirrors.mirror.Mirror, force: bool, update_index: bool, signing_key: Optional[str], ) -> None: super().__init__(mirror, force, update_index) self.url = mirror.push_url self.signing_key = signi...
URLUploader
python
wandb__wandb
wandb/vendor/pygments/formatters/terminal256.py
{ "start": 1155, "end": 2995 }
class ____: def __init__(self, fg=None, bg=None, bold=False, underline=False): self.fg = fg self.bg = bg self.bold = bold self.underline = underline def escape(self, attrs): if len(attrs): return "\x1b[" + ";".join(attrs) + "m" return "" def colo...
EscapeSequence
python
tensorflow__tensorflow
tensorflow/python/ops/weak_tensor_ops_test.py
{ "start": 4207, "end": 15076 }
class ____( test_util.TensorFlowTestCase, parameterized.TestCase ): # Test unary ops with one input. @parameterized.named_parameters( (api.__module__ + "." + api.__name__, api) for api in set(_TF_UNARY_APIS) - set(_TF_UNARY_APIS_WITH_MULT_INPUT) ) def test_unary_ops_return_weak_tensor(self, una...
WeakTensorUnaryOpsTest
python
doocs__leetcode
solution/0600-0699/0677.Map Sum Pairs/Solution.py
{ "start": 0, "end": 629 }
class ____: def __init__(self): self.children: List[Trie | None] = [None] * 26 self.val: int = 0 def insert(self, w: str, x: int): node = self for c in w: idx = ord(c) - ord('a') if node.children[idx] is None: node.children[idx] = Trie() ...
Trie
python
getsentry__sentry
tests/sentry/integrations/vsts/test_issues.py
{ "start": 22470, "end": 27416 }
class ____(VstsIssueBase): def setUp(self) -> None: super().setUp() responses.add( responses.GET, "https://fabrikam-fiber-inc.visualstudio.com/_apis/projects", json={ "value": [ {"id": "project-1-id", "name": "project_1"}, ...
VstsIssueFormTest
python
openai__openai-python
src/openai/types/beta/assistant.py
{ "start": 755, "end": 1074 }
class ____(BaseModel): vector_store_ids: Optional[List[str]] = None """ The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. """
ToolResourcesFileSearch
python
huggingface__transformers
src/transformers/models/phi4_multimodal/configuration_phi4_multimodal.py
{ "start": 11733, "end": 24853 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Phi4MultimodalModel`]. It is used to instantiate a Phi4Multimodal model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a...
Phi4MultimodalConfig
python
huggingface__transformers
src/transformers/models/deepseek_vl_hybrid/modeling_deepseek_vl_hybrid.py
{ "start": 10749, "end": 17614 }
class ____(DeepseekVLHybridPreTrainedModel): def __init__(self, config): super().__init__(config) self.output_size = config.vision_config.image_size // config.vision_config.patch_size self.global_attn_index = config.high_res_vision_config.global_attn_indexes[0] self.high_res_vision_...
DeepseekVLHybridModel
python
sympy__sympy
sympy/core/mod.py
{ "start": 294, "end": 8363 }
class ____(DefinedFunction): """Represents a modulo operation on symbolic expressions. Parameters ========== p : Expr Dividend. q : Expr Divisor. Notes ===== The convention used is the same as Python's: the remainder always has the same sign as the divisor. ...
Mod
python
keon__algorithms
tests/test_streaming.py
{ "start": 754, "end": 1875 }
class ____(unittest.TestCase): def test_one_sparse_correct(self): self.assertEqual(4, one_sparse([(4, '+'), (2, '+'), (2, '-'), (4, '+'), (3, '+'), (3, '-')])) self.assertEqual(2, one_sparse([(2, '+'), (2, '+'), (2, '+'), ...
TestOneSparse
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink06.py
{ "start": 346, "end": 3033 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with hyperlinks.""" workbook = Wor...
TestCompareXLSXFiles
python
streamlit__streamlit
lib/tests/streamlit/data_mocks/snowpandas_mocks.py
{ "start": 1715, "end": 2657 }
class ____: """This is dummy Series class, which imitates snowflake.snowpark.modin.pandas.series.Series class for testing purposes. We use this to make sure that our code does a special handling if it detects a Snowpark Pandas Series. This allows testing of the functionality without having the libr...
Series
python
pandas-dev__pandas
pandas/tests/test_common.py
{ "start": 5856, "end": 7742 }
class ____: def test_non_bool_array_with_na(self): # in particular, this should not raise arr = np.array(["A", "B", np.nan], dtype=object) assert not com.is_bool_indexer(arr) def test_list_subclass(self): # GH#42433 class MyList(list): pass val = My...
TestIsBoolIndexer
python
ray-project__ray
rllib/connectors/env_to_module/mean_std_filter.py
{ "start": 633, "end": 10297 }
class ____(ConnectorV2): """A connector used to mean-std-filter observations. Incoming observations are filtered such that the output of this filter is on average 0.0 and has a standard deviation of 1.0. If the observation space is a (possibly nested) dict, this filtering is applied separately per elem...
MeanStdFilter
python
instagram__MonkeyType
tests/test_tracing.py
{ "start": 1127, "end": 1798 }
class ____: @staticmethod def a_static_method() -> Optional[FrameType]: return inspect.currentframe() @classmethod def a_class_method(cls) -> Optional[FrameType]: return inspect.currentframe() def an_instance_method(self) -> Optional[FrameType]: return inspect.currentframe(...
GetFuncHelper
python
tensorflow__tensorflow
tensorflow/python/util/protobuf/compare_test.py
{ "start": 10162, "end": 12004 }
class ____(googletest.TestCase): """Tests for NormalizeNumberFields().""" def testNormalizesInts(self): pb = compare_test_pb2.Large(int64_=4) compare.NormalizeNumberFields(pb) self.assertIsInstance(pb.int64_, int) pb.int64_ = 4 compare.NormalizeNumberFields(pb) self.assertIsInstance(pb.int...
NormalizeNumbersTest
python
django__django
tests/flatpages_tests/test_sitemaps.py
{ "start": 375, "end": 1378 }
class ____(TestCase): @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() @classmethod def setUpTestData(cls): Site = apps.ge...
FlatpagesSitemapTests
python
sqlalchemy__sqlalchemy
test/orm/test_versioning.py
{ "start": 2059, "end": 4581 }
class ____(fixtures.MappedTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "version_table", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Co...
NullVersionIdTest
python
wandb__wandb
wandb/vendor/pygments/lexers/prolog.py
{ "start": 3126, "end": 12066 }
class ____(RegexLexer): """ For `Logtalk <http://logtalk.org/>`_ source code. .. versionadded:: 0.10 """ name = 'Logtalk' aliases = ['logtalk'] filenames = ['*.lgt', '*.logtalk'] mimetypes = ['text/x-logtalk'] tokens = { 'root': [ # Directives (r'^\...
LogtalkLexer
python
sanic-org__sanic
sanic/http/http3.py
{ "start": 8428, "end": 8548 }
class ____(Receiver): # noqa """Websocket receiver implementation.""" async def run(self): ...
WebsocketReceiver
python
pytorch__pytorch
torch/distributed/optim/zero_redundancy_optimizer.py
{ "start": 11183, "end": 72841 }
class ____(Optimizer, Joinable): r""" Wrap an arbitrary :class:`optim.Optimizer <torch.optim.Optimizer>` and shards its states across ranks in the group. The sharing is done as described by `ZeRO <https://arxiv.org/abs/1910.02054>`_. The local optimizer instance in each rank is only responsible fo...
ZeroRedundancyOptimizer
python
joke2k__faker
faker/providers/person/ka_GE/__init__.py
{ "start": 44, "end": 15024 }
class ____(PersonProvider): formats_male = ("{{first_name_male}} {{last_name}}",) formats_female = ("{{first_name_female}} {{last_name}}",) formats = formats_male + formats_female # Source: 2012 Voters List. # Obtained from http://mashasada.me/en/chamotvirtva first_names_male = ( "ავთა...
Provider
python
walkccc__LeetCode
solutions/650. 2 Keys Keyboard/650.py
{ "start": 0, "end": 396 }
class ____: def minSteps(self, n: int) -> int: if n <= 1: return 0 # dp[i] := the minimum steps to get i 'A's # Copy 'A', then paste 'A' i - 1 times. dp = [i for i in range(n + 1)] for i in range(2, n + 1): for j in range(i // 2, 2, -1): if i % j == 0: dp[i] = dp[j]...
Solution
python
google__jax
tests/state_test.py
{ "start": 59011, "end": 60211 }
class ____(jtu.JaxTestCase): def test_token(self): def f(x_ref): x = x_ref[...] x_ref[...] = x ref_addupdate(x_ref, (), x) return [x] jaxpr, _, _ = pe.trace_to_jaxpr_dynamic( wrap_init(f, 1), [AbstractRef(core.AbstractToken())]) self.assertIs(type(jaxpr.outvars[0].aval), c...
GeneralRefTest
python
coleifer__peewee
tests/sqlite.py
{ "start": 78736, "end": 83035 }
class ____(BaseTestCase): def setUp(self): super(TestLSM1Extension, self).setUp() if os.path.exists(KV._meta.filename): os.unlink(KV._meta.filename) database.connect() database.load_extension(LSM_EXTENSION.rstrip('.so')) def tearDown(self): super(TestLSM1Ext...
TestLSM1Extension
python
facelessuser__soupsieve
soupsieve/css_parser.py
{ "start": 13419, "end": 47223 }
class ____: """Parse CSS selectors.""" css_tokens = ( SelectorPattern("pseudo_close", PAT_PSEUDO_CLOSE), SpecialPseudoPattern( ( ( "pseudo_contains", (':contains', ':-soup-contains', ':-soup-contains-own'), ...
CSSParser
python
plotly__plotly.py
plotly/animation.py
{ "start": 80, "end": 1395 }
class ____(EnumeratedValidator): def __init__(self, plotly_name="easing", parent_name="batch_animate", **_): super(EasingValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, values=[ "linear", "quad", ...
EasingValidator
python
matplotlib__matplotlib
lib/matplotlib/_docstring.py
{ "start": 2576, "end": 4435 }
class ____: """ A class to substitute formatted placeholders in docstrings. This is realized in a single instance ``_docstring.interpd``. Use `~._ArtistPropertiesSubstition.register` to define placeholders and their substitution, e.g. ``_docstring.interpd.register(name="some value")``. Use th...
_ArtistPropertiesSubstitution
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 67823, "end": 69833 }
class ____(GeneratedAirbyteSource): class SignInViaGoogleOAuth: @public def __init__( self, client_id: str, client_secret: str, refresh_token: str, credentials_title: Optional[str] = None, ): self.credentials_title = che...
GoogleDirectorySource
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dlp.py
{ "start": 28428, "end": 33064 }
class ____(GoogleCloudBaseOperator): """ De-identifies potentially sensitive info from a content item; limits input size and output size. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDLPDeidentifyContentOperator` :pa...
CloudDLPDeidentifyContentOperator
python
FactoryBoy__factory_boy
tests/test_fuzzy.py
{ "start": 2031, "end": 3458 }
class ____(unittest.TestCase): def test_definition(self): """Tests all ways of defining a FuzzyInteger.""" fuzz = fuzzy.FuzzyInteger(2, 3) for _i in range(20): res = utils.evaluate_declaration(fuzz) self.assertIn(res, [2, 3]) fuzz = fuzzy.FuzzyInteger(4) ...
FuzzyIntegerTestCase
python
django__django
django/core/management/commands/makemigrations.py
{ "start": 962, "end": 22559 }
class ____(BaseCommand): autodetector = MigrationAutodetector help = "Creates new migration(s) for apps." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="*", help="Specify the app label(s) to create migrations...
Command
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 103292, "end": 103699 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(EnterpriseMemberOrderField), graphql_name="field" ) direction = sgqlc.types.Field( s...
EnterpriseMemberOrder
python
etianen__django-reversion
reversion/models.py
{ "start": 4652, "end": 8831 }
class ____(models.QuerySet): def get_for_model(self, model, model_db=None): model_db = model_db or router.db_for_write(model) content_type = _get_content_type(model, self.db) return self.filter( content_type=content_type, db=model_db, ) def get_for_objec...
VersionQuerySet
python
docker__docker-py
tests/unit/swarm_test.py
{ "start": 147, "end": 2150 }
class ____(BaseAPIClientTest): @requires_api_version('1.24') def test_node_update(self): node_spec = { 'Availability': 'active', 'Name': 'node-name', 'Role': 'manager', 'Labels': {'foo': 'bar'} } self.client.update_node( node_i...
SwarmTest
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-neutrino/llama_index/llms/neutrino/base.py
{ "start": 493, "end": 3042 }
class ____(OpenAILike): """ Neutrino LLM. Examples: `pip install llama-index-llms-neutrino` You can create an API key at: <a href="https://platform.neutrinoapp.com/">platform.neutrinoapp.com</a> ```python import os os.environ["NEUTRINO_API_KEY"] = "<your-neutrino-...
Neutrino
python
django-compressor__django-compressor
compressor/tests/test_storages.py
{ "start": 511, "end": 697 }
class ____(LazyObject): def _setup(self): self._wrapped = storages.create_storage({ "BACKEND": "compressor.storage.GzipCompressorFileStorage" })
GzipStorage
python
pdm-project__pdm
src/pdm/models/setup.py
{ "start": 13700, "end": 15306 }
class ____(Distribution): def __init__(self, data: Setup) -> None: self._data = data def read_text(self, filename: str) -> str | None: return None def locate_file(self, path: str | os.PathLike[str]) -> _SimplePath: return Path() @property def metadata(self) -> dict[str, An...
SetupDistribution
python
getsentry__sentry
src/sentry/integrations/coding_agent/integration.py
{ "start": 1219, "end": 1611 }
class ____(IntegrationProvider, abc.ABC): """Abstract base provider for coding agent integrations.""" @abc.abstractmethod def get_agent_name(self) -> str: """Return the name of the coding agent.""" pass @abc.abstractmethod def get_agent_key(self) -> str: """Return the uniqu...
CodingAgentIntegrationProvider
python
pytorch__pytorch
test/distributed/test_c10d_common.py
{ "start": 71122, "end": 78328 }
class ____(MultiProcessTestCase): @property def world_size(self): return 1 def setUp(self): super().setUp() self._spawn_processes() def tearDown(self): super().tearDown() try: os.remove(self.file_name) except OSError: pass de...
ProcessGroupWithDispatchedCollectivesTests
python
scipy__scipy
scipy/stats/tests/test_mgc.py
{ "start": 2340, "end": 8373 }
class ____: """ Test validity of MGC test statistic """ def setup_method(self): self.rng = np.random.default_rng(1266219746) def _simulations(self, samps=100, dims=1, sim_type="", rng=None): rng = rng or self.rng # linear simulation if sim_type == "linear": x...
TestMGCStat
python
apache__airflow
airflow-core/src/airflow/assets/evaluation.py
{ "start": 1262, "end": 2839 }
class ____: """Evaluates whether an asset-like object has been satisfied.""" _session: Session def _resolve_asset_ref(self, o: AssetRef) -> Asset | None: asset = resolve_ref_to_asset(**attrs.asdict(o), session=self._session) return asset.to_public() if asset else None def _resolve_ass...
AssetEvaluator
python
google__jax
tests/tree_util_test.py
{ "start": 36238, "end": 39124 }
class ____(absltest.TestCase): def testBasic(self): def assert_equal_and_hash_equal(a, b): self.assertEqual(a, b) self.assertEqual(hash(a), hash(b)) key = SequenceKey(idx=1) self.assertEqual(str(key), "[1]") self.assertEqual(key.idx, 1) assert_equal_and_hash_equal(key, SequenceKey(1)...
TreeKeyTest
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 4414, "end": 5816 }
class ____(nn.Module): """Performs symmetrization, apc, and computes a logistic regression on the output features""" def __init__( self, in_features: int, bias=True, eos_idx: int = 2, ): super().__init__() self.in_features = in_features self.eos_idx =...
EsmContactPredictionHead
python
google__pytype
pytype/tests/test_functions2.py
{ "start": 22092, "end": 23018 }
class ____(test_base.BaseTest): """Tests for error disabling.""" def test_invalid_parameter_annotation(self): self.Check(""" def f( x: 0 = 0 ): # pytype: disable=invalid-annotation pass """) def test_invalid_return_annotation(self): self.Check(""" def f() -> ( ...
DisableTest
python
Lightning-AI__lightning
src/lightning/pytorch/callbacks/lambda_function.py
{ "start": 784, "end": 3435 }
class ____(Callback): r"""Create a simple callback on the fly using lambda functions. Args: **kwargs: hooks supported by :class:`~lightning.pytorch.callbacks.callback.Callback` Example:: >>> from lightning.pytorch import Trainer >>> from lightning.pytorch.callbacks import LambdaCa...
LambdaCallback
python
spyder-ide__spyder
spyder/plugins/preferences/tests/conftest.py
{ "start": 2368, "end": 4958 }
class ____(QWidget): def __init__(self, parent, main_class, general_config_plugins, plugins): super().__init__(parent) self._main = main_class(self) if main_class else None if self._main is None: self._main = MainWindowMock(self) def register_plugin(self...
ConfigDialogTester