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
davidhalter__parso
test/fuzz_diff_parser.py
{ "start": 7799, "end": 11338 }
class ____: def __init__(self, file_path, test_count, change_count): self._path = file_path with open(file_path, errors='replace') as f: code = f.read() self._code_lines = split_lines(code, keepends=True) self._test_count = test_count self._code_lines = self._code...
FileTests
python
matplotlib__matplotlib
lib/matplotlib/backend_bases.py
{ "start": 43368, "end": 43450 }
class ____(Event): """An event triggered by a figure being closed."""
CloseEvent
python
weaviate__weaviate-python-client
weaviate/backup/executor.py
{ "start": 867, "end": 24321 }
class ____(Generic[ConnectionType]): def __init__(self, connection: Connection): self._connection = connection def create( self, backup_id: str, backend: BackupStorage, include_collections: Union[List[str], str, None] = None, exclude_collections: Union[List[str],...
_BackupExecutor
python
great-expectations__great_expectations
great_expectations/render/renderer_configuration.py
{ "start": 1338, "end": 2299 }
class ____(str, Enum): """Type used in renderer param json schema dictionary.""" ARRAY = "array" BOOLEAN = "boolean" DATETIME = "datetime" NUMBER = "number" OBJECT = "object" STRING = "string" @classmethod def from_value(cls, value: Any) -> RendererValueType: # noqa: PLR0911 ...
RendererValueType
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-cleanlab/llama_index/llms/cleanlab/base.py
{ "start": 799, "end": 4138 }
class ____(CustomLLM): """ Cleanlab TLM. Examples: `pip install llama-index-llms-cleanlab` ```python from llama_index.llms.cleanlab import CleanlabTLM llm = CleanlabTLM(api_key=api_key, quality_preset="best", options={"log": ["explanation"]}) resp = llm.complete("W...
CleanlabTLM
python
numpy__numpy
numpy/_core/tests/test_casting_unittests.py
{ "start": 5616, "end": 40941 }
class ____: size = 1500 # Best larger than NPY_LOWLEVEL_BUFFER_BLOCKSIZE * itemsize def get_data(self, dtype1, dtype2): if dtype2 is None or dtype1.itemsize >= dtype2.itemsize: length = self.size // dtype1.itemsize else: length = self.size // dtype2.itemsize # ...
TestCasting
python
doocs__leetcode
solution/2700-2799/2786.Visit Array Positions to Maximize Score/Solution.py
{ "start": 0, "end": 236 }
class ____: def maxScore(self, nums: List[int], x: int) -> int: f = [-inf] * 2 f[nums[0] & 1] = nums[0] for v in nums[1:]: f[v & 1] = max(f[v & 1], f[v & 1 ^ 1] - x) + v return max(f)
Solution
python
walkccc__LeetCode
solutions/200. Number of Islands/200.py
{ "start": 0, "end": 720 }
class ____: def numIslands(self, grid: list[list[str]]) -> int: DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) def bfs(r, c): q = collections.deque([(r, c)]) grid[r][c] = '2' # Mark '2' as visited. while q: i, j = q.popleft() for dx, dy in ...
Solution
python
pandas-dev__pandas
pandas/io/pytables.py
{ "start": 68951, "end": 79633 }
class ____: """ an index column description class Parameters ---------- axis : axis which I reference values : the ndarray like converted values kind : a string description of this type typ : the pytables type pos : the position in the pytables """ is_an_indexabl...
IndexCol
python
sympy__sympy
sympy/physics/continuum_mechanics/arch.py
{ "start": 574, "end": 39243 }
class ____: """ This class is used to solve problems related to a three hinged arch(determinate) structure.\n An arch is a curved vertical structure spanning an open space underneath it.\n Arches can be used to reduce the bending moments in long-span structures.\n Arches are used in structural engi...
Arch
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-convert-all-elements-to-zero.py
{ "start": 50, "end": 416 }
class ____(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 stk = [0] for x in nums: while stk and stk[-1] > x: stk.pop() if stk[-1] < x: result += 1 ...
Solution
python
pennersr__django-allauth
tests/apps/account/test_auth_backends.py
{ "start": 284, "end": 3601 }
class ____(TestCase): def setUp(self): user = get_user_model().objects.create( is_active=True, email="john@example.com", username="john" ) user.set_password(user.username) user.save() self.user = user @override_settings( ACCOUNT_LOGIN_METHODS={app_set...
AuthenticationBackendTests
python
kamyu104__LeetCode-Solutions
Python/max-chunks-to-make-sorted-ii.py
{ "start": 543, "end": 1021 }
class ____(object): def maxChunksToSorted(self, arr): """ :type arr: List[int] :rtype: int """ def compare(i1, i2): return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2 idxs = [i for i in xrange(len(arr))] result, max_i = 0, 0 for i, v ...
Solution2
python
kamyu104__LeetCode-Solutions
Python/min-cost-climbing-stairs.py
{ "start": 29, "end": 333 }
class ____(object): def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ dp = [0] * 3 for i in reversed(xrange(len(cost))): dp[i%3] = cost[i] + min(dp[(i+1)%3], dp[(i+2)%3]) return min(dp[0], dp[1])
Solution
python
optuna__optuna
optuna/_gp/acqf.py
{ "start": 6881, "end": 7305 }
class ____(BaseAcquisitionFunc): def __init__( self, gpr: GPRegressor, search_space: SearchSpace, beta: float, ) -> None: self._gpr = gpr self._beta = beta super().__init__(gpr.length_scales, search_space) def eval_acqf(self, x: torch.Tensor) -> torch...
LCB
python
keras-team__keras
keras/src/optimizers/adafactor.py
{ "start": 193, "end": 8418 }
class ____(optimizer.Optimizer): """Optimizer that implements the Adafactor algorithm. Adafactor is commonly used in NLP tasks, and has the advantage of taking less memory because it only saves partial information of previous gradients. The default argument setup is based on the original paper (se...
Adafactor
python
apache__airflow
airflow-core/src/airflow/lineage/hook.py
{ "start": 2501, "end": 3022 }
class ____: """ Holds lineage collected by HookLineageCollector. This class represents the lineage information collected by the `HookLineageCollector`. It stores the input and output assets, each with an associated count indicating how many times the asset has been encountered during the hook execu...
HookLineage
python
Netflix__metaflow
metaflow/runner/deployer.py
{ "start": 16522, "end": 17138 }
class ____(metaclass=DeployedFlowMeta): """ DeployedFlow class represents a flow that has been deployed. This class is not meant to be instantiated directly. Instead, it is returned from methods of `Deployer`. """ # This should match the TYPE value in DeployerImpl for proper stub generation ...
DeployedFlow
python
Netflix__metaflow
metaflow/plugins/azure/azure_secret_manager_secrets_provider.py
{ "start": 762, "end": 895 }
class ____(MetaflowException): """Raised when the secret name does not match expected pattern"""
MetaflowAzureKeyVaultBadSecretName
python
pytorch__pytorch
test/inductor/test_lookup_table.py
{ "start": 2822, "end": 5862 }
class ____(TestCase): """Base class for lookup table tests with common setup and utilities""" def setUp(self): super().setUp() self.original_table = inductor_config.lookup_table.table self.original_max_autotune = getattr(inductor_config, "max_autotune", False) inductor_config.ma...
BaseLookupTableTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis20.py
{ "start": 315, "end": 1455 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis20.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
pyca__cryptography
tests/hazmat/primitives/test_aead.py
{ "start": 26979, "end": 36292 }
class ____: @pytest.mark.skipif( sys.platform not in {"linux", "darwin"} or sys.maxsize < 2**31, reason="mmap and 64-bit platform required", ) def test_data_too_large(self): key = AESOCB3.generate_key(128) aesocb3 = AESOCB3(key) nonce = b"0" * 12 large_data =...
TestAESOCB3
python
allegroai__clearml
clearml/backend_api/services/v2_9/projects.py
{ "start": 79858, "end": 81004 }
class ____(Response): """ Response of projects.make_private endpoint. :param updated: Number of projects updated :type updated: int """ _service = "projects" _action = "make_private" _version = "2.9" _schema = { "definitions": {}, "properties": { "update...
MakePrivateResponse
python
doocs__leetcode
solution/2700-2799/2733.Neither Minimum nor Maximum/Solution.py
{ "start": 0, "end": 175 }
class ____: def findNonMinOrMax(self, nums: List[int]) -> int: mi, mx = min(nums), max(nums) return next((x for x in nums if x != mi and x != mx), -1)
Solution
python
facebook__pyre-check
client/commands/commands.py
{ "start": 338, "end": 938 }
class ____(enum.IntEnum): SUCCESS = 0 FOUND_ERRORS = 1 FAILURE = 2 BUCK_INTERNAL_ERROR = 3 SERVER_NOT_FOUND = 4 INCONSISTENT_SERVER = 5 CONFIGURATION_ERROR = 6 BUCK_USER_ERROR = 7 WATCHMAN_ERROR = 8 TAINT_CONFIGURATION_ERROR = 9 MODEL_VERIFICATION_ERROR = 10 UNSUPPORTED_P...
ExitCode
python
cython__cython
Demos/benchmarks/bm_raytrace.py
{ "start": 3922, "end": 4368 }
class ____(object): def __init__(self, point, normal): self.point = point self.normal = normal.normalized() def __repr__(self): return 'Halfspace(%s,%s)' % (repr(self.point), repr(self.normal)) def intersectionTime(self, ray): v = ray.vector.dot(self.normal) if v: ...
Halfspace
python
milvus-io__pymilvus
pymilvus/client/prepare.py
{ "start": 1545, "end": 96866 }
class ____: @classmethod def create_collection_request( cls, collection_name: str, fields: Union[Dict[str, Iterable], CollectionSchema], **kwargs, ) -> milvus_types.CreateCollectionRequest: """ Args: fields (Union(Dict[str, Iterable], CollectionSch...
Prepare
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 22177, "end": 24691 }
class ____(BaseTest): """ Test calling convention of floating point arguments of RISC-V using different ABI. """ triple = "riscv32-unknown-linux" def setUp(self): super().setUp() llvm.initialize_all_targets() llvm.initialize_all_asmprinters() def check_riscv_target(...
TestRISCVABI
python
dask__distributed
distributed/client.py
{ "start": 21129, "end": 21214 }
class ____(Exception): """Custom exception class to exit All(...) early."""
AllExit
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 13959, "end": 15501 }
class ____(rv_continuous): r"""An alpha continuous random variable. %(before_notes)s Notes ----- The probability density function for `alpha` ([1]_, [2]_) is: .. math:: f(x, a) = \frac{1}{x^2 \Phi(a) \sqrt{2\pi}} * \exp(-\frac{1}{2} (a-1/x)^2) where :math:`\Phi...
alpha_gen
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/serializers/action_serializer.py
{ "start": 303, "end": 470 }
class ____(TypedDict): id: str type: str integrationId: str | None data: dict config: dict status: str @register(Action)
ActionSerializerResponse
python
pytorch__pytorch
test/distributed/test_c10d_ucc.py
{ "start": 4054, "end": 11405 }
class ____(MultiProcessTestCase): def _create_process_group_ucc(self): store = c10d.FileStore(self.file_name, self.world_size) return c10d.ProcessGroupUCC(store, self.rank, self.world_size) def setUp(self): super().setUp() self._spawn_processes() def tearDown(self): ...
ProcessGroupUCCTest
python
py-pdf__pypdf
pypdf/annotations/_non_markup_annotations.py
{ "start": 2692, "end": 3649 }
class ____(AnnotationDictionary): def __init__( self, *, rect: Union[RectangleObject, tuple[float, float, float, float]], parent: Optional[DictionaryObject] = None, open: bool = False, **kwargs: Any, ) -> None: super().__init__(**kwargs) self.updat...
Popup
python
spack__spack
lib/spack/spack/llnl/util/filesystem.py
{ "start": 76581, "end": 95079 }
class ____(FileList): """Sequence of absolute paths to libraries Provides a few convenience methods to manipulate library paths and get commonly used compiler flags or names """ @property def libraries(self) -> List[str]: """Stable de-duplication of library files. Returns: ...
LibraryList
python
google__jax
tests/stax_test.py
{ "start": 1696, "end": 8198 }
class ____(jtu.JaxTestCase): @jtu.sample_product(shape=[(2, 3), (5,)]) def testRandnInitShape(self, shape): key = random.PRNGKey(0) out = stax.randn()(key, shape) self.assertEqual(out.shape, shape) @jtu.sample_product(shape=[(2, 3), (2, 3, 4)]) def testGlorotInitShape(self, shape): key = rando...
StaxTest
python
django__django
tests/foreign_object/models/article.py
{ "start": 2836, "end": 3057 }
class ____(models.Model): article = models.ForeignKey( Article, models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255)
ArticleTag
python
lxml__lxml
src/lxml/tests/test_xpathevaluator.py
{ "start": 19703, "end": 20829 }
class ____(HelperTestCase): "Tests for the EXSLT support in XPath (requires libxslt 1.1.25+)" NSMAP = dict( date = "http://exslt.org/dates-and-times", math = "http://exslt.org/math", set = "http://exslt.org/sets", str = "http://exslt.org/strings", ) def test_xpath...
ETreeXPathExsltTestCase
python
weaviate__weaviate-python-client
weaviate/collections/backups/async_.py
{ "start": 188, "end": 271 }
class ____(_CollectionBackupExecutor[ConnectionAsync]): pass
_CollectionBackupAsync
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 118387, "end": 120514 }
class ____(LogitsProcessor): r"""This processor ensures that the EOS token is selected if its probability is greater than the `min_eos_p`. <Tip warning={true}> This logits processor is exclusively compatible with [Bark](https://huggingface.co/docs/transformers/en/model_doc/bark). See the model documen...
BarkEosPrioritizerLogitsProcessor
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 28606, "end": 37751 }
class ____(VariableTracker): """represents a torch.autograd.Function subclass""" _nonvar_fields = { "fn_cls", *VariableTracker._nonvar_fields, } def __init__(self, fn_cls, **kwargs) -> None: super().__init__(**kwargs) self.fn_cls = fn_cls def call_apply(self, tx: "...
AutogradFunctionVariable
python
pytest-dev__pytest
src/_pytest/_code/code.py
{ "start": 48240, "end": 51344 }
class ____(TerminalRepr): lines: Sequence[str] reprfuncargs: ReprFuncArgs | None reprlocals: ReprLocals | None reprfileloc: ReprFileLocation | None style: TracebackStyle def _write_entry_lines(self, tw: TerminalWriter) -> None: """Write the source code portions of a list of traceback en...
ReprEntry
python
rushter__MLAlgorithms
mla/svm/kernerls.py
{ "start": 74, "end": 214 }
class ____(object): def __call__(self, x, y): return np.dot(x, y.T) def __repr__(self): return "Linear kernel"
Linear
python
openai__openai-python
src/openai/types/beta/realtime/realtime_connect_params.py
{ "start": 212, "end": 290 }
class ____(TypedDict, total=False): model: Required[str]
RealtimeConnectParams
python
conda__conda
conda/exceptions.py
{ "start": 6406, "end": 7579 }
class ____(ClobberError): def __init__( self, target_path: PathType, colliding_dist_being_linked: PackageRecord | str, colliding_linked_dist: PackageRecord | str, context: Context, ): message = dals( """ The package '%(colliding_dist_being_link...
KnownPackageClobberError
python
pandas-dev__pandas
asv_bench/benchmarks/io/hdf.py
{ "start": 154, "end": 3302 }
class ____(BaseIO): def setup(self): N = 25000 index = Index([f"i-{i}" for i in range(N)], dtype=object) self.df = DataFrame( {"float1": np.random.randn(N), "float2": np.random.randn(N)}, index=index ) self.df_mixed = DataFrame( { "floa...
HDFStoreDataFrame
python
coleifer__peewee
playhouse/postgres_ext.py
{ "start": 3098, "end": 3342 }
class ____(_JsonLookupBase): def __sql__(self, ctx): return (ctx .sql(self.node) .literal('#>' if self._as_json else '#>>') .sql(Value('{%s}' % ','.join(map(str, self.parts)))))
JsonPath
python
PrefectHQ__prefect
tests/utilities/test_hashing.py
{ "start": 2011, "end": 2928 }
class ____: def test_hash_objects_handles_unhashable_objects_gracefully(self): """Test that unhashable objects return None by default""" lock = threading.Lock() result = hash_objects({"data": "hello", "lock": lock}) assert result is None def test_hash_objects_raises_with_helpful...
TestHashObjects
python
django__django
tests/template_tests/test_origin.py
{ "start": 111, "end": 1111 }
class ____(TestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_origin_compares_equal(self): a = self.engine.get_template("index.html") b = self.engine.get_template("index.html") self.assertEqual(a.origin, b.origin) # Use assertIs() to test __eq...
OriginTestCase
python
pennersr__django-allauth
allauth/socialaccount/providers/saml/views.py
{ "start": 6329, "end": 7147 }
class ____(SAMLViewMixin, View): def dispatch(self, request, organization_slug): provider = self.get_provider(organization_slug) config = build_saml_config( self.request, provider.app.settings, organization_slug ) saml_settings = OneLogin_Saml2_Settings( setti...
MetadataView
python
pypa__pip
src/pip/_vendor/idna/codec.py
{ "start": 2880, "end": 2939 }
class ____(Codec, codecs.StreamWriter): pass
StreamWriter
python
getsentry__sentry
src/sentry/utils/circuit_breaker2.py
{ "start": 1158, "end": 2319 }
class ____(TypedDict): # The number of errors within the given time period necessary to trip the breaker error_limit: int # The time period, in seconds, over which we're tracking errors error_limit_window: int # How long, in seconds, to stay in the BROKEN state (blocking all requests) before enterin...
CircuitBreakerConfig
python
ray-project__ray
rllib/examples/_old_api_stack/models/action_mask_model.py
{ "start": 484, "end": 2416 }
class ____(TFModelV2): """Model that handles simple discrete action masking. This assumes the outputs are logits for a single Categorical action dist. Getting this to work with a more complex output (e.g., if the action space is a tuple of several distributions) is also possible but left as an exer...
ActionMaskModel
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/mapped_collection.py
{ "start": 11817, "end": 19727 }
class ____(Dict[_KT, _VT]): """Base for ORM mapped dictionary classes. Extends the ``dict`` type with additional methods needed by SQLAlchemy ORM collection classes. Use of :class:`_orm.KeyFuncDict` is most directly by using the :func:`.attribute_keyed_dict` or :func:`.column_keyed_dict` class fact...
KeyFuncDict
python
pytorch__pytorch
benchmarks/dynamo/genai_layers/kernels.py
{ "start": 9062, "end": 11426 }
class ____(BenchmarkKernel): def __init__(self, script_args): super().__init__(script_args) self.available_backends = ["eager", "compiled", "quack", "liger"] def get_shapes(self) -> tuple[tuple[int, ...], ...]: return ( (32768, 256), (32768, 512), (32...
SoftmaxBackward
python
google__jax
tests/pallas/mosaic_gpu_test.py
{ "start": 213455, "end": 213559 }
class ____( ExamplesTest, lowering_semantics=plgpu.LoweringSemantics.Warpgroup ): ...
ExamplesWGTest
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_task_instances.py
{ "start": 95465, "end": 97273 }
class ____: def setup_method(self): clear_db_runs() def teardown_method(self): clear_db_runs() def test_ti_patch_rendered_map_index(self, client, session, create_task_instance): """Test updating rendered_map_index for a task instance.""" ti = create_task_instance( ...
TestTIPatchRenderedMapIndex
python
tornadoweb__tornado
tornado/test/gen_test.py
{ "start": 22437, "end": 28117 }
class ____(AsyncTestCase): @gen_test def test_empty_iterator(self): g = gen.WaitIterator() self.assertTrue(g.done(), "empty generator iterated") with self.assertRaises(ValueError): g = gen.WaitIterator(Future(), bar=Future()) self.assertIsNone(g.current_index, "bad ...
WaitIteratorTest
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/supervisor.py
{ "start": 60661, "end": 81972 }
class ____(ActivitySubprocess): """A supervisor that runs tasks in-process for easier testing.""" comms: InProcessSupervisorComms = attrs.field(init=False) stdin: socket = attrs.field(init=False) class _Client(Client): def request(self, *args, **kwargs): # Bypass the tenacity retr...
InProcessTestSupervisor
python
conda__conda
conda/exceptions.py
{ "start": 14730, "end": 14888 }
class ____(CondaError, OSError): def __init__(self, message: str, **kwargs): msg = f"{message}" super().__init__(msg, **kwargs)
CondaOSError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 285176, "end": 285491 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("Discussion", graphql_name="node")
DiscussionEdge
python
eth-brownie__brownie
tests/test_expansion.py
{ "start": 80, "end": 2505 }
class ____(unittest.TestCase): def setUp(self): self.v = str(uuid.uuid4()) self.input = { "non": "b", "simple": "${FOO}", "partial": "the ${FOO}", "number": 1, "bool": True, "nested": { "one": "nest ${FOO}", ...
TestExpandDict
python
apache__airflow
airflow-core/tests/unit/models/test_xcom.py
{ "start": 17882, "end": 19988 }
class ____: @pytest.mark.parametrize( ("value", "expected_value"), [ pytest.param(1, 1, id="int"), pytest.param(1.0, 1.0, id="float"), pytest.param("string", "string", id="str"), pytest.param(True, True, id="bool"), pytest.param({"key": "va...
TestXComRoundTrip
python
tensorflow__tensorflow
tensorflow/python/framework/tensor_shape_test.py
{ "start": 1093, "end": 10304 }
class ____(test_util.TensorFlowTestCase): def testDimension(self): dim = tensor_shape.Dimension(12) self.assertEqual(12, dim.value) self.assertEqual(12, int(dim)) self.assertEqual(dim, tensor_shape.Dimension(12)) self.assertEqual( tensor_shape.Dimension(15), dim + tensor_shape.Dimension(3...
DimensionTest
python
ray-project__ray
python/ray/llm/_internal/common/utils/cloud_filesystem/gcs_filesystem.py
{ "start": 473, "end": 2752 }
class ____(BaseCloudFileSystem): """GCS-specific implementation of cloud filesystem operations. **Note**: This implementation currently delegates to PyArrowFileSystem to maintain stability. Optimized implementation using google-cloud-storage SDK and gsutil will be added in a future PR. """ @st...
GCSFileSystem
python
plotly__plotly.py
plotly/graph_objs/layout/coloraxis/colorbar/_tickformatstop.py
{ "start": 235, "end": 8562 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.coloraxis.colorbar" _path_str = "layout.coloraxis.colorbar.tickformatstop" _valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"} @property def dtickrange(self): """ range [*min*, *max*], whe...
Tickformatstop
python
doocs__leetcode
lcof/面试题16. 数值的整数次方/Solution.py
{ "start": 0, "end": 333 }
class ____: def myPow(self, x: float, n: int) -> float: def qpow(a: float, n: int) -> float: ans = 1 while n: if n & 1: ans *= a a *= a n >>= 1 return ans return qpow(x, n) if n >= 0 else 1 / qpo...
Solution
python
ray-project__ray
python/ray/serve/llm/__init__.py
{ "start": 1807, "end": 12794 }
class ____(_OpenAiIngress): pass ########## # Builders ########## @PublicAPI(stability="alpha") def build_llm_deployment( llm_config: "LLMConfig", *, name_prefix: Optional[str] = None, bind_kwargs: Optional[dict] = None, override_serve_options: Optional[dict] = None, deployment_cls: Opti...
LLMRouter
python
donnemartin__interactive-coding-challenges
arrays_strings/compress_alt/test_compress.py
{ "start": 18, "end": 603 }
class ____(unittest.TestCase): def test_compress(self, func): self.assertEqual(func(None), None) self.assertEqual(func(''), '') self.assertEqual(func('AABBCC'), 'AABBCC') self.assertEqual(func('AAABCCDDDD'), 'A3BCCD4') self.assertEqual( func('aaBCCEFFFFKKMMMMMMP ...
TestCompress
python
docker__docker-py
tests/unit/utils_json_stream_test.py
{ "start": 82, "end": 589 }
class ____: def test_json_splitter_no_object(self): data = '{"foo": "bar' assert json_splitter(data) is None def test_json_splitter_with_object(self): data = '{"foo": "bar"}\n \n{"next": "obj"}' assert json_splitter(data) == ({'foo': 'bar'}, '{"next": "obj"}') def test_js...
TestJsonSplitter
python
pytorch__pytorch
test/distributed/tensor/test_op_strategy.py
{ "start": 6063, "end": 19402 }
class ____(DTensorOpTestBase): @property def world_size(self) -> int: return 4 def test_redistribute_cost_mesh_1d(self): mesh_1d = self.build_device_mesh() shard_placement = (Shard(0),) replica_placement = (Replicate(),) partial_placement = (Partial(),) glob...
TestCostModel
python
matplotlib__matplotlib
lib/matplotlib/figure.py
{ "start": 2201, "end": 3775 }
class ____: """ Helper class to track Axes in a figure. Axes are tracked both in the order in which they have been added (``self._axes`` insertion/iteration order) and in the separate "gca" stack (which is the index to which they map in the ``self._axes`` dict). """ def __init__(self): ...
_AxesStack
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 502, "end": 661 }
class ____(list[T_co]): pass # This should generate an error because the type parameter for list # is invariant, so T_co here cannot be contravariant.
Class1
python
jazzband__django-simple-history
simple_history/tests/tests/test_utils.py
{ "start": 14029, "end": 14600 }
class ____(TestCase): def setUp(self): self.data = [ BulkCreateManyToManyModel(name="Object 1"), BulkCreateManyToManyModel(name="Object 2"), BulkCreateManyToManyModel(name="Object 3"), BulkCreateManyToManyModel(name="Object 4"), BulkCreateManyToMan...
BulkCreateWithManyToManyField
python
tensorflow__tensorflow
tensorflow/python/framework/type_spec.py
{ "start": 25339, "end": 29104 }
class ____(object, metaclass=abc.ABCMeta): """Class used to encode and decode composite tensor values for batching. In order to be batched and unbatched by APIs such as `tf.data.Dataset` and `tf.map_fn`, composite tensors must be encoded using flat tensors that can themselves be batched or unbatched. `TypeSpe...
TypeSpecBatchEncoder
python
vyperlang__vyper
vyper/venom/analysis/mem_ssa.py
{ "start": 2997, "end": 16480 }
class ____(IRAnalysis): """ This analysis converts memory/storage operations into Memory SSA form. The analysis is based on LLVM's https://llvm.org/docs/MemorySSA.html. Notably, the LLVM design does not partition memory into ranges. Rather, it keeps track of memory _states_ (each write increments a ...
MemSSAAbstract
python
great-expectations__great_expectations
great_expectations/datasource/fluent/fabric.py
{ "start": 8884, "end": 14661 }
class ____(Datasource): """ Microsoft Fabric Datasource. https://pypi.org/project/semantic-link/ """ # class var definitions asset_types: ClassVar[List[Type[DataAsset]]] = [ PowerBIDax, PowerBIMeasure, PowerBITable, ] # any fabric datsource specific fields shoul...
FabricPowerBIDatasource
python
pola-rs__polars
py-polars/tests/unit/io/database/test_write.py
{ "start": 1035, "end": 11565 }
class ____: """Database write tests that share common pytest/parametrize options.""" @staticmethod def _get_connection(uri: str, engine: DbWriteEngine, uri_connection: bool) -> Any: if uri_connection: return uri elif engine == "sqlalchemy": return create_engine(uri) ...
TestWriteDatabase
python
spack__spack
lib/spack/spack/solver/core.py
{ "start": 9057, "end": 9901 }
class ____: """Tracks context in which a Spec's clause-set is generated (i.e. with ``SpackSolverSetup.spec_clauses``). Facts generated for the spec may include this context. """ def __init__(self, *, source: Optional[str] = None): # This can be "literal" for constraints that come from a us...
SourceContext
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 8204, "end": 9046 }
class ____(Hardtanh): r"""Applies the ReLU6 function element-wise. .. math:: \text{ReLU6}(x) = \min(\max(0,x), 6) Args: inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(*)`, where :math:`*` means any number of dimensions. - ...
ReLU6
python
doocs__leetcode
solution/0700-0799/0746.Min Cost Climbing Stairs/Solution3.py
{ "start": 0, "end": 214 }
class ____: def minCostClimbingStairs(self, cost: List[int]) -> int: f = g = 0 for i in range(2, len(cost) + 1): f, g = g, min(f + cost[i - 2], g + cost[i - 1]) return g
Solution
python
getsentry__sentry
tests/sentry/sentry_apps/web/test_sentryapp_avatar.py
{ "start": 353, "end": 1191 }
class ____(APITestCase): def test_headers_control_file(self) -> None: sentry_app = self.create_sentry_app(name="Meow", organization=self.organization) photo = ControlFile.objects.create(name="test.png", type="avatar.file") photo.putfile(BytesIO(b"test")) avatar = SentryAppAvatar.obje...
SentryAppAvatarTest
python
PyCQA__pylint
pylint/checkers/utils.py
{ "start": 15689, "end": 15801 }
class ____(Exception): """A format string ended in the middle of a format specifier."""
IncompleteFormatString
python
PyCQA__pylint
tests/functional/i/invalid/invalid_format_returned.py
{ "start": 195, "end": 331 }
class ____: """__format__ returns <type 'str'>""" def __format__(self, format_spec): return "some format"
FirstGoodFormat
python
altair-viz__altair
tests/utils/test_schemapi.py
{ "start": 4583, "end": 41128 }
class ____(_TestSchema): _schema = { **_validation_selection_schema, "$schema": "http://json-schema.org/draft-06/schema#", } def test_construct_multifaceted_schema(): dct = { "a": {"foo": "bar"}, "a2": {"foo": 42}, "b": ["a", "b", "c"], "b2": [1, 2, 3], ...
Draft6Schema
python
lazyprogrammer__machine_learning_examples
tf2.0/keras_trader.py
{ "start": 2784, "end": 6632 }
class ____: """ A 3-stock trading environment. State: vector of size 7 (n_stock * 2 + 1) - # shares of stock 1 owned - # shares of stock 2 owned - # shares of stock 3 owned - price of stock 1 (using daily close price) - price of stock 2 - price of stock 3 - cash owned (can be used to p...
MultiStockEnv
python
Pylons__pyramid
tests/test_authentication.py
{ "start": 67873, "end": 68048 }
class ____: def remember(self, environ, identity): return environ, identity def forget(self, environ, identity): return environ, identity
DummyWhoPlugin
python
python-poetry__poetry
src/poetry/repositories/pypi_repository.py
{ "start": 1216, "end": 8410 }
class ____(HTTPRepository): def __init__( self, url: str = "https://pypi.org/", *, config: Config | None = None, disable_cache: bool = False, pool_size: int = requests.adapters.DEFAULT_POOLSIZE, fallback: bool = True, ) -> None: super().__init__( ...
PyPiRepository
python
pandas-dev__pandas
pandas/tests/arrays/test_datetimelike.py
{ "start": 31421, "end": 35927 }
class ____(SharedTests): index_cls = TimedeltaIndex array_cls = TimedeltaArray scalar_type = pd.Timedelta example_dtype = "m8[ns]" def test_from_tdi(self): tdi = TimedeltaIndex(["1 Day", "3 Hours"]) arr = tdi._data assert list(arr) == list(tdi) # Check that Index.__...
TestTimedeltaArray
python
huggingface__transformers
src/transformers/models/convbert/modeling_convbert.py
{ "start": 1460, "end": 4255 }
class ____(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id) self.position_embeddings = n...
ConvBertEmbeddings
python
sympy__sympy
sympy/physics/quantum/density.py
{ "start": 679, "end": 9546 }
class ____(HermitianOperator): """Density operator for representing mixed states. TODO: Density operator support for Qubits Parameters ========== values : tuples/lists Each tuple/list should be of form (state, prob) or [state,prob] Examples ======== Create a density operator wit...
Density
python
ansible__ansible
hacking/create-bulk-issues.py
{ "start": 1614, "end": 3257 }
class ____: title: str summary: str component: str labels: list[str] | None = None assignee: str | None = None @staticmethod def from_dict(data: dict[str, t.Any]) -> Feature: title = data.get('title') summary = data.get('summary') component = data.get('component') ...
Feature
python
python-pillow__Pillow
src/PIL/ImageWin.py
{ "start": 6685, "end": 7590 }
class ____: """Create a Window with the given title size.""" def __init__( self, title: str = "PIL", width: int | None = None, height: int | None = None ) -> None: self.hwnd = Image.core.createwindow( title, self.__dispatcher, width or 0, height or 0 ) def __dispatc...
Window
python
pandas-dev__pandas
asv_bench/benchmarks/stat_ops.py
{ "start": 3288, "end": 4380 }
class ____: params = [["spearman", "kendall", "pearson"]] param_names = ["method"] def setup(self, method): self.df = pd.DataFrame(np.random.randn(500, 15)) self.df2 = pd.DataFrame(np.random.randn(500, 15)) self.df_wide = pd.DataFrame(np.random.randn(500, 100)) self.df_wide_...
Correlation
python
langchain-ai__langchain
libs/partners/openai/langchain_openai/middleware/openai_moderation.py
{ "start": 1434, "end": 15399 }
class ____(AgentMiddleware[AgentState[Any], Any]): """Moderate agent traffic using OpenAI's moderation endpoint.""" def __init__( self, *, model: ModerationModel = "omni-moderation-latest", check_input: bool = True, check_output: bool = True, check_tool_results: ...
OpenAIModerationMiddleware
python
redis__redis-py
tests/test_retry.py
{ "start": 5737, "end": 10410 }
class ____: "Test the standalone Redis client behavior with retries" def test_client_retry_on_error_with_success(self, request): with patch.object(Redis, "parse_response") as parse_response: def mock_parse_response(connection, *args, **options): def ok_response(connection, ...
TestRedisClientRetry
python
getsentry__sentry
src/sentry/plugins/base/binding_manager.py
{ "start": 619, "end": 701 }
class ____(ProviderManager): type = RepositoryProvider
RepositoryProviderManager
python
huggingface__transformers
src/transformers/models/chinese_clip/modeling_chinese_clip.py
{ "start": 27127, "end": 28744 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList([ChineseCLIPTextLayer(config) for i in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @can_return_tuple def forward( self, ...
ChineseCLIPTextEncoder
python
pytorch__pytorch
torch/utils/weak.py
{ "start": 2691, "end": 4269 }
class ____(weakref.ref): __slots__ = ["_id"] def __init__(self, key, callback=None) -> None: # Unlike stock weakref, which preserves hash semantics of the # original object but lazily defers hash calls until the first # time the user attempts to hash the weakref, we can eagerly ...
WeakIdRef
python
getsentry__sentry
src/sentry/utils/snuba_rpc.py
{ "start": 2091, "end": 2452 }
class ____: table_response: list[TraceItemTableResponse] timeseries_response: list[TimeSeriesResponse] def log_snuba_info(content: str) -> None: if SNUBA_INFO_FILE: with open(SNUBA_INFO_FILE, "a") as file: file.writelines(content) else: print(content) # NOQA: only prints w...
MultiRpcResponse
python
Netflix__metaflow
metaflow/plugins/airflow/airflow_utils.py
{ "start": 699, "end": 1099 }
class ____(Exception): headline = "Metaflow is incompatible with current version of Airflow." def __init__(self, version_number) -> None: msg = ( "Airflow version %s is incompatible with Metaflow. Metaflow requires Airflow a minimum version %s" % (version_number, AIRFLOW_MIN_SUP...
IncompatibleVersionException