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
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/kubernetes_engine.py
{ "start": 15883, "end": 18041 }
class ____(GoogleBaseHook, KubernetesHook): """ GKE authenticated hook for standard Kubernetes API. This hook provides full set of the standard Kubernetes API provided by the KubernetesHook, and at the same time it provides a GKE authentication, so it makes it possible to KubernetesHook functionali...
GKEKubernetesHook
python
apache__airflow
airflow-core/src/airflow/timetables/trigger.py
{ "start": 2351, "end": 4776 }
class ____(Timetable): _interval: datetime.timedelta | relativedelta def infer_manual_data_interval(self, *, run_after: DateTime) -> DataInterval: return DataInterval( coerce_datetime(run_after - self._interval), run_after, ) def _calc_first_run(self) -> DateTime: ...
_TriggerTimetable
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_polymorphic_rel.py
{ "start": 64394, "end": 69337 }
class ____(_PolymorphicTestBase, _Polymorphic): def test_joined_aliasing_unrelated_subuqery(self): """test #8456""" inner = select(Engineer).where(Engineer.name == "vlad").subquery() crit = select(inner.c.person_id) outer = select(Engineer).where(Engineer.person_id.in_(crit)) ...
PolymorphicTest
python
django__django
tests/utils_tests/test_csp.py
{ "start": 967, "end": 4902 }
class ____(SimpleTestCase): def assertPolicyEqual(self, a, b): parts_a = sorted(a.split("; ")) if a is not None else None parts_b = sorted(b.split("; ")) if b is not None else None self.assertEqual(parts_a, parts_b, f"Policies not equal: {a!r} != {b!r}") def test_config_empty(self): ...
CSPBuildPolicyTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1587386, "end": 1587558 }
class ____(sgqlc.types.Union): """Types that can own an IP allow list.""" __schema__ = github_schema __types__ = (App, Enterprise, Organization)
IpAllowListOwner
python
tiangolo__fastapi
docs_src/schema_extra_example/tutorial002.py
{ "start": 111, "end": 517 }
class ____(BaseModel): name: str = Field(examples=["Foo"]) description: Union[str, None] = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: Union[float, None] = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") async def update_item(item_id: ...
Item
python
numba__numba
numba/core/datamodel/models.py
{ "start": 5067, "end": 6312 }
class ____(DataModel): _bit_type = ir.IntType(1) _byte_type = ir.IntType(8) def get_value_type(self): return self._bit_type def get_data_type(self): return self._byte_type def get_return_type(self): return self.get_data_type() def get_argument_type(self): retu...
BooleanModel
python
pytorch__pytorch
test/test_linalg.py
{ "start": 4324, "end": 472841 }
class ____(TestCase): def setUp(self): super().setUp() torch.backends.cuda.matmul.allow_tf32 = False def tearDown(self): torch.backends.cuda.matmul.allow_tf32 = True super().tearDown() @contextlib.contextmanager def _tunableop_ctx(self): # Initialize and then te...
TestLinalg
python
readthedocs__readthedocs.org
readthedocs/projects/views/mixins.py
{ "start": 3032, "end": 4731 }
class ____: """Helpers to import a Project.""" def finish_import_project(self, request, project): """ Perform last steps to import a project into Read the Docs. - Add the user from request as maintainer - Send Django Signal - Trigger initial build It requires t...
ProjectImportMixin
python
Farama-Foundation__Gymnasium
docs/tutorials/training_agents/mujoco_reinforce.py
{ "start": 6155, "end": 12098 }
class ____: """REINFORCE algorithm.""" def __init__(self, obs_space_dims: int, action_space_dims: int): """Initializes an agent that learns a policy via REINFORCE algorithm [1] to solve the task at hand (Inverted Pendulum v4). Args: obs_space_dims: Dimension of the observat...
REINFORCE
python
pypa__pipenv
pipenv/vendor/click/parser.py
{ "start": 8052, "end": 19067 }
class ____: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you. It's not nearly as e...
OptionParser
python
FactoryBoy__factory_boy
tests/test_alchemy.py
{ "start": 8216, "end": 8739 }
class ____(TransactionTestCase): def test_create_raises_exception_when_no_session_was_set(self): with self.assertRaises(RuntimeError): NoSessionFactory.create() def test_build_does_not_raises_exception_when_no_session_was_set(self): NoSessionFactory.reset_sequence() # Make sure we...
SQLAlchemyNoSessionTestCase
python
docker__docker-py
docker/models/images.py
{ "start": 6472, "end": 18023 }
class ____(Collection): model = Image def build(self, **kwargs): """ Build an image and return it. Similar to the ``docker build`` command. Either ``path`` or ``fileobj`` must be set. If you already have a tar file for the Docker build context (including a Dockerfile), ...
ImageCollection
python
openai__openai-python
src/openai/resources/containers/containers.py
{ "start": 16506, "end": 17183 }
class ____: def __init__(self, containers: Containers) -> None: self._containers = containers self.create = _legacy_response.to_raw_response_wrapper( containers.create, ) self.retrieve = _legacy_response.to_raw_response_wrapper( containers.retrieve, )...
ContainersWithRawResponse
python
pydantic__pydantic
pydantic/mypy.py
{ "start": 50001, "end": 50448 }
class ____(TypeTranslator): """A type translator used to change type of Any's, if explicit.""" def __init__(self, type_of_any: int) -> None: self._type_of_any = type_of_any super().__init__() def visit_any(self, t: AnyType) -> Type: # noqa: D102 if t.type_of_any == TypeOfAny.expli...
ChangeExplicitTypeOfAny
python
getsentry__sentry
src/sentry/integrations/utils/sync.py
{ "start": 1301, "end": 8774 }
class ____(StrEnum): EMAIL = "email" EXTERNAL_ACTOR = "external_actor" def should_sync_assignee_inbound( organization: Organization | RpcOrganization, provider: str ) -> bool: if provider == "github": return features.has("organizations:integrations-github-project-management", organization) ...
AssigneeInboundSyncMethod
python
cython__cython
Cython/Build/IpythonMagic.py
{ "start": 2156, "end": 21453 }
class ____(Magics): def __init__(self, shell): super().__init__(shell) self._reloads = {} self._code_cache = {} self._pyximport_installed = False def _import_all(self, module): mdict = module.__dict__ if '__all__' in mdict: keys = mdict['__all__'] ...
CythonMagics
python
pytorch__pytorch
benchmarks/dynamo/pr_time_benchmarks/benchmarks/symint_sum.py
{ "start": 69, "end": 1450 }
class ____(BenchmarkBase): N = 200 def __init__(self, use_loop=False): self.use_loop = use_loop super().__init__( category="symint_sum", backend="inductor", device="cpu", ) def name(self): if self.use_loop: return f"{self.cate...
Benchmark
python
facelessuser__pymdown-extensions
tests/test_extensions/test_superfences.py
{ "start": 29080, "end": 30509 }
class ____(util.MdCase): """Test fence ids and classes with attribute lists and with no Pygments.""" extension = ['pymdownx.highlight', 'pymdownx.superfences', 'markdown.extensions.attr_list'] extension_configs = { "pymdownx.highlight": { "use_pygments": False } } def t...
TestSuperFencesClassesIdsAttrListNoPygments
python
astropy__astropy
astropy/wcs/wcsapi/high_level_api.py
{ "start": 1315, "end": 11717 }
class ____(metaclass=abc.ABCMeta): """ Abstract base class for the high-level WCS interface. This is described in `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_. """ @property @abc.abstractmethod def low_level_wcs(self): ...
BaseHighLevelWCS
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-upstage/llama_index/readers/upstage/base.py
{ "start": 2843, "end": 13712 }
class ____(BaseReader): """ Upstage Layout Analysis Reader. To use, you should have the environment variable `UPSTAGE_API_KEY` set with your API key or pass it as a named parameter to the constructor. Example: .. code-block:: python from llama_index.readers.file import Upstage...
UpstageLayoutAnalysisReader
python
ZoranPandovski__al-go-rithms
data_structures/linked-queue/python/linked_queue.py
{ "start": 231, "end": 2074 }
class ____: #------------------------------------------------------------------- # Construct Queue object self as an empty Queue object. def __init__(self): self._first = None # Reference to first _Node self._last = None # Reference to last _Node self._length = 0 # Number of...
Queue
python
scipy__scipy
scipy/signal/tests/test_ltisys.py
{ "start": 32581, "end": 33225 }
class ____: def test_initialization(self): # Check that all initializations work ZerosPolesGain(1, 1, 1) ZerosPolesGain([1], [2], 1) ZerosPolesGain(np.array([1]), np.array([2]), 1) def test_conversion(self): #Check the conversion functions s = ZerosPolesGain(1, 2...
TestZerosPolesGain
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 37908, "end": 38110 }
class ____(Blockwise): _parameters = ["frame", "index"] _defaults = {"index": 0} @staticmethod def operation(value, index=0): return pd.Series(value, index=[index])
ScalarToSeries
python
kamyu104__LeetCode-Solutions
Python/find-triangular-sum-of-an-array.py
{ "start": 1699, "end": 2075 }
class ____(object): def triangularSum(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 nCr = 1 for i in xrange(len(nums)): result = (result+nCr*nums[i])%10 nCr *= (len(nums)-1)-i nCr //= i+1 return r...
Solution2
python
getsentry__sentry
src/sentry/users/api/serializers/user.py
{ "start": 12223, "end": 12322 }
class ____(UserSerializerResponse): permissions: Sequence[str]
DetailedSelfUserSerializerResponse
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 85623, "end": 85878 }
class ____(BaseModel, extra="forbid"): id: "ExtendedPointId" = Field(..., description="") vector: "VectorStruct" = Field(..., description="") payload: Optional["Payload"] = Field(default=None, description="Payload values (optional)")
PointStruct
python
django-extensions__django-extensions
django_extensions/management/commands/sqldiff.py
{ "start": 48245, "end": 51206 }
class ____(SQLDiff): can_detect_notnull_differ = True can_detect_unsigned_differ = False def load_null(self): for table_name in self.db_tables: # sqlite does not support tablespaces tablespace = "public" # index, column_name, column_type, nullable, default_value ...
SqliteSQLDiff
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 47263, "end": 51744 }
class ____(DefinedFunction): r""" Genocchi numbers / Genocchi polynomials / Genocchi function The Genocchi numbers are a sequence of integers `G_n` that satisfy the relation: .. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!} They are related to the Bernoulli numbers by ...
genocchi
python
ray-project__ray
doc/source/serve/doc_code/grpc_proxy/user_defined_protos_pb2_grpc.py
{ "start": 3748, "end": 6249 }
class ____(object): """Missing associated documentation comment in .proto file.""" @staticmethod def __call__( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None,...
UserDefinedService
python
pytorch__pytorch
test/test_datapipe.py
{ "start": 131328, "end": 142107 }
class ____(TestCase): r""" Each `IterDataPipe` can only have one active iterator. Whenever a new iterator is created, older iterators are invalidated. These tests aim to ensure `IterDataPipe` follows this behavior. """ def _check_single_iterator_invalidation_logic(self, source_dp: IterDataPipe): ...
TestIterDataPipeSingletonConstraint
python
boto__boto3
tests/functional/test_resource.py
{ "start": 733, "end": 1430 }
class ____(unittest.TestCase): def setUp(self): self.botocore_session = botocore.session.get_session() def add_new_method(self, name): def handler(class_attributes, **kwargs): class_attributes[name] = identity return handler def test_can_inject_method_onto_resource(sel...
TestResourceCustomization
python
pytorch__pytorch
test/dynamo/cpython/3_13/seq_tests.py
{ "start": 2981, "end": 3194 }
class ____: 'Test propagation of exceptions' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def __next__(self): 3 // 0
IterGenExc
python
tensorflow__tensorflow
tensorflow/python/keras/engine/base_layer.py
{ "start": 129208, "end": 130672 }
class ____(Layer): """Adds its inputs as a metric. Attributes: aggregation: 'mean' or None. How the inputs should be aggregated. metric_name: The name to use for this metric. """ def __init__(self, aggregation=None, metric_name=None, **kwargs): super(AddMetric, self).__init__(**kwargs) self.ag...
AddMetric
python
pennersr__django-allauth
allauth/socialaccount/providers/tumblr/provider.py
{ "start": 366, "end": 736 }
class ____(OAuthProvider): id = "tumblr" name = "Tumblr" account_class = TumblrAccount oauth_adapter_class = TumblrOAuthAdapter def extract_uid(self, data): return data["name"] def extract_common_fields(self, data): return dict( first_name=data.get("name"), ...
TumblrProvider
python
haoel__leetcode
algorithms/python/SerializeAndDeserializeBST/serialize.py
{ "start": 0, "end": 761 }
class ____: def serialize(self, root): preorder = [] def helper(node): if node: preorder.append(node.val) helper(node.left) helper(node.right) helper(root) return ' '.join(map(str, preorder)) def dese...
Codec
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 20020, "end": 20182 }
class ____(BaseModel, extra="forbid"): positive: "VectorInput" = Field(..., description="") negative: "VectorInput" = Field(..., description="")
ContextPair
python
kamyu104__LeetCode-Solutions
Python/maximum-score-after-applying-operations-on-a-tree.py
{ "start": 54, "end": 1116 }
class ____(object): def maximumScoreAfterOperations(self, edges, values): """ :type edges: List[List[int]] :type values: List[int] :rtype: int """ def iter_dfs(): dp = [0]*len(values) stk = [(1, 0, -1)] while stk: st...
Solution
python
pola-rs__polars
py-polars/src/polars/series/list.py
{ "start": 575, "end": 28748 }
class ____: """Namespace for list related methods.""" _accessor = "list" def __init__(self, series: Series) -> None: self._s: PySeries = series._s def all(self) -> Series: """ Evaluate whether all boolean values in a list are true. Returns ------- Seri...
ListNameSpace
python
jpadilla__pyjwt
jwt/algorithms.py
{ "start": 5451, "end": 9121 }
class ____(ABC): """ The interface for an algorithm used to sign and verify tokens. """ # pyjwt-964: Validate to ensure the key passed in was decoded to the correct cryptography key family _crypto_key_types: tuple[type[AllowedKeys], ...] | None = None def compute_hash_digest(self, bytestr: byt...
Algorithm
python
pytorch__pytorch
torch/_dynamo/variables/dicts.py
{ "start": 61896, "end": 62918 }
class ____(DictViewVariable): kv = "items" @property def view_items_vt(self) -> list[VariableTracker]: # Returns an iterable of the unpacked items return [variables.TupleVariable([k.vt, v]) for k, v in self.view_items] def python_type(self) -> type: return dict_items def c...
DictItemsVariable
python
ethereum__web3.py
web3/utils/caching.py
{ "start": 137, "end": 230 }
class ____(Enum): FINALIZED = "finalized" SAFE = "safe"
RequestCacheValidationThreshold
python
matplotlib__matplotlib
galleries/examples/animation/pause_resume.py
{ "start": 738, "end": 1683 }
class ____: def __init__(self): fig, ax = plt.subplots() ax.set_title('Click to pause/resume the animation') x = np.linspace(-0.1, 0.1, 1000) # Start with a normal distribution self.n0 = (1.0 / ((4 * np.pi * 2e-4 * 0.1) ** 0.5) * np.exp(-x ** 2 / (4 * 2e-4...
PauseAnimation
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 26801, "end": 27922 }
class ____(TypeDefinition): __slots__ = ('loc', 'name', 'fields', 'directives',) _fields = ('name', 'fields',) def __init__(self, name, fields, loc=None, directives=None): self.loc = loc self.name = name self.fields = fields self.directives = directives def __eq__(self,...
InterfaceTypeDefinition
python
langchain-ai__langchain
libs/partners/prompty/tests/unit_tests/fake_output_parser.py
{ "start": 733, "end": 1330 }
class ____(AgentOutputParser): def parse(self, text: str) -> AgentAction | AgentFinish: action, input = extract_action_details(text) if action: log = f"\nInvoking: `{action}` with `{input}" return AgentAction(tool=action, tool_input=(input or ""), log=log) elif "Fin...
FakeOutputParser
python
kubernetes-client__python
kubernetes/client/models/v1_job_condition.py
{ "start": 383, "end": 8111 }
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...
V1JobCondition
python
pennersr__django-allauth
allauth/socialaccount/providers/mailru/views.py
{ "start": 206, "end": 1354 }
class ____(OAuth2Adapter): provider_id = "mailru" access_token_url = "https://connect.mail.ru/oauth/token" # nosec authorize_url = "https://connect.mail.ru/oauth/authorize" profile_url = "https://www.appsmail.ru/platform/api" def complete_login(self, request, app, token, **kwargs): uid = k...
MailRuOAuth2Adapter
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 132138, "end": 142597 }
class ____(AssertsCompiledSQL, fixtures.TestBase): __dialect__ = "postgresql" def setup_test(self): metadata = MetaData() self.test_table = Table( "test_table", metadata, Column("id", Integer, primary_key=True), Column("hash", HSTORE), ) ...
HStoreTest
python
ray-project__ray
python/ray/train/v2/_internal/metrics/base.py
{ "start": 2422, "end": 4386 }
class ____(Metric, Generic[E]): """A metric for tracking enum values.""" DEFAULT_VALUE = 0 RECORDED_VALUE = 1 def __init__( self, name: str, description: str, base_tags: Dict[str, str], enum_tag_key: str, ): self._enum_tag_key = enum_tag_key ...
EnumMetric
python
huggingface__transformers
src/transformers/models/deberta_v2/modeling_deberta_v2.py
{ "start": 23670, "end": 28506 }
class ____(nn.Module): """Modified BertEncoder with relative position bias support""" def __init__(self, config): super().__init__() self.layer = nn.ModuleList([DebertaV2Layer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attenti...
DebertaV2Encoder
python
getsentry__sentry
tests/sentry/utils/test_types.py
{ "start": 143, "end": 3224 }
class ____(TestCase): def test_any(self) -> None: assert Any("foo") == "foo" assert Any(1) == 1 assert Any(None) is None assert Any() is None assert Any.test(None) assert Any.test("foo") assert Any.test("bar") def test_bool(self) -> None: assert B...
OptionsTypesTest
python
python-attrs__attrs
tests/test_make.py
{ "start": 69286, "end": 79118 }
class ____: @pytest.mark.parametrize("C", [BareC, BareSlottedC]) def test_determine_detects_non_presence_correctly(self, C): """ On an empty class, nothing should be detected. """ assert True is _determine_whether_to_implement( C, None, True, ("__init__",) ) ...
TestAutoDetect
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 108052, "end": 116746 }
class ____: def test_exceptions(self): assert_raises(ValueError, interp, 0, [], []) assert_raises(ValueError, interp, 0, [0], [1, 2]) assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0) assert_raises(ValueError, interp, 0, [], [], period=360) assert_raises(ValueEr...
TestInterp
python
pdm-project__pdm
src/pdm/cli/commands/run.py
{ "start": 3578, "end": 4247 }
class ____(NamedTuple): kind: str name: str args: str | Sequence[str] options: TaskOptions def __str__(self) -> str: return f"<task [primary]{self.name}[/]>" @property def short_description(self) -> str: """ A short one line task description """ if s...
Task
python
walkccc__LeetCode
solutions/1224. Maximum Equal Frequency/1224.py
{ "start": 0, "end": 470 }
class ____: def maxEqualFreq(self, nums: list[int]) -> int: ans = 0 maxFreq = 0 count = collections.Counter() freq = collections.Counter() for i, num in enumerate(nums): freq[count[num]] -= 1 count[num] += 1 freq[count[num]] += 1 maxFreq = max(maxFreq, count[num]) if...
Solution
python
cython__cython
Cython/Plex/Scanners.py
{ "start": 237, "end": 11938 }
class ____: """ A Scanner is used to read tokens from a stream of characters using the token set specified by a Plex.Lexicon. Constructor: Scanner(lexicon, stream, name = '') See the docstring of the __init__ method for details. Methods: See the docstrings of the individual ...
Scanner
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 177223, "end": 178311 }
class ____(Response): """ Response of events.scalar_metrics_iter_histogram endpoint. :param images: :type images: Sequence[dict] """ _service = "events" _action = "scalar_metrics_iter_histogram" _version = "2.23" _schema = { "definitions": {}, "properties": {"images...
ScalarMetricsIterHistogramResponse
python
doocs__leetcode
solution/2000-2099/2021.Brightest Position on Street/Solution.py
{ "start": 0, "end": 382 }
class ____: def brightestPosition(self, lights: List[List[int]]) -> int: d = defaultdict(int) for i, j in lights: l, r = i - j, i + j d[l] += 1 d[r + 1] -= 1 ans = s = mx = 0 for k in sorted(d): s += d[k] if mx < s: ...
Solution
python
kubernetes-client__python
kubernetes/client/models/v1beta2_device_request.py
{ "start": 383, "end": 7443 }
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...
V1beta2DeviceRequest
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/property_subclasses/my_models.py
{ "start": 3192, "end": 3446 }
class ____(ndb.Model): name = ndb.StringProperty() birth = FuzzyDateProperty() death = FuzzyDateProperty() # Parallel lists: event_dates = FuzzyDateProperty(repeated=True) event_names = ndb.StringProperty(repeated=True)
HistoricPerson
python
spack__spack
lib/spack/spack/test/cmd/url.py
{ "start": 362, "end": 5594 }
class ____: def __init__(self, name, versions): self.name = name self.versions = versions def test_name_parsed_correctly(): # Expected True assert name_parsed_correctly(MyPackage("netcdf", []), "netcdf") assert name_parsed_correctly(MyPackage("r-devtools", []), "devtools") assert n...
MyPackage
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_valid_arn.py
{ "start": 121, "end": 3438 }
class ____(RegexBasedColumnMapExpectation): """Expect values in this column to be a valid amazon arn.""" # These values will be used to configure the metric created by your expectation regex_camel_name = "AmazonResourceName" regex = r"^arn:([^:\n]*):([^:\n]*):([^:\n]*):([^:\n]*):(([^:\/\n]*)[:\/])?(.*)...
ExpectColumnValuesToBeValidArn
python
jmcnamara__XlsxWriter
xlsxwriter/test/utility/test_xl_cell_to_rowcol.py
{ "start": 283, "end": 1597 }
class ____(unittest.TestCase): """ Test xl_cell_to_rowcol() utility function. """ def test_xl_cell_to_rowcol(self): """Test xl_cell_to_rowcol()""" tests = [ # row, col, A1 string (0, 0, "A1"), (0, 1, "B1"), (0, 2, "C1"), (0, ...
TestUtility
python
fluentpython__example-code
16-coroutine/taxi_sim.py
{ "start": 2763, "end": 7938 }
class ____: def __init__(self, procs_map): self.events = queue.PriorityQueue() self.procs = dict(procs_map) def run(self, end_time): # <1> """Schedule and display events until time is up""" # schedule the first event for each cab for _, proc in sorted(self.procs.items(...
Simulator
python
run-llama__llama_index
llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py
{ "start": 683, "end": 809 }
class ____(TextMessageContentEvent, Event): type: EventType = EventType.TEXT_MESSAGE_CONTENT
TextMessageContentWorkflowEvent
python
allegroai__clearml
clearml/binding/frameworks/tensorflow_bind.py
{ "start": 52806, "end": 54432 }
class ____(object): """Model adapter which extends the save and save_weights methods of a Keras Model instance""" _model: Any = None _output_model: OutputModel = None def __init__(self, model: Any, output_model: OutputModel) -> None: super(_ModelAdapter, self).__init__() super(_ModelAd...
_ModelAdapter
python
yaml__pyyaml
lib/yaml/dumper.py
{ "start": 1051, "end": 1950 }
class ____(Emitter, Serializer, SafeRepresenter, Resolver): def __init__(self, stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, ...
SafeDumper
python
python-poetry__poetry
tests/plugins/test_plugin_manager.py
{ "start": 1842, "end": 18876 }
class ____: group = "poetry.plugin" def activate(self, poetry: Poetry, io: IO) -> None: io.write_line("Updating version") poetry.package.version = Version.parse("9.9.9") @pytest.fixture def repo() -> Repository: repo = Repository("repo") repo.add_package(Package("my-other-plugin", "1....
InvalidPlugin
python
mlflow__mlflow
mlflow/telemetry/events.py
{ "start": 638, "end": 704 }
class ____(Event): name: str = "create_prompt"
CreatePromptEvent
python
spack__spack
lib/spack/spack/modules/common.py
{ "start": 11007, "end": 16885 }
class ____: """Manipulates the information needed to generate a module file to make querying easier. It needs to be sub-classed for specific module types. """ default_projections = {"all": "{name}/{version}-{compiler.name}-{compiler.version}"} def __init__(self, spec: spack.spec.Spec, module_set_n...
BaseConfiguration
python
sympy__sympy
sympy/plotting/pygletplot/plot_modes.py
{ "start": 436, "end": 915 }
class ____(PlotCurve): i_vars, d_vars = 'x', 'y' intervals = [[-5, 5, 100]] aliases = ['cartesian'] is_default = True def _get_sympy_evaluator(self): fy = self.d_vars[0] x = self.t_interval.v @float_vec3 def e(_x): return (_x, fy.subs(x, _x), 0.0) ...
Cartesian2D
python
weaviate__weaviate-python-client
weaviate/collections/classes/aggregate.py
{ "start": 2190, "end": 2489 }
class ____: """The property that the collection was grouped by.""" prop: str value: Union[ str, int, float, bool, List[str], List[int], List[float], List[bool], GeoCoordinate, None, ] @dataclass
GroupedBy
python
google__jax
jax/experimental/jet.py
{ "start": 8076, "end": 10788 }
class ____(core.Trace): __slots__ = ("tag", "parent_trace", "order") def __init__(self, tag, parent_trace, order): super().__init__() self.tag = tag self.parent_trace = parent_trace self.order = order def to_primal_terms_pair(self, val): if isinstance(val, JetTracer) and val._trace.tag is se...
JetTrace
python
huggingface__transformers
src/transformers/models/dia/configuration_dia.py
{ "start": 4583, "end": 9904 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DiaDecoder`]. It is used to instantiate a Dia decoder according to the specified arguments, defining the decoder architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to ...
DiaDecoderConfig
python
miyuchina__mistletoe
test/test_span_token.py
{ "start": 1438, "end": 2704 }
class ____(TestBranchToken): def test_parse(self): self._test_parse(span_token.Emphasis, '*some text*', 'some text') self._test_parse(span_token.Emphasis, '_some text_', 'some text') def test_emphasis_with_straight_quote(self): tokens = iter(span_token.tokenize_inner('_Book Title_\'s au...
TestEmphasis
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/uninitializedVariable1.py
{ "start": 178, "end": 424 }
class ____: # This should generate an error if reportUninitializedInstanceVariable # is enabled. v1: int v2: int v3 = 2 v4: int = 3 def __init__(self) -> None: self.v2 = 3 super().__init__() @dataclass
A
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 20810, "end": 21437 }
class ____(BaseModel): """ Serializer for React App Plugin responses. """ model_config = ConfigDict( extra="allow", ) name: Annotated[str, Field(title="Name")] icon: Annotated[str | None, Field(title="Icon")] = None icon_dark_mode: Annotated[str | None, Field(title="Icon Dark Mo...
ReactAppResponse
python
scikit-learn__scikit-learn
sklearn/utils/tests/test_metaestimators.py
{ "start": 86, "end": 2107 }
class ____: """This estimator's `available` parameter toggles the presence of a method""" def __init__(self, available=True, return_value=1): self.available = available self.return_value = return_value @available_if(lambda est: est.available) def available_func(self): """This i...
AvailableParameterEstimator
python
pytorch__pytorch
test/dynamo/test_autograd_function.py
{ "start": 1714, "end": 1816 }
class ____(torch.nn.Module): def forward(self, foo): return CustomFunc3().apply(foo)
Module5
python
streamlit__streamlit
lib/streamlit/external/langchain/streamlit_callback_handler.py
{ "start": 2964, "end": 3029 }
class ____(NamedTuple): name: str input_str: str
ToolRecord
python
pydantic__pydantic
pydantic/_internal/_repr.py
{ "start": 799, "end": 1075 }
class ____(str): """String class where repr doesn't include quotes. Useful with Representation when you want to return a string representation of something that is valid (or pseudo-valid) python. """ def __repr__(self) -> str: return str(self)
PlainRepr
python
rapidsai__cudf
python/cudf/cudf/pandas/fast_slow_proxy.py
{ "start": 33754, "end": 50785 }
class ____(FallbackError): """Raises when cuDF produces a TypeError""" pass def _raise_fallback_error(err, name): """Raises a fallback error.""" err_message = f"Falling back to the slow path. The exception was {err}. \ The function called was {name}." exception_map = { (RMMError, ...
TypeFallbackError
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 12564, "end": 13763 }
class ____(RenderedComponentContent): def __init__( self, tabs, header=None, subheader=None, styling=None, content_block_type="tabs" ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.tabs = tabs self.header = header self.subheader = ...
RenderedTabsContent
python
jazzband__django-waffle
waffle/tests/test_mixin.py
{ "start": 613, "end": 1722 }
class ____(TestCase): def setUp(self): super().setUp() self.request = get() def test_flag_must_be_active(self): view = views.FlagView self.assertRaises(Http404, process_request, self.request, view) Flag.objects.create(name='foo', everyone=True) response = proces...
WaffleFlagMixinTest
python
ray-project__ray
python/ray/data/_internal/datasource/iceberg_datasource.py
{ "start": 2137, "end": 8660 }
class ____( _ExprVisitor["BooleanExpression | UnboundTerm[Any] | Literal[Any]"] ): """ Visitor that converts Ray Data expressions to PyIceberg expressions. This enables Ray Data users to write filters using the familiar col() syntax while leveraging Iceberg's native filtering capabilities. Exa...
_IcebergExpressionVisitor
python
huggingface__transformers
src/transformers/models/moshi/modeling_moshi.py
{ "start": 41753, "end": 60099 }
class ____(MoshiPreTrainedModel, GenerationMixin): """ Transformer depth decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MoshiTransformerLayer`] Args: config: MoshiConfig """ config: MoshiDepthConfig def __init__(self, config: MoshiDepthConfig): supe...
MoshiDepthDecoder
python
run-llama__llama_index
llama-index-core/llama_index/core/prompts/utils.py
{ "start": 174, "end": 1929 }
class ____: """Safe string formatter that does not raise KeyError if key is missing.""" def __init__(self, format_dict: Optional[Dict[str, str]] = None): self.format_dict = format_dict or {} def format(self, format_string: str) -> str: return re.sub(r"\{([^{}]+)\}", self._replace_match, fo...
SafeFormatter
python
wandb__wandb
wandb/apis/public/api.py
{ "start": 2777, "end": 5223 }
class ____: """A GraphQL client that retries requests on failure. <!-- lazydoc-ignore-class: internal --> """ INFO_QUERY = gql( """ query ServerInfo{ serverInfo { cliVersionInfo latestLocalVersionInfo { outOfDate ...
RetryingClient
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/psycopg.py
{ "start": 10890, "end": 10971 }
class ____(_PGExecutionContext_common_psycopg): pass
PGExecutionContext_psycopg
python
getsentry__sentry
tests/sentry/tasks/test_weekly_reports.py
{ "start": 2250, "end": 51752 }
class ____(OutcomesSnubaTest, SnubaTestCase, PerformanceIssueTestCase): def setUp(self) -> None: super().setUp() self.now = timezone.now() self.timestamp = floor_to_utc_day(self.now).timestamp() self.two_days_ago = self.now - timedelta(days=2) self.three_days_ago = self.now -...
WeeklyReportsTest
python
django__django
tests/migrations/migrations_test_apps/alter_fk/book_app/migrations/0001_initial.py
{ "start": 43, "end": 624 }
class ____(migrations.Migration): dependencies = [ ("author_app", "0001_initial"), ] operations = [ migrations.CreateModel( name="Book", fields=[ ( "id", models.AutoField( serialize=False...
Migration
python
allegroai__clearml
clearml/binding/frameworks/tensorflow_bind.py
{ "start": 2220, "end": 10606 }
class ____(object): def __init__( self, logger: Any, report_freq: int = 100, histogram_update_freq_multiplier: int = 10, histogram_granularity: int = 50, ) -> None: self.logger = logger self.report_freq = report_freq self._histogram_granularity = h...
WeightsGradientHistHelper
python
eventlet__eventlet
tests/wsgi_test.py
{ "start": 6572, "end": 8026 }
class ____(tests.LimitedTestCase): def setUp(self): super().setUp() self.site = Site() self.killer = None self.set_site() self.spawn_server() def tearDown(self): greenthread.kill(self.killer) eventlet.sleep(0) super().tearDown() def spawn_ser...
_TestBase
python
bottlepy__bottle
test/test_wsgi.py
{ "start": 17544, "end": 18455 }
class ____(ServerTestBase): def setUp(self): ServerTestBase.setUp(self) def testWithStatement(self): default = bottle.default_app() inner_app = bottle.Bottle() self.assertEqual(default, bottle.default_app()) with inner_app: self.assertEqual(inner_app, bottle....
TestAppShortcuts
python
scipy__scipy
scipy/special/tests/test_exponential_integrals.py
{ "start": 3745, "end": 3863 }
class ____: def test_out_of_domain(self): assert all(np.isnan([sc.expn(-1, 1.0), sc.expn(1, -1.0)]))
TestExpn
python
ray-project__ray
python/ray/llm/_internal/common/callbacks/cloud_downloader.py
{ "start": 184, "end": 893 }
class ____(BaseModel): """Model for validating CloudDownloader configuration.""" paths: List[Tuple[str, str]] @field_validator("paths") @classmethod def validate_paths(cls, v: List[Tuple[str, str]]) -> List[Tuple[str, str]]: # Supported cloud storage URI schemes valid_schemes = ("s...
CloudDownloaderConfig
python
ansible__ansible
test/lib/ansible_test/_internal/config.py
{ "start": 9302, "end": 11180 }
class ____(TestConfig): """Configuration for the integration command.""" def __init__(self, args: t.Any, command: str) -> None: super().__init__(args, command) self.start_at: str = args.start_at self.start_at_task: str = args.start_at_task self.allow_destructive: bool = args.al...
IntegrationConfig
python
scipy__scipy
benchmarks/benchmarks/interpolate.py
{ "start": 4276, "end": 4726 }
class ____(Benchmark): param_names = ['n_samples', 'method'] params = [ [10, 50, 100], ['linear', 'cubic', 'quintic'], ] def setup(self, n_samples, method): r_samples = n_samples / 2. self.x = np.arange(-r_samples, r_samples, 0.25) self.y = np.arange(-r_samples, ...
Interpolate2d
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 187737, "end": 187838 }
class ____( _DateTimeTZRangeTests, _RangeTypeCompilation ): pass
DateTimeTZRangeCompilationTest
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 16885, "end": 17429 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): # The minimum can only be zero if there are no nominal features, # otherwise it is at least one # TODO: shouldn't this rather be two? minimum = None for unique in helper_functions.get_value("NumSymbols"):...
SymbolsMin