language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 43181, "end": 43273 }
class ____(Protocol[_T_co]): def __call__(s, self: Any, /) -> _T_co: ...
_HybridGetterType
python
rapidsai__cudf
python/cudf/cudf/core/dataframe.py
{ "start": 14750, "end": 17354 }
class ____(_DataFrameIndexer): """ For selection by index. """ def __getitem__(self, arg): ( row_key, ( col_is_scalar, ca, ), ) = indexing_utils.destructure_dataframe_iloc_indexer(arg, self._frame) row_spec = indexing_utils.parse_row_iloc_indexer( row_key, len(self._frame) ) return self._frame._getitem_preprocessed(row_spec, col_is_scalar, ca) @_performance_tracking def _setitem_tuple_arg(self, key, value): columns_df = self._frame._from_data( self._frame._data.select_by_index(key[1]), self._frame.index ) if is_scalar(value): for col in columns_df._column_names: self._frame[col].iloc[key[0]] = value elif isinstance(value, cudf.DataFrame): if value.shape != self._frame.iloc[key[0]].shape: _shape_mismatch_error( value.shape, self._frame.loc[key[0]].shape, ) value_column_names = set(value._column_names) for col in columns_df._column_names: columns_df[col][key[0]] = ( value._data[col] if col in value_column_names else NA ) else: # TODO: consolidate code path with identical counterpart # in `_DataFrameLocIndexer._setitem_tuple_arg` if not is_column_like(value): value = cupy.asarray(value) if getattr(value, "ndim", 1) == 2: indexed_shape = columns_df.iloc[key[0]].shape if value.shape[1] == 1: if value.shape[0] != indexed_shape[0]: _shape_mismatch_error(value.shape, indexed_shape) for i, col in enumerate(columns_df._column_names): self._frame[col].iloc[key[0]] = value[:, 0] else: if value.shape != indexed_shape: _shape_mismatch_error(value.shape, indexed_shape) for i, col in enumerate(columns_df._column_names): self._frame._data[col][key[0]] = value[:, i] else: if is_scalar(key[1]): for col in columns_df._column_names: self._frame[col].iloc[key[0]] = value else: for i, col in enumerate(columns_df._column_names): self._frame[col].iloc[key[0]] = value[i]
_DataFrameIlocIndexer
python
ApeWorX__ape
src/ape/managers/chain.py
{ "start": 23760, "end": 35737 }
class ____(BaseManager): """ A class for managing the state of the active blockchain. Also, handy for querying data about the chain and managing local caches. Access the chain manager singleton from the root ``ape`` namespace. Usage example:: from ape import chain """ _snapshots: defaultdict = defaultdict(list) # chain_id -> snapshots _chain_id_map: dict[str, int] = {} _block_container_map: dict[int, BlockContainer] = {} _transaction_history_map: dict[int, TransactionHistory] = {} _reports: ReportManager = ReportManager() _code: dict[str, dict[str, dict[AddressType, "ContractCode"]]] = {} @cached_property def contracts(self) -> ContractCache: """ A manager for cached contract-types, proxy info, and more. """ return ContractCache() @property def blocks(self) -> BlockContainer: """ The list of blocks on the chain. """ if self.chain_id not in self._block_container_map: blocks = BlockContainer() self._block_container_map[self.chain_id] = blocks return self._block_container_map[self.chain_id] @property def history(self) -> TransactionHistory: """ A mapping of transactions from the active session to the account responsible. """ try: chain_id = self.chain_id except ProviderNotConnectedError: return TransactionHistory() # Empty list. if chain_id not in self._transaction_history_map: history = TransactionHistory() self._transaction_history_map[chain_id] = history return self._transaction_history_map[chain_id] @property def chain_id(self) -> int: """ The blockchain ID. See `ChainList <https://chainlist.org/>`__ for a comprehensive list of IDs. """ network_name = self.provider.network.name if network_name not in self._chain_id_map: self._chain_id_map[network_name] = self.provider.chain_id return self._chain_id_map[network_name] @property def gas_price(self) -> int: """ The price for what it costs to transact. """ return self.provider.gas_price @property def base_fee(self) -> int: """ The minimum value required to get your transaction included on the next block. Only providers that implement `EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__ will use this property. Raises: NotImplementedError: When this provider does not implement `EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__. """ return self.provider.base_fee @property def pending_timestamp(self) -> int: """ The current epoch time of the chain, as an ``int``. You can also set the timestamp for development purposes. Usage example:: from ape import chain chain.pending_timestamp += 3600 """ return self.provider.get_block("pending").timestamp @pending_timestamp.setter def pending_timestamp(self, new_value: Union[int, str]): self.provider.set_timestamp(self.conversion_manager.convert(new_value, int)) @log_instead_of_fail(default="<ChainManager>") def __repr__(self) -> str: props = f"id={self.chain_id}" if self.network_manager.active_provider else "disconnected" cls_name = getattr(type(self), "__name__", ChainManager.__name__) return f"<{cls_name} ({props})>" def snapshot(self) -> "SnapshotID": """ Record the current state of the blockchain with intent to later call the method :meth:`~ape.managers.chain.ChainManager.revert` to go back to this point. This method is for local networks only. Raises: NotImplementedError: When the active provider does not support snapshotting. Returns: :class:`~ape.types.SnapshotID`: The snapshot ID. """ chain_id = self.chain_manager.chain_id snapshot_id = self.provider.snapshot() if snapshot_id not in self._snapshots[chain_id]: self._snapshots[chain_id].append(snapshot_id) return snapshot_id def restore(self, snapshot_id: Optional["SnapshotID"] = None): """ Regress the current call using the given snapshot ID. Allows developers to go back to a previous state. Raises: NotImplementedError: When the active provider does not support snapshotting. :class:`~ape.exceptions.UnknownSnapshotError`: When the snapshot ID is not cached. :class:`~ape.exceptions.ChainError`: When there are no snapshot IDs to select from. Args: snapshot_id (Optional[:class:`~ape.types.SnapshotID`]): The snapshot ID. Defaults to the most recent snapshot ID. """ chain_id = self.chain_manager.chain_id if snapshot_id is None and not self._snapshots[chain_id]: raise ChainError("There are no snapshots to revert to.") elif snapshot_id is None: snapshot_id = self._snapshots[chain_id].pop() elif snapshot_id not in self._snapshots[chain_id]: raise UnknownSnapshotError(snapshot_id) else: snapshot_index = self._snapshots[chain_id].index(snapshot_id) self._snapshots[chain_id] = self._snapshots[chain_id][:snapshot_index] self.provider.restore(snapshot_id) self.history.revert_to_block(self.blocks.height) @contextmanager def isolate(self): """ Run code in an isolated context. Requires using a local provider that supports snapshotting. Usages example:: owner = accounts[0] with chain.isolate(): contract = owner.deploy(project.MyContract) receipt = contract.fooBar(sender=owner) """ snapshot = None try: snapshot = self.snapshot() except APINotImplementedError: logger.warning("Provider does not support snapshotting.") pending = self.pending_timestamp start_ecosystem_name = self.provider.network.ecosystem.name start_network_name = self.provider.network.name start_provider_name = self.provider.name try: yield finally: if snapshot is None: logger.error("Failed to create snapshot.") return end_ecosystem_name = self.provider.network.ecosystem.name end_network_name = self.provider.network.name end_provider_name = self.provider.name if ( start_ecosystem_name != end_ecosystem_name or start_network_name != end_network_name or start_provider_name != end_provider_name ): logger.warning("Provider changed before isolation completed.") return self.chain_manager.restore(snapshot) try: self.pending_timestamp = pending except APINotImplementedError: # Provider does not support time travel. pass def mine( self, num_blocks: int = 1, timestamp: Optional[int] = None, deltatime: Optional[int] = None, ) -> None: """ Mine any given number of blocks. Raises: ValueError: When a timestamp AND a deltatime argument are both passed Args: num_blocks (int): Choose the number of blocks to mine. Defaults to 1 block. timestamp (Optional[int]): Designate a time (in seconds) to begin mining. Defaults to None. deltatime (Optional[int]): Designate a change in time (in seconds) to begin mining. Defaults to None. """ if timestamp and deltatime: raise ValueError("Cannot give both `timestamp` and `deltatime` arguments together.") if timestamp: self.pending_timestamp = timestamp elif deltatime: self.pending_timestamp += deltatime self.provider.mine(num_blocks) def get_balance( self, address: Union[BaseAddress, AddressType, str], block_id: Optional["BlockID"] = None ) -> int: """ Get the balance of the given address. If ``ape-ens`` is installed, you can pass ENS names. Args: address (BaseAddress, AddressType | str): An address, ENS, or account/contract. block_id (:class:`~ape.types.BlockID` | None): The block ID. Defaults to latest. Returns: int: The account balance. """ if (isinstance(address, str) and not address.startswith("0x")) or not isinstance( address, str ): # Handles accounts, ENS, integers, aliases, everything. address = self.account_manager.resolve_address(address) return self.provider.get_balance(address, block_id=block_id) def set_balance(self, account: Union[BaseAddress, AddressType, str], amount: Union[int, str]): """ Set an account balance, only works on development chains. Args: account (BaseAddress, AddressType | str): The account. amount (int | str): The new balance. """ if isinstance(account, BaseAddress): account = account.address if isinstance(amount, str) and len(str(amount).split(" ")) > 1: # Support values like "1000 ETH". amount = self.conversion_manager.convert(amount, int) elif isinstance(amount, str): # Support hex strings amount = int(amount, 16) return self.provider.set_balance(account, amount) def get_receipt(self, transaction_hash: str) -> ReceiptAPI: """ Get a transaction receipt from the chain. Args: transaction_hash (str): The hash of the transaction. Returns: :class:`~ape.apt.transactions.ReceiptAPI` """ receipt = self.chain_manager.history[transaction_hash] if not isinstance(receipt, ReceiptAPI): raise TransactionNotFoundError(transaction_hash=transaction_hash) return receipt def get_code( self, address: AddressType, block_id: Optional["BlockID"] = None ) -> "ContractCode": network = self.provider.network # Two reasons to avoid caching: # 1. dev networks - chain isolation makes this mess up # 2. specifying block_id= kwarg - likely checking if code # exists at the time and shouldn't use cache. skip_cache = network.is_dev or block_id is not None if skip_cache: return self.provider.get_code(address, block_id=block_id) self._code.setdefault(network.ecosystem.name, {}) self._code[network.ecosystem.name].setdefault(network.name, {}) if address in self._code[network.ecosystem.name][network.name]: return self._code[network.ecosystem.name][network.name][address] # Get from RPC for the first time AND use cache. code = self.provider.get_code(address) self._code[network.ecosystem.name][network.name][address] = code return code def get_delegate(self, address: AddressType) -> Optional[BaseAddress]: ecosystem = self.provider.network.ecosystem if not (proxy_info := ecosystem.get_proxy_info(address)): return None # NOTE: Do this every time because it can change? self.contracts.cache_proxy_info(address, proxy_info) try: return self.contracts.instance_at(proxy_info.target) except ContractNotFoundError: return Address(proxy_info.target)
ChainManager
python
apache__airflow
task-sdk/tests/task_sdk/api/test_client.py
{ "start": 53846, "end": 54722 }
class ____: def test_get_start_date(self): """Test that the client can get the start date of a task reschedule""" ti_id = uuid6.uuid7() def handle_request(request: httpx.Request) -> httpx.Response: if request.url.path == f"/task-reschedules/{ti_id}/start_date": assert request.url.params.get("try_number") == "1" return httpx.Response( status_code=200, json="2024-01-01T00:00:00Z", ) return httpx.Response(status_code=422) client = make_client(transport=httpx.MockTransport(handle_request)) result = client.task_instances.get_reschedule_start_date(id=ti_id, try_number=1) assert isinstance(result, TaskRescheduleStartDate) assert result.start_date == "2024-01-01T00:00:00Z"
TestTaskRescheduleOperations
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 8074, "end": 8162 }
class ____(VyperException): """Reference to a type that does not exist."""
UnknownType
python
facebook__pyre-check
client/language_server/protocol.py
{ "start": 8141, "end": 8280 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin): start: LspPosition end: LspPosition @dataclasses.dataclass(frozen=True)
LspRange
python
PyCQA__pylint
tests/functional/u/unbalanced/unbalanced_tuple_unpacking.py
{ "start": 2944, "end": 4716 }
class ____(NamedTuple): first: float second: float third: float = 1.0 def my_sum(self): """Unpack 3 variables""" first, second, third = self return first + second + third def sum_unpack_3_into_4(self): """Attempt to unpack 3 variables into 4""" first, second, third, fourth = self # [unbalanced-tuple-unpacking] return first + second + third + fourth def sum_unpack_3_into_2(self): """Attempt to unpack 3 variables into 2""" first, second = self # [unbalanced-tuple-unpacking] return first + second def my_function(mystring): """The number of items on the right-hand-side of the assignment to this function is not known""" mylist = [] for item in mystring: mylist.append(item) return mylist A, B = my_function("12") # [unbalanced-tuple-unpacking] C = my_function("12") D, *_ = my_function("12") # https://github.com/pylint-dev/pylint/issues/5998 x, y, z = (1, 2) # [unbalanced-tuple-unpacking] # https://github.com/pylint-dev/pylint/issues/7710 # Using a lot of args, so we have a high probability to still trigger the problem if # we add arguments to our unittest command later (p, q, r, s, t, u, v, w, x, y, z) = sys.argv # pylint: disable=invalid-name # https://github.com/pylint-dev/pylint/issues/10721 def fruit(apple: int, pear: int, kiwi: int | None = None) -> tuple[int, int] | tuple[int, int, int]: return (apple, pear) if kiwi is None else (apple, pear, kiwi) def main(): _, _ = fruit(1, 2) _, _ = fruit(1, 2, 3) # known false negative, requires better None comprehension in astroid _, _, _ = fruit(1, 2) # known false negative, requires better None comprehension in astroid _, _, _ = fruit(1, 2, 3)
MyClass
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/with1.py
{ "start": 1915, "end": 2077 }
class ____(Generic[_T1]): async def __aenter__(self) -> Self: return self async def __aexit__(self, *args: Any) -> None: return None
Class5
python
numba__numba
numba/core/utils.py
{ "start": 11832, "end": 13066 }
class ____(dict): def __setitem__(self, key, value): if key in self: raise AssertionError("key already in dictionary: %r" % (key,)) super(UniqueDict, self).__setitem__(key, value) def runonce(fn): @functools.wraps(fn) def inner(): if not inner._ran: res = fn() inner._result = res inner._ran = True return inner._result inner._ran = False return inner def bit_length(intval): """ Return the number of bits necessary to represent integer `intval`. """ assert isinstance(intval, int) if intval >= 0: return len(bin(intval)) - 2 else: return len(bin(-intval - 1)) - 2 def stream_list(lst): """ Given a list, return an infinite iterator of iterators. Each iterator iterates over the list from the last seen point up to the current end-of-list. In effect, each iterator will give the newly appended elements from the previous iterator instantiation time. """ def sublist_iterator(start, stop): return iter(lst[start:stop]) start = 0 while True: stop = len(lst) yield sublist_iterator(start, stop) start = stop
UniqueDict
python
huggingface__transformers
tests/utils/test_doc_samples.py
{ "start": 874, "end": 4326 }
class ____(unittest.TestCase): def analyze_directory( self, directory: Path, identifier: str | None = None, ignore_files: list[str] | None = None, n_identifier: str | list[str] | None = None, only_modules: bool = True, ): """ Runs through the specific directory, looking for the files identified with `identifier`. Executes the doctests in those files Args: directory (`Path`): Directory containing the files identifier (`str`): Will parse files containing this ignore_files (`List[str]`): List of files to skip n_identifier (`str` or `List[str]`): Will not parse files containing this/these identifiers. only_modules (`bool`): Whether to only analyze modules """ files = [file for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))] if identifier is not None: files = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(n_identifier, list): for n_ in n_identifier: files = [file for file in files if n_ not in file] else: files = [file for file in files if n_identifier not in file] ignore_files = ignore_files or [] ignore_files.append("__init__.py") files = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing", file) if only_modules: module_identifier = file.split(".")[0] try: module_identifier = getattr(transformers, module_identifier) suite = doctest.DocTestSuite(module_identifier) result = unittest.TextTestRunner().run(suite) self.assertIs(len(result.failures), 0) except AttributeError: logger.info(f"{module_identifier} is not a module.") else: result = doctest.testfile(str(".." / directory / file), optionflags=doctest.ELLIPSIS) self.assertIs(result.failed, 0) def test_modeling_examples(self): transformers_directory = Path("src/transformers") files = "modeling" ignore_files = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(transformers_directory, identifier=files, ignore_files=ignore_files) def test_tokenization_examples(self): transformers_directory = Path("src/transformers") files = "tokenization" self.analyze_directory(transformers_directory, identifier=files) def test_configuration_examples(self): transformers_directory = Path("src/transformers") files = "configuration" self.analyze_directory(transformers_directory, identifier=files) def test_remaining_examples(self): transformers_directory = Path("src/transformers") n_identifiers = ["configuration", "modeling", "tokenization"] self.analyze_directory(transformers_directory, n_identifier=n_identifiers) def test_doc_sources(self): doc_source_directory = Path("docs/source") ignore_files = ["favicon.ico"] self.analyze_directory(doc_source_directory, ignore_files=ignore_files, only_modules=False)
TestCodeExamples
python
getsentry__sentry
src/sentry/seer/models.py
{ "start": 1663, "end": 1861 }
class ____(BaseModel): handoff_point: AutofixHandoffPoint target: Literal["cursor_background_agent"] integration_id: int auto_create_pr: bool = False
SeerAutomationHandoffConfiguration
python
getsentry__sentry
src/sentry/sentry_apps/api/endpoints/sentry_app_avatar.py
{ "start": 621, "end": 1403 }
class ____(AvatarMixin[SentryAppAvatar], SentryAppBaseEndpoint): owner = ApiOwner.INTEGRATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } object_type = "sentry_app" model = SentryAppAvatar serializer_cls = SentryAppAvatarParser def get(self, request: Request, **kwargs) -> Response: return super().get( request, access=request.access, serializer=SentryAppSerializer(), **kwargs ) def put(self, request: Request, **kwargs) -> Response: return super().put( request, access=request.access, serializer=SentryAppSerializer(), **kwargs ) def get_avatar_filename(self, obj) -> str: return f"{obj.slug}.png"
SentryAppAvatarEndpoint
python
doocs__leetcode
solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution2.py
{ "start": 624, "end": 896 }
class ____: def earliestAcq(self, logs: List[List[int]], n: int) -> int: uf = UnionFind(n) for t, x, y in sorted(logs): if uf.union(x, y): n -= 1 if n == 1: return t return -1
Solution
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 144912, "end": 145241 }
class ____(BaseModel, extra="forbid"): type: "UuidIndexType" = Field(..., description="") is_tenant: Optional[bool] = Field(default=None, description="If true - used for tenant optimization.") on_disk: Optional[bool] = Field(default=None, description="If true, store the index on disk. Default: false.")
UuidIndexParams
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 399201, "end": 437859 }
class ____(Response): """ Response of tasks.get_by_id endpoint. :param task: Task info :type task: Task """ _service = "tasks" _action = "get_by_id" _version = "2.23" _schema = { "definitions": { "artifact": { "properties": { "content_size": { "description": "Raw data length in bytes", "type": "integer", }, "display_data": { "description": "User-defined list of key/value pairs, sorted", "items": {"items": {"type": "string"}, "type": "array"}, "type": "array", }, "hash": { "description": "Hash of entire raw data", "type": "string", }, "key": {"description": "Entry key", "type": "string"}, "mode": { "$ref": "#/definitions/artifact_mode_enum", "description": "System defined input/output indication", }, "timestamp": { "description": "Epoch time when artifact was created", "type": "integer", }, "type": { "description": "System defined type", "type": "string", }, "type_data": { "$ref": "#/definitions/artifact_type_data", "description": "Additional fields defined by the system", }, "uri": {"description": "Raw data location", "type": "string"}, }, "required": ["key", "type"], "type": "object", }, "artifact_mode_enum": { "default": "output", "enum": ["input", "output"], "type": "string", }, "artifact_type_data": { "properties": { "content_type": { "description": "System defined raw data content type", "type": ["string", "null"], }, "data_hash": { "description": "Hash of raw data, without any headers or descriptive parts", "type": ["string", "null"], }, "preview": { "description": "Description or textual data", "type": ["string", "null"], }, }, "type": "object", }, "augmentation": { "properties": { "crop_around_rois": { "description": "Crop image data around all frame ROIs", "type": ["boolean", "null"], }, "sets": { "description": "List of augmentation sets", "items": {"$ref": "#/definitions/augmentation_set"}, "type": ["array", "null"], }, }, "type": "object", }, "augmentation_set": { "properties": { "arguments": { "additionalProperties": { "additionalProperties": True, "type": "object", }, "description": "Arguments dictionary per custom augmentation type.", "type": ["object", "null"], }, "cls": { "description": "Augmentation class", "type": ["string", "null"], }, "strength": { "description": "Augmentation strength. Range [0,).", "minimum": 0, "type": ["number", "null"], }, "types": { "description": "Augmentation type", "items": {"type": "string"}, "type": ["array", "null"], }, }, "type": "object", }, "configuration_item": { "properties": { "description": { "description": "The parameter description. Optional", "type": ["string", "null"], }, "name": { "description": "Name of the parameter. Should be unique", "type": ["string", "null"], }, "type": { "description": "Type of the parameter. Optional", "type": ["string", "null"], }, "value": { "description": "Value of the parameter", "type": ["string", "null"], }, }, "type": "object", }, "execution": { "properties": { "artifacts": { "description": "Task artifacts", "items": {"$ref": "#/definitions/artifact"}, "type": ["array", "null"], }, "dataviews": { "description": "Additional dataviews for the task", "items": {"additionalProperties": True, "type": "object"}, "type": ["array", "null"], }, "docker_cmd": { "description": "Command for running docker script for the execution of the task", "type": ["string", "null"], }, "framework": { "description": ( "Framework related to the task. Case insensitive. Mandatory for Training tasks. " ), "type": ["string", "null"], }, "model": { "description": "Execution input model ID Not applicable for Register (Import) tasks", "type": ["string", "null"], }, "model_desc": { "additionalProperties": True, "description": "Json object representing the Model descriptors", "type": ["object", "null"], }, "model_labels": { "additionalProperties": {"type": "integer"}, "description": ( "Json object representing the ids of the labels in the model.\n The keys are the" " layers' names and the values are the IDs.\n Not applicable for Register" " (Import) tasks.\n Mandatory for Training tasks" ), "type": ["object", "null"], }, "parameters": { "additionalProperties": True, "description": "Json object containing the Task parameters", "type": ["object", "null"], }, "queue": { "description": "Queue ID where task was queued.", "type": ["string", "null"], }, "test_split": { "description": "Percentage of frames to use for testing only", "type": ["integer", "null"], }, }, "type": "object", }, "filter_by_roi_enum": { "default": "label_rules", "enum": ["disabled", "no_rois", "label_rules"], "type": "string", }, "filter_label_rule": { "properties": { "conf_range": { "description": ( "Range of ROI confidence level in the frame (min, max). -1 for not applicable\n " " Both min and max can be either -1 or positive.\n 2nd number (max) must be" " either -1 or larger than or equal to the 1st number (min)" ), "items": {"type": "number"}, "maxItems": 2, "minItems": 1, "type": "array", }, "count_range": { "description": ( "Range of times ROI appears in the frame (min, max). -1 for not applicable.\n " " Both integers must be larger than or equal to -1.\n 2nd integer (max) must be" " either -1 or larger than or equal to the 1st integer (min)" ), "items": {"type": "integer"}, "maxItems": 2, "minItems": 1, "type": "array", }, "label": { "description": ( "Lucene format query (see lucene query syntax).\nDefault search field is label.keyword and" " default operator is AND, so searching for:\n\n'Bus Stop' Blue\n\nis equivalent" " to:\n\nLabel.keyword:'Bus Stop' AND label.keyword:'Blue'" ), "type": "string", }, "must_not": { "default": False, "description": ( "If set then the label must not exist or lucene query must not be true.\n The" " default value is false" ), "type": "boolean", }, }, "required": ["label"], "type": "object", }, "filter_rule": { "properties": { "dataset": { "description": ( "Dataset ID. Must be a dataset which is in the task's view. If set to '*' all datasets in" " View are used." ), "type": "string", }, "filter_by_roi": { "description": "Type of filter. Optional, the default value is 'label_rules'", "oneOf": [ {"$ref": "#/definitions/filter_by_roi_enum"}, {"type": "null"}, ], }, "frame_query": { "description": "Frame filter, in Lucene query syntax", "type": ["string", "null"], }, "label_rules": { "description": ( "List of FilterLabelRule ('AND' connection)\n\ndisabled - No filtering by ROIs. Select all" " frames, even if they don't have ROIs (all frames)\n\nno_rois - Select only frames without" " ROIs (empty frames)\n\nlabel_rules - Select frames according to label rules" ), "items": {"$ref": "#/definitions/filter_label_rule"}, "type": ["array", "null"], }, "sources_query": { "description": "Sources filter, in Lucene query syntax. Filters sources in each frame.", "type": ["string", "null"], }, "version": { "description": ( "Dataset version to apply rule to. Must belong to the dataset and be in the task's view. If" " set to '*' all version of the datasets in View are used." ), "type": "string", }, "weight": { "description": "Rule weight. Default is 1", "type": "number", }, }, "required": ["dataset"], "type": "object", }, "filtering": { "properties": { "filtering_rules": { "description": "List of FilterRule ('OR' connection)", "items": {"$ref": "#/definitions/filter_rule"}, "type": ["array", "null"], }, "output_rois": { "description": ( "'all_in_frame' - all rois for a frame are returned\n\n'only_filtered' - only rois which" " led this frame to be selected\n\n'frame_per_roi' - single roi per frame. Frame can be" " returned multiple times with a different roi each time.\n\nNote: this should be used for" " Training tasks only\n\nNote: frame_per_roi implies that only filtered rois will be" " returned\n " ), "oneOf": [ {"$ref": "#/definitions/output_rois_enum"}, {"type": "null"}, ], }, }, "type": "object", }, "input": { "properties": { "augmentation": { "description": "Augmentation parameters. Only for training and testing tasks.", "oneOf": [ {"$ref": "#/definitions/augmentation"}, {"type": "null"}, ], }, "dataviews": { "additionalProperties": {"type": "string"}, "description": "Key to DataView ID Mapping", "type": ["object", "null"], }, "frames_filter": { "description": "Filtering params", "oneOf": [ {"$ref": "#/definitions/filtering"}, {"type": "null"}, ], }, "iteration": { "description": "Iteration parameters. Not applicable for register (import) tasks.", "oneOf": [ {"$ref": "#/definitions/iteration"}, {"type": "null"}, ], }, "mapping": { "description": "Mapping params (see common definitions section)", "oneOf": [{"$ref": "#/definitions/mapping"}, {"type": "null"}], }, "view": { "description": "View params", "oneOf": [{"$ref": "#/definitions/view"}, {"type": "null"}], }, }, "type": "object", }, "iteration": { "description": "Sequential Iteration API configuration", "properties": { "infinite": { "description": "Infinite iteration", "type": ["boolean", "null"], }, "jump": { "description": "Jump entry", "oneOf": [{"$ref": "#/definitions/jump"}, {"type": "null"}], }, "limit": { "description": ( "Maximum frames per task. If not passed, frames will end when no more matching frames are" " found, unless infinite is True." ), "type": ["integer", "null"], }, "min_sequence": { "description": ( "Length (in ms) of video clips to return. This is used in random order, and in sequential" " order only if jumping is provided and only for video frames" ), "type": ["integer", "null"], }, "order": { "description": ( "\n Input frames order. Values: 'sequential', 'random'\n In" " Sequential mode frames will be returned according to the order in which the frames were" " added to the dataset." ), "type": ["string", "null"], }, "random_seed": { "description": "Random seed used during iteration", "type": "integer", }, }, "required": ["random_seed"], "type": "object", }, "jump": { "properties": { "time": { "description": "Max time in milliseconds between frames", "type": ["integer", "null"], } }, "type": "object", }, "label_source": { "properties": { "dataset": { "description": "Source dataset id. '*' for all datasets in view", "type": ["string", "null"], }, "labels": { "description": ( "List of source labels (AND connection). '*' indicates any label. Labels must exist in at" " least one of the dataset versions in the task's view" ), "items": {"type": "string"}, "type": ["array", "null"], }, "version": { "description": ( "Source dataset version id. Default is '*' (for all versions in dataset in the view)" " Version must belong to the selected dataset, and must be in the task's view[i]" ), "type": ["string", "null"], }, }, "type": "object", }, "last_metrics_event": { "properties": { "max_value": { "description": "Maximum value reported", "type": ["number", "null"], }, "max_value_iteration": { "description": "The iteration at which the maximum value was reported", "type": ["integer", "null"], }, "metric": { "description": "Metric name", "type": ["string", "null"], }, "min_value": { "description": "Minimum value reported", "type": ["number", "null"], }, "min_value_iteration": { "description": "The iteration at which the minimum value was reported", "type": ["integer", "null"], }, "value": { "description": "Last value reported", "type": ["number", "null"], }, "variant": { "description": "Variant name", "type": ["string", "null"], }, }, "type": "object", }, "last_metrics_variants": { "additionalProperties": {"$ref": "#/definitions/last_metrics_event"}, "description": "Last metric events, one for each variant hash", "type": "object", }, "mapping": { "properties": { "rules": { "description": "Rules list", "items": {"$ref": "#/definitions/mapping_rule"}, "type": ["array", "null"], } }, "type": "object", }, "mapping_rule": { "properties": { "source": { "description": "Source label info", "oneOf": [ {"$ref": "#/definitions/label_source"}, {"type": "null"}, ], }, "target": { "description": "Target label name", "type": ["string", "null"], }, }, "type": "object", }, "output": { "properties": { "destination": { "description": "Storage id. This is where output files will be stored.", "type": ["string", "null"], }, "error": { "description": "Last error text", "type": ["string", "null"], }, "model": {"description": "Model id.", "type": ["string", "null"]}, "result": { "description": "Task result. Values: 'success', 'failure'", "type": ["string", "null"], }, "view": { "description": "View params", "oneOf": [{"$ref": "#/definitions/view"}, {"type": "null"}], }, }, "type": "object", }, "output_rois_enum": { "enum": ["all_in_frame", "only_filtered", "frame_per_roi"], "type": "string", }, "params_item": { "properties": { "description": { "description": "The parameter description. Optional", "type": ["string", "null"], }, "name": { "description": "Name of the parameter. The combination of section and name should be unique", "type": ["string", "null"], }, "section": { "description": "Section that the parameter belongs to", "type": ["string", "null"], }, "type": { "description": "Type of the parameter. Optional", "type": ["string", "null"], }, "value": { "description": "Value of the parameter", "type": ["string", "null"], }, }, "type": "object", }, "script": { "properties": { "binary": { "default": "python", "description": "Binary to use when running the script", "type": ["string", "null"], }, "branch": { "description": ( "Repository branch id If not provided and tag not provided, default repository branch " "is used." ), "type": ["string", "null"], }, "diff": { "description": "Uncommitted changes found in the repository when task was run", "type": ["string", "null"], }, "entry_point": { "description": "Path to execute within the repository", "type": ["string", "null"], }, "repository": { "description": "Name of the repository where the script is located", "type": ["string", "null"], }, "requirements": { "description": "A JSON object containing requirements strings by key", "type": ["object", "null"], }, "tag": { "description": "Repository tag", "type": ["string", "null"], }, "version_num": { "description": ( "Version (changeset) number. Optional (default is head version) Unused if tag is provided." ), "type": ["string", "null"], }, "working_dir": { "description": ( "Path to the folder from which to run the script Default - root folder of repository" ), "type": ["string", "null"], }, }, "type": "object", }, "section_params": { "additionalProperties": {"$ref": "#/definitions/params_item"}, "description": "Task section params", "type": "object", }, "task": { "properties": { "active_duration": { "description": "Task duration time (seconds)", "type": ["integer", "null"], }, "comment": { "description": "Free text comment", "type": ["string", "null"], }, "company": { "description": "Company ID", "type": ["string", "null"], }, "completed": { "description": "Task end time (UTC)", "format": "date-time", "type": ["string", "null"], }, "configuration": { "additionalProperties": { "$ref": "#/definitions/configuration_item" }, "description": "Task configuration params", "type": ["object", "null"], }, "container": { "additionalProperties": {"type": ["string", "null"]}, "description": "Docker container parameters", "type": ["object", "null"], }, "created": { "description": "Task creation time (UTC) ", "format": "date-time", "type": ["string", "null"], }, "execution": { "description": "Task execution params", "oneOf": [ {"$ref": "#/definitions/execution"}, {"type": "null"}, ], }, "hyperparams": { "additionalProperties": { "$ref": "#/definitions/section_params" }, "description": "Task hyper params per section", "type": ["object", "null"], }, "id": {"description": "Task id", "type": ["string", "null"]}, "input": { "description": "Task input params", "oneOf": [{"$ref": "#/definitions/input"}, {"type": "null"}], }, "last_change": { "description": "Last time any update was done to the task", "format": "date-time", "type": ["string", "null"], }, "last_iteration": { "description": "Last iteration reported for this task", "type": ["integer", "null"], }, "last_metrics": { "additionalProperties": { "$ref": "#/definitions/last_metrics_variants" }, "description": "Last metric variants (hash to events), one for each metric hash", "type": ["object", "null"], }, "last_update": { "description": ( "Last time this task was created, edited, changed or events for this task were reported" ), "format": "date-time", "type": ["string", "null"], }, "last_worker": { "description": "ID of last worker that handled the task", "type": ["string", "null"], }, "last_worker_report": { "description": "Last time a worker reported while working on this task", "format": "date-time", "type": ["string", "null"], }, "models": { "description": "Task models", "oneOf": [ {"$ref": "#/definitions/task_models"}, {"type": "null"}, ], }, "name": {"description": "Task Name", "type": ["string", "null"]}, "output": { "description": "Task output params", "oneOf": [{"$ref": "#/definitions/output"}, {"type": "null"}], }, "parent": { "description": "Parent task id", "type": ["string", "null"], }, "project": { "description": "Project ID of the project to which this task is assigned", "type": ["string", "null"], }, "published": { "description": "Task publish time", "format": "date-time", "type": ["string", "null"], }, "runtime": { "additionalProperties": True, "description": "Task runtime mapping", "type": ["object", "null"], }, "script": { "description": "Script info", "oneOf": [{"$ref": "#/definitions/script"}, {"type": "null"}], }, "started": { "description": "Task start time (UTC)", "format": "date-time", "type": ["string", "null"], }, "status": { "description": "", "oneOf": [ {"$ref": "#/definitions/task_status_enum"}, {"type": "null"}, ], }, "status_changed": { "description": "Last status change time", "format": "date-time", "type": ["string", "null"], }, "status_message": { "description": "free text string representing info about the status", "type": ["string", "null"], }, "status_reason": { "description": "Reason for last status change", "type": ["string", "null"], }, "system_tags": { "description": "System tags list. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": ["array", "null"], }, "tags": { "description": "User-defined tags list", "items": {"type": "string"}, "type": ["array", "null"], }, "type": { "description": "Type of task. Values: 'dataset_import', 'annotation', 'training', 'testing'", "oneOf": [ {"$ref": "#/definitions/task_type_enum"}, {"type": "null"}, ], }, "user": { "description": "Associated user id", "type": ["string", "null"], }, }, "type": "object", }, "task_model_item": { "properties": { "model": {"description": "The model ID", "type": "string"}, "name": { "description": "The task model name", "type": "string", }, }, "required": ["name", "model"], "type": "object", }, "task_models": { "properties": { "input": { "description": "The list of task input models", "items": {"$ref": "#/definitions/task_model_item"}, "type": ["array", "null"], }, "output": { "description": "The list of task output models", "items": {"$ref": "#/definitions/task_model_item"}, "type": ["array", "null"], }, }, "type": "object", }, "task_status_enum": { "enum": [ "created", "queued", "in_progress", "stopped", "published", "publishing", "closed", "failed", "completed", "unknown", ], "type": "string", }, "task_type_enum": { "enum": [ "dataset_import", "annotation", "annotation_manual", "training", "testing", "inference", "data_processing", "application", "monitor", "controller", "optimizer", "service", "qc", "custom", ], "type": "string", }, "view": { "properties": { "entries": { "description": "List of view entries. All tasks must have at least one view.", "items": {"$ref": "#/definitions/view_entry"}, "type": ["array", "null"], } }, "type": "object", }, "view_entry": { "properties": { "dataset": { "description": "Existing Dataset id", "type": ["string", "null"], }, "merge_with": { "description": "Version ID to merge with", "type": ["string", "null"], }, "version": { "description": "Version id of a version belonging to the dataset", "type": ["string", "null"], }, }, "type": "object", }, }, "properties": { "task": { "description": "Task info", "oneOf": [{"$ref": "#/definitions/task"}, {"type": "null"}], } }, "type": "object", } def __init__(self, task=None, **kwargs): super(GetByIdResponse, self).__init__(**kwargs) self.task = task @schema_property("task") def task(self): return self._property_task @task.setter def task(self, value): if value is None: self._property_task = None return if isinstance(value, dict): value = Task.from_dict(value) else: self.assert_isinstance(value, "task", Task) self._property_task = value
GetByIdResponse
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-dashscope/llama_index/readers/dashscope/domain/lease_domains.py
{ "start": 4581, "end": 5003 }
class ____(DictToObject): def __init__(self, file_id: str, parser: str): self.file_id = file_id self.parser = parser @classmethod def from_dict(cls, data: dict): default_values = {"file_id": "", "parser": ""} file_id = data.get("file_id", default_values["file_id"]) parser = data.get("parser", default_values["parser"]) return cls(file_id, parser)
AddFileResult
python
pytorch__pytorch
torch/__init__.py
{ "start": 73683, "end": 73913 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.quint4x2
QUInt4x2Storage
python
keras-team__keras
keras/src/utils/image_utils_test.py
{ "start": 217, "end": 1342 }
class ____(testing.TestCase, parameterized.TestCase): @parameterized.named_parameters( ("rgb_explicit_format", (50, 50, 3), "rgb.jpg", "jpg", True), ("rgba_explicit_format", (50, 50, 4), "rgba.jpg", "jpg", True), ("rgb_inferred_format", (50, 50, 3), "rgb_inferred.jpg", None, False), ("rgba_inferred_format", (50, 50, 4), "rgba_inferred.jpg", None, False), ) def test_save_jpg(self, shape, name, file_format, use_explicit_format): tmp_dir = self.get_temp_dir() path = os.path.join(tmp_dir, name) img = np.random.randint(0, 256, size=shape, dtype=np.uint8) # Test the actual inferred case - don't pass file_format at all if use_explicit_format: save_img(path, img, file_format=file_format) else: save_img(path, img) # Let it infer from path self.assertTrue(os.path.exists(path)) # Verify saved image is correctly converted to RGB if needed loaded_img = load_img(path) loaded_array = img_to_array(loaded_img) self.assertEqual(loaded_array.shape, (50, 50, 3))
SaveImgTest
python
openai__openai-python
src/openai/resources/models.py
{ "start": 5084, "end": 9586 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModelsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return AsyncModelsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncModelsWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return AsyncModelsWithStreamingResponse(self) async def retrieve( self, model: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Model: """ Retrieves a model instance, providing basic information about the model such as the owner and permissioning. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not model: raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return await self._get( f"/models/{model}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Model, ) def list( self, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AsyncPaginator[Model, AsyncPage[Model]]: """ Lists the currently available models, and provides basic information about each one such as the owner and availability. """ return self._get_api_list( "/models", page=AsyncPage[Model], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), model=Model, ) async def delete( self, model: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> ModelDeleted: """Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not model: raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return await self._delete( f"/models/{model}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=ModelDeleted, )
AsyncModels
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_drypython_returns.py
{ "start": 2812, "end": 4763 }
class ____(_FirstBase[int, str], _SecondBase[float, bool]): pass _generic_test_types = ( TwoGenericBases1, TwoGenericBases2, OneGenericOneConrete1, OneGenericOneConrete2, MixedGenerics1, MixedGenerics2, AllConcrete, ) @pytest.mark.parametrize("type_", _generic_test_types) def test_several_generic_bases(type_): with temp_registered(_FirstBase, st.builds(type_)): find_any(st.builds(_FirstBase)) with temp_registered(_SecondBase, st.builds(type_)): find_any(st.builds(_SecondBase)) def var_generic_func1(obj: _FirstBase[A, B]): pass def var_generic_func2(obj: _SecondBase[A, B]): pass def concrete_generic_func1(obj: _FirstBase[int, str]): pass def concrete_generic_func2(obj: _SecondBase[float, bool]): pass def mixed_generic_func1(obj: _FirstBase[A, str]): pass def mixed_generic_func2(obj: _SecondBase[float, D]): pass @pytest.mark.parametrize("type_", _generic_test_types) @pytest.mark.parametrize( "func", [ var_generic_func1, var_generic_func2, concrete_generic_func1, concrete_generic_func2, mixed_generic_func1, mixed_generic_func2, ], ) def test_several_generic_bases_functions(type_, func): with ( temp_registered(_FirstBase, st.builds(type_)), temp_registered(_SecondBase, st.builds(type_)), ): find_any(st.builds(func)) with temp_registered(type_, st.builds(type_)): find_any(st.builds(func)) def wrong_generic_func1(obj: _FirstBase[A, None]): pass def wrong_generic_func2(obj: _SecondBase[None, bool]): pass @pytest.mark.parametrize("func", [wrong_generic_func1, wrong_generic_func2]) def test_several_generic_bases_wrong_functions(func): with ( temp_registered(AllConcrete, st.builds(AllConcrete)), pytest.raises(ResolutionFailed), ): check_can_generate_examples(st.builds(func))
AllConcrete
python
ray-project__ray
python/ray/serve/tests/test_config_files/pizza.py
{ "start": 1020, "end": 1400 }
class ____: def __init__(self, factor: int): self.factor = factor def reconfigure(self, config: Dict): self.factor = config.get("factor", -1) def multiply(self, input_factor: int) -> int: return input_factor * self.factor @serve.deployment( user_config={ "increment": 2, }, ray_actor_options={"num_cpus": 0.15}, )
Multiplier
python
getsentry__sentry
src/sentry/explore/models.py
{ "start": 724, "end": 1199 }
class ____(TypesClass): SPANS = 0 OURLOGS = 1 METRICS = 2 # This is a temporary dataset to be used for the discover -> explore migration. # It will track which queries are generated from discover queries. SEGMENT_SPANS = 101 TYPES = [ (SPANS, "spans"), (OURLOGS, "logs"), (SEGMENT_SPANS, "segment_spans"), (METRICS, "metrics"), ] TYPE_NAMES = [t[1] for t in TYPES] @region_silo_model
ExploreSavedQueryDataset
python
aio-libs__aiohttp
aiohttp/_websocket/models.py
{ "start": 3170, "end": 3251 }
class ____(Exception): """WebSocket protocol handshake error."""
WSHandshakeError
python
getsentry__sentry
src/sentry/snuba/rpc_dataset_common.py
{ "start": 2941, "end": 3625 }
class ____: """Container for rpc requests""" rpc_request: TraceItemTableRequest columns: list[AnyResolved] def check_timeseries_has_data(timeseries: SnubaData, y_axes: list[str]): for row in timeseries: for axis in y_axes: if row[axis] and row[axis] != 0: return True return False def log_rpc_request(message: str, rpc_request): rpc_debug_json = json.loads(MessageToJson(rpc_request)) logger.info( message, extra={ "rpc_query": rpc_debug_json, "referrer": rpc_request.meta.referrer, "trace_item_type": rpc_request.meta.trace_item_type, }, )
TableRequest
python
pytorch__pytorch
torch/testing/_internal/distributed/_tensor/common_dtensor.py
{ "start": 2525, "end": 3004 }
class ____(nn.Module): def __init__(self, device, bias: bool = True): super().__init__() torch.manual_seed(5) self.net1 = nn.Linear(10, 16, bias=bias, device=device) self.relu = nn.ReLU() self.net2 = nn.Linear(16, 10, bias=bias, device=device) def forward(self, x): return self.net2(self.relu(self.net1(x))) def reset_parameters(self): self.net1.reset_parameters() self.net2.reset_parameters()
MLPModule
python
pandas-dev__pandas
asv_bench/benchmarks/libs.py
{ "start": 1540, "end": 2219 }
class ____: param_names = ["dtype"] data_dict = { "np-object": np.array([1] * 100000, dtype="O"), "py-object": [1] * 100000, "np-null": np.array([1] * 50000 + [np.nan] * 50000), "py-null": [1] * 50000 + [None] * 50000, "np-int": np.array([1] * 100000, dtype=int), "np-floating": np.array([1.0] * 100000, dtype=float), "empty": [], "bytes": [b"a"] * 100000, } params = list(data_dict.keys()) def time_infer_dtype_skipna(self, dtype): infer_dtype(self.data_dict[dtype], skipna=True) def time_infer_dtype(self, dtype): infer_dtype(self.data_dict[dtype], skipna=False)
InferDtype
python
Textualize__textual
src/textual/_duration.py
{ "start": 186, "end": 1211 }
class ____(DurationError): """ Indicates a malformed duration string that could not be parsed. """ def _duration_as_seconds(duration: str) -> float: """ Args: duration: A string of the form `"2s"` or `"300ms"`, representing 2 seconds and 300 milliseconds respectively. If no unit is supplied, e.g. `"2"`, then the duration is assumed to be in seconds. Raises: DurationParseError: If the argument `duration` is not a valid duration string. Returns: The duration in seconds. """ match = _match_duration(duration) if match: value, unit_name = match.groups() value = float(value) if unit_name == "ms": duration_secs = value / 1000 else: duration_secs = value else: try: duration_secs = float(duration) except ValueError: raise DurationParseError(f"{duration!r} is not a valid duration.") from None return duration_secs
DurationParseError
python
kamyu104__LeetCode-Solutions
Python/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py
{ "start": 934, "end": 1812 }
class ____(object): def longestSubarray(self, nums, limit): """ :type nums: List[int] :type limit: int :rtype: int """ max_dq, min_dq = collections.deque(), collections.deque() result, left = 0, 0 for right, num in enumerate(nums): while max_dq and nums[max_dq[-1]] <= num: max_dq.pop() max_dq.append(right) while min_dq and nums[min_dq[-1]] >= num: min_dq.pop() min_dq.append(right) while nums[max_dq[0]]-nums[min_dq[0]] > limit: # both always exist "right" element if max_dq[0] == left: max_dq.popleft() if min_dq[0] == left: min_dq.popleft() left += 1 result = max(result, right-left+1) return result
Solution2
python
ray-project__ray
python/ray/data/_internal/actor_autoscaler/autoscaling_actor_pool.py
{ "start": 267, "end": 1036 }
class ____: delta: int force: bool = field(default=False) reason: Optional[str] = field(default=None) @classmethod def no_op(cls, *, reason: Optional[str] = None) -> "ActorPoolScalingRequest": return ActorPoolScalingRequest(delta=0, reason=reason) @classmethod def upscale(cls, *, delta: int, reason: Optional[str] = None): assert delta > 0 return ActorPoolScalingRequest(delta=delta, reason=reason) @classmethod def downscale( cls, *, delta: int, force: bool = False, reason: Optional[str] = None ): assert delta < 0, "For scale down delta is expected to be negative!" return ActorPoolScalingRequest(delta=delta, force=force, reason=reason) @DeveloperAPI
ActorPoolScalingRequest
python
kubernetes-client__python
kubernetes/client/api/apps_v1_api.py
{ "start": 543, "end": 794629 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_namespaced_controller_revision(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_controller_revision # noqa: E501 create a ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_controller_revision(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ControllerRevision body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevision If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_controller_revision_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_controller_revision_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_controller_revision # noqa: E501 create a ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_controller_revision_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ControllerRevision body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevision, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevision', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_daemon_set(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_daemon_set # noqa: E501 create a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_daemon_set(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_daemon_set_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_daemon_set_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_daemon_set # noqa: E501 create a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_daemon_set_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_deployment(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_deployment # noqa: E501 create a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_deployment(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_deployment_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_deployment # noqa: E501 create a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_deployment_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_deployment`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_replica_set(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_replica_set # noqa: E501 create a ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_replica_set(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_replica_set_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_replica_set_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_replica_set # noqa: E501 create a ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_replica_set_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_stateful_set(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_stateful_set # noqa: E501 create a StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_stateful_set(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_stateful_set_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_stateful_set_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_stateful_set # noqa: E501 create a StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_stateful_set_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_controller_revision(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_controller_revision # noqa: E501 delete collection of ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_controller_revision(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_controller_revision_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_controller_revision_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_controller_revision # noqa: E501 delete collection of ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_controller_revision_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_daemon_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_daemon_set # noqa: E501 delete collection of DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_daemon_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_daemon_set_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_daemon_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_daemon_set # noqa: E501 delete collection of DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_daemon_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_deployment(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_deployment # noqa: E501 delete collection of Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_deployment(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_deployment_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_deployment # noqa: E501 delete collection of Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_deployment_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_replica_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_replica_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_replica_set_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_replica_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_replica_set # noqa: E501 delete collection of ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_replica_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_stateful_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_controller_revision(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_controller_revision # noqa: E501 delete a ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_controller_revision(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_controller_revision_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_controller_revision_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_controller_revision # noqa: E501 delete a ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_controller_revision_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_daemon_set(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_daemon_set # noqa: E501 delete a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_daemon_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_daemon_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_daemon_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_daemon_set # noqa: E501 delete a DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_daemon_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_deployment(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_deployment # noqa: E501 delete a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_deployment(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_deployment_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_deployment_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_deployment # noqa: E501 delete a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_deployment_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_deployment`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_replica_set # noqa: E501 delete a ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_replica_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_replica_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_replica_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_replica_set # noqa: E501 delete a ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_replica_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_stateful_set(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_stateful_set # noqa: E501 delete a StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_stateful_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_stateful_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_stateful_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_stateful_set # noqa: E501 delete a StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_stateful_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_api_resources(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.get_api_resources_with_http_info(**kwargs) # noqa: E501 def get_api_resources_with_http_info(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIResourceList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_resources" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIResourceList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_controller_revision_for_all_namespaces(self, **kwargs): # noqa: E501 """list_controller_revision_for_all_namespaces # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_controller_revision_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevisionList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_controller_revision_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_controller_revision_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_controller_revision_for_all_namespaces # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_controller_revision_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevisionList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_controller_revision_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/controllerrevisions', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevisionList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_daemon_set_for_all_namespaces(self, **kwargs): # noqa: E501 """list_daemon_set_for_all_namespaces # noqa: E501 list or watch objects of kind DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_daemon_set_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_daemon_set_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_daemon_set_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_daemon_set_for_all_namespaces # noqa: E501 list or watch objects of kind DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_daemon_set_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_daemon_set_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/daemonsets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_deployment_for_all_namespaces(self, **kwargs): # noqa: E501 """list_deployment_for_all_namespaces # noqa: E501 list or watch objects of kind Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_deployment_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DeploymentList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_deployment_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_deployment_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_deployment_for_all_namespaces # noqa: E501 list or watch objects of kind Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_deployment_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DeploymentList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_deployment_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/deployments', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DeploymentList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_controller_revision(self, namespace, **kwargs): # noqa: E501 """list_namespaced_controller_revision # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_controller_revision(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevisionList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_controller_revision_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_controller_revision_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_controller_revision # noqa: E501 list or watch objects of kind ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_controller_revision_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevisionList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevisionList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_daemon_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_daemon_set # noqa: E501 list or watch objects of kind DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_daemon_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_daemon_set_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_daemon_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_daemon_set # noqa: E501 list or watch objects of kind DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_daemon_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_deployment(self, namespace, **kwargs): # noqa: E501 """list_namespaced_deployment # noqa: E501 list or watch objects of kind Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_deployment(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DeploymentList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_deployment_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_deployment_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_deployment # noqa: E501 list or watch objects of kind Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_deployment_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DeploymentList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DeploymentList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_replica_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_replica_set # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_replica_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_replica_set_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_replica_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_replica_set # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_replica_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_stateful_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_stateful_set_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_stateful_set # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_stateful_set_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_replica_set_for_all_namespaces(self, **kwargs): # noqa: E501 """list_replica_set_for_all_namespaces # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_replica_set_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_replica_set_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_replica_set_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_replica_set_for_all_namespaces # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_replica_set_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_replica_set_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/replicasets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_stateful_set_for_all_namespaces(self, **kwargs): # noqa: E501 """list_stateful_set_for_all_namespaces # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_stateful_set_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSetList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_stateful_set_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_stateful_set_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_stateful_set_for_all_namespaces # noqa: E501 list or watch objects of kind StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_stateful_set_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSetList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_stateful_set_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/statefulsets', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSetList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_controller_revision(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_controller_revision # noqa: E501 partially update the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_controller_revision(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevision If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_controller_revision # noqa: E501 partially update the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_controller_revision_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevision, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevision', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_daemon_set(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_daemon_set # noqa: E501 partially update the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_daemon_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_daemon_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_daemon_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_daemon_set # noqa: E501 partially update the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_daemon_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_daemon_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_daemon_set_status # noqa: E501 partially update status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_daemon_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_daemon_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_daemon_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_daemon_set_status # noqa: E501 partially update status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_daemon_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_daemon_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_daemon_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_daemon_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_daemon_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_deployment(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment # noqa: E501 partially update the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment # noqa: E501 partially update the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment_scale # noqa: E501 partially update scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment_scale # noqa: E501 partially update scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_deployment_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_deployment_status(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment_status # noqa: E501 partially update status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_deployment_status # noqa: E501 partially update status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_deployment_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_deployment_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_replica_set(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set # noqa: E501 partially update the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_replica_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_replica_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set # noqa: E501 partially update the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_replica_set_scale(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set_scale # noqa: E501 partially update scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_replica_set_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_replica_set_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set_scale # noqa: E501 partially update scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_replica_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replica_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replica_set_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replica_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_replica_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set_status # noqa: E501 partially update status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_replica_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_replica_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set_status # noqa: E501 partially update status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_replica_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replica_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replica_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replica_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_stateful_set(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set # noqa: E501 partially update the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set # noqa: E501 partially update the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_stateful_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_stateful_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set_status # noqa: E501 partially update status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_stateful_set_status # noqa: E501 partially update status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_stateful_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_controller_revision(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_controller_revision # noqa: E501 read the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_controller_revision(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevision If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_controller_revision_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_controller_revision_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_controller_revision # noqa: E501 read the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_controller_revision_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevision, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevision', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_daemon_set(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_daemon_set # noqa: E501 read the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_daemon_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_daemon_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_daemon_set # noqa: E501 read the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_daemon_set_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_daemon_set_status # noqa: E501 read status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_daemon_set_status_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_daemon_set_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_daemon_set_status # noqa: E501 read status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_daemon_set_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_daemon_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_daemon_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_daemon_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_deployment(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment # noqa: E501 read the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_deployment_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_deployment_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment # noqa: E501 read the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_deployment`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_deployment_scale(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment_scale # noqa: E501 read scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_scale(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_deployment_scale_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment_scale # noqa: E501 read scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_scale_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_deployment_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_deployment_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment_status # noqa: E501 read status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_deployment_status_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_deployment_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_deployment_status # noqa: E501 read status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_deployment_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_replica_set(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set # noqa: E501 read the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_replica_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_replica_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set # noqa: E501 read the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_replica_set_scale(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set_scale # noqa: E501 read scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_scale(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_replica_set_scale_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_replica_set_scale_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set_scale # noqa: E501 read scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_scale_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_replica_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replica_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replica_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_replica_set_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set_status # noqa: E501 read status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_replica_set_status_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_replica_set_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set_status # noqa: E501 read status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_replica_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replica_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replica_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_stateful_set(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set # noqa: E501 read the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_stateful_set_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_stateful_set_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set # noqa: E501 read the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_stateful_set_scale(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set_scale # noqa: E501 read scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set_scale(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_stateful_set_scale_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_stateful_set_scale_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set_scale # noqa: E501 read scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set_scale_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_stateful_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_stateful_set_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set_status # noqa: E501 read status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_stateful_set_status_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_stateful_set_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_stateful_set_status # noqa: E501 read status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_stateful_set_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_stateful_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_controller_revision(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_controller_revision # noqa: E501 replace the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_controller_revision(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ControllerRevision body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ControllerRevision If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_controller_revision # noqa: E501 replace the specified ControllerRevision # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_controller_revision_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ControllerRevision (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ControllerRevision body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ControllerRevision, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_controller_revision" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_controller_revision`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_controller_revision`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/controllerrevisions/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ControllerRevision', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_daemon_set(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_daemon_set # noqa: E501 replace the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_daemon_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_daemon_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_daemon_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_daemon_set # noqa: E501 replace the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_daemon_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_daemon_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_daemon_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_daemon_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_daemon_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_daemon_set_status # noqa: E501 replace status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_daemon_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1DaemonSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_daemon_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_daemon_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_daemon_set_status # noqa: E501 replace status of the specified DaemonSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_daemon_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the DaemonSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1DaemonSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1DaemonSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_daemon_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_daemon_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_daemon_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_daemon_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/daemonsets/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1DaemonSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_deployment(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment # noqa: E501 replace the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_deployment_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment # noqa: E501 replace the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_deployment" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_deployment_scale(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment_scale # noqa: E501 replace scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment_scale # noqa: E501 replace scale of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_deployment_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_deployment_status(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment_status # noqa: E501 replace status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Deployment If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_deployment_status # noqa: E501 replace status of the specified Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_deployment_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Deployment (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Deployment body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Deployment, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_deployment_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/deployments/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Deployment', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_replica_set(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set # noqa: E501 replace the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_replica_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_replica_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set # noqa: E501 replace the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_replica_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replica_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replica_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_replica_set_scale(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set_scale # noqa: E501 replace scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_replica_set_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_replica_set_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set_scale # noqa: E501 replace scale of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_replica_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replica_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replica_set_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replica_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_replica_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set_status # noqa: E501 replace status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_replica_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_replica_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_replica_set_status # noqa: E501 replace status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_replica_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1ReplicaSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ReplicaSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_replica_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replica_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replica_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replica_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ReplicaSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_stateful_set(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set # noqa: E501 replace the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set # noqa: E501 replace the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_stateful_set" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set_scale # noqa: E501 replace scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set_scale(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Scale If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set_scale # noqa: E501 replace scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Scale (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Scale body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_stateful_set_scale" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_scale`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_scale`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_scale`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Scale', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_stateful_set_status(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set_status # noqa: E501 replace status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1StatefulSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_stateful_set_status # noqa: E501 replace status of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the StatefulSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1StatefulSet body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1StatefulSet, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_stateful_set_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StatefulSet', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
AppsV1Api
python
huggingface__transformers
src/transformers/models/rembert/modeling_rembert.py
{ "start": 12593, "end": 15728 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = RemBertAttention(config, layer_idx) self.is_decoder = config.is_decoder self.add_cross_attention = config.add_cross_attention if self.add_cross_attention: if not self.is_decoder: raise ValueError(f"{self} should be used as a decoder model if cross attention is added") self.crossattention = RemBertAttention(config, layer_idx=layer_idx) self.intermediate = RemBertIntermediate(config) self.output = RemBertOutput(config) # copied from transformers.models.bert.modeling_bert.BertLayer.forward def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, past_key_values: Optional[Cache] = None, output_attentions: Optional[bool] = False, cache_position: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor]: self_attention_outputs = self.attention( hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, past_key_values=past_key_values, cache_position=cache_position, ) attention_output = self_attention_outputs[0] outputs = self_attention_outputs[1:] # add self attentions if we output attention weights if self.is_decoder and encoder_hidden_states is not None: if not hasattr(self, "crossattention"): raise ValueError( f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers" " by setting `config.add_cross_attention=True`" ) cross_attention_outputs = self.crossattention( attention_output, attention_mask=encoder_attention_mask, encoder_hidden_states=encoder_hidden_states, past_key_values=past_key_values, output_attentions=output_attentions, cache_position=cache_position, ) attention_output = cross_attention_outputs[0] outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output ) outputs = (layer_output,) + outputs return outputs # Copied from transformers.models.bert.modeling_bert.BertLayer.feed_forward_chunk def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output
RemBertLayer
python
kamyu104__LeetCode-Solutions
Python/unique-paths-ii.py
{ "start": 37, "end": 676 }
class ____(object): # @param obstacleGrid, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ m, n = len(obstacleGrid), len(obstacleGrid[0]) ways = [0]*n ways[0] = 1 for i in xrange(m): if obstacleGrid[i][0] == 1: ways[0] = 0 for j in xrange(n): if obstacleGrid[i][j] == 1: ways[j] = 0 elif j>0: ways[j] += ways[j-1] return ways[-1]
Solution
python
numba__numba
numba/cuda/tests/cudapy/test_sm_creation.py
{ "start": 1380, "end": 7231 }
class ____(CUDATestCase): def getarg(self): return np.array(100, dtype=np.float32, ndmin=1) def getarg2(self): return self.getarg().reshape(1,1) def test_global_constants(self): udt = cuda.jit((float32[:],))(udt_global_constants) udt[1, 1](self.getarg()) def test_global_build_tuple(self): udt = cuda.jit((float32[:, :],))(udt_global_build_tuple) udt[1, 1](self.getarg2()) @skip_on_cudasim('Simulator does not prohibit lists for shared array shape') def test_global_build_list(self): with self.assertRaises(TypingError) as raises: cuda.jit((float32[:, :],))(udt_global_build_list) self.assertIn("No implementation of function " "Function(<function shared.array", str(raises.exception)) self.assertIn("found for signature:\n \n " ">>> array(shape=list(int64)<iv=[5, 6]>, " "dtype=class(float32)", str(raises.exception)) def test_global_constant_tuple(self): udt = cuda.jit((float32[:, :],))(udt_global_constant_tuple) udt[1, 1](self.getarg2()) @skip_on_cudasim("Can't check for constants in simulator") def test_invalid_1(self): # Scalar shape cannot be a floating point value with self.assertRaises(TypingError) as raises: cuda.jit((float32[:],))(udt_invalid_1) self.assertIn("No implementation of function " "Function(<function shared.array", str(raises.exception)) self.assertIn("found for signature:\n \n " ">>> array(shape=float32, dtype=class(float32))", str(raises.exception)) @skip_on_cudasim("Can't check for constants in simulator") def test_invalid_2(self): # Tuple shape cannot contain a floating point value with self.assertRaises(TypingError) as raises: cuda.jit((float32[:, :],))(udt_invalid_2) self.assertIn("No implementation of function " "Function(<function shared.array", str(raises.exception)) self.assertIn("found for signature:\n \n " ">>> array(shape=Tuple(Literal[int](1), " "array(float32, 1d, A)), dtype=class(float32))", str(raises.exception)) @skip_on_cudasim("Can't check for constants in simulator") def test_invalid_3(self): # Scalar shape must be literal with self.assertRaises(TypingError) as raises: cuda.jit((int32[:],))(udt_invalid_1) self.assertIn("No implementation of function " "Function(<function shared.array", str(raises.exception)) self.assertIn("found for signature:\n \n " ">>> array(shape=int32, dtype=class(float32))", str(raises.exception)) @skip_on_cudasim("Can't check for constants in simulator") def test_invalid_4(self): # Tuple shape must contain only literals with self.assertRaises(TypingError) as raises: cuda.jit((int32[:],))(udt_invalid_3) self.assertIn("No implementation of function " "Function(<function shared.array", str(raises.exception)) self.assertIn("found for signature:\n \n " ">>> array(shape=Tuple(Literal[int](1), int32), " "dtype=class(float32))", str(raises.exception)) def check_dtype(self, f, dtype): # Find the typing of the dtype argument to cuda.shared.array annotation = next(iter(f.overloads.values()))._type_annotation l_dtype = annotation.typemap['s'].dtype # Ensure that the typing is correct self.assertEqual(l_dtype, dtype) @skip_on_cudasim("Can't check typing in simulator") def test_numba_dtype(self): # Check that Numba types can be used as the dtype of a shared array @cuda.jit(void(int32[::1])) def f(x): s = cuda.shared.array(10, dtype=int32) s[0] = x[0] x[0] = s[0] self.check_dtype(f, int32) @skip_on_cudasim("Can't check typing in simulator") def test_numpy_dtype(self): # Check that NumPy types can be used as the dtype of a shared array @cuda.jit(void(int32[::1])) def f(x): s = cuda.shared.array(10, dtype=np.int32) s[0] = x[0] x[0] = s[0] self.check_dtype(f, int32) @skip_on_cudasim("Can't check typing in simulator") def test_string_dtype(self): # Check that strings can be used to specify the dtype of a shared array @cuda.jit(void(int32[::1])) def f(x): s = cuda.shared.array(10, dtype='int32') s[0] = x[0] x[0] = s[0] self.check_dtype(f, int32) @skip_on_cudasim("Can't check typing in simulator") def test_invalid_string_dtype(self): # Check that strings of invalid dtypes cause a typing error re = ".*Invalid NumPy dtype specified: 'int33'.*" with self.assertRaisesRegex(TypingError, re): @cuda.jit(void(int32[::1])) def f(x): s = cuda.shared.array(10, dtype='int33') s[0] = x[0] x[0] = s[0] @skip_on_cudasim("Can't check typing in simulator") def test_type_with_struct_data_model(self): @cuda.jit(void(test_struct_model_type[::1])) def f(x): s = cuda.shared.array(10, dtype=test_struct_model_type) s[0] = x[0] x[0] = s[0] self.check_dtype(f, test_struct_model_type) if __name__ == '__main__': unittest.main()
TestSharedMemoryCreation
python
PyCQA__pylint
tests/functional/ext/docparams/return/missing_return_doc_required_Numpy.py
{ "start": 1762, "end": 2198 }
class ____: """test_non_property_annotation_return_type_numpy Example of a class function trying to use `type` as return documentation in a numpy style docstring """ def foo_method(self) -> int: # [missing-return-doc] """int: docstring ... Raises ------ RuntimeError Always """ print(self) raise RuntimeError() return 10 # [unreachable]
Foo
python
kamyu104__LeetCode-Solutions
Python/zuma-game.py
{ "start": 3503, "end": 6580 }
class ____(object): def findMinStep(self, board, hand): """ :type board: str :type hand: str :rtype: int """ def shrink(s): # Time: O(n), Space: O(n) stack = [] start = 0 for i in xrange(len(s)+1): if i == len(s) or s[i] != s[start]: if stack and stack[-1][0] == s[start]: stack[-1][1] += i - start if stack[-1][1] >= 3: stack.pop() elif s and i - start < 3: stack += [s[start], i - start], start = i result = [] for p in stack: result += [p[0]] * p[1] return result def findMinStepHelper2(board, hand, lookup): result = float("inf") for i in xrange(len(hand)): for j in xrange(len(board)+1): next_board = shrink(board[0:j] + hand[i:i+1] + board[j:]) next_hand = hand[0:i] + hand[i+1:] result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1) return result def find(board, c, j): for i in xrange(j, len(board)): if board[i] == c: return i return -1 def findMinStepHelper(board, hand, lookup): if not board: return 0 if not hand: return float("inf") if tuple(hand) in lookup[tuple(board)]: return lookup[tuple(board)][tuple(hand)] result = float("inf") for i in xrange(len(hand)): j = 0 while j < len(board): k = find(board, hand[i], j) if k == -1: break if k < len(board) - 1 and board[k] == board[k+1]: next_board = shrink(board[0:k] + board[k+2:]) next_hand = hand[0:i] + hand[i+1:] result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1) k += 1 elif i > 0 and hand[i] == hand[i-1]: next_board = shrink(board[0:k] + board[k+1:]) next_hand = hand[0:i-1] + hand[i+1:] result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 2) j = k+1 lookup[tuple(board)][tuple(hand)] = result return result board, hand = list(board), list(hand) hand.sort() result = findMinStepHelper(board, hand, collections.defaultdict(dict)) if result == float("inf"): result = findMinStepHelper2(board, hand, collections.defaultdict(dict)) return -1 if result == float("inf") else result # Time: O(b * b! * h!) # Space: O(b * b! * h!) # if a ball can be only inserted beside a ball with same color, # we can do by this solution
Solution_GREEDY_ACCEPT_BUT_NOT_PROVED
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 43117, "end": 50683 }
class ____(LogitsProcessor): r""" [`LogitsProcessor`] that performs eta-sampling, a technique to filter out tokens with probabilities below a dynamic cutoff value, `eta`, which is calculated based on a combination of the hyperparameter `epsilon` and the entropy of the token probabilities, i.e. `eta := min(epsilon, sqrt(epsilon * e^-entropy(probabilities)))`. Takes the largest min_tokens_to_keep tokens if no tokens satisfy this constraint. It addresses the issue of poor quality in long samples of text generated by neural language models leading to more coherent and fluent text. See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more information. Note: `do_sample` must be set to `True` for this `LogitsProcessor` to work. Args: epsilon (`float`): A float value in the range (0, 1). Hyperparameter used to calculate the dynamic cutoff value, `eta`. The suggested values from the paper ranges from 3e-4 to 4e-3 depending on the size of the model. filter_value (`float`, *optional*, defaults to -inf): All values that are found to be below the dynamic cutoff value, `eta`, are set to this float value. This parameter is useful when logits need to be modified for very low probability tokens that should be excluded from generation entirely. min_tokens_to_keep (`int`, *optional*, defaults to 1): Specifies the minimum number of tokens that must be kept for generation, regardless of their probabilities. For example, if `min_tokens_to_keep` is set to 1, at least one token will always be kept for generation, even if all tokens have probabilities below the cutoff `eta`. device (`str`, *optional*, defaults to `"cpu"`): The device to allocate the tensors. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed >>> set_seed(1) >>> model = AutoModelForCausalLM.from_pretrained("distilbert/distilgpt2") >>> tokenizer = AutoTokenizer.from_pretrained("distilbert/distilgpt2") >>> inputs = tokenizer("A sequence: 1, 2", return_tensors="pt") >>> # With sampling, the output is unexpected -- sometimes too unexpected. >>> outputs = model.generate(**inputs, do_sample=True) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3 | < 4 (left-hand pointer) ; <BLANKLINE> <BLANKLINE> >>> # With eta sampling, the output gets restricted to high-probability tokens. You can see it as a dynamic form of >>> # epsilon sampling that adapts its cutoff probability based on the entropy (high entropy = lower cutoff). >>> # Pro tip: The paper recommends using `eta_cutoff` values between 3e-4 to 4e-3 >>> outputs = model.generate(**inputs, do_sample=True, eta_cutoff=0.1) >>> print(tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]) A sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9 ``` """ def __init__( self, epsilon: float, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1, device: str = "cpu" ): epsilon = float(epsilon) if epsilon <= 0 or epsilon >= 1: raise ValueError(f"`eta_cutoff` has to be a float > 0 and < 1, but is {epsilon}") min_tokens_to_keep = int(min_tokens_to_keep) if min_tokens_to_keep < 1: raise ValueError( f"`min_tokens_to_keep` has to be a strictly positive integer, but is {min_tokens_to_keep}" ) self.epsilon = torch.tensor(epsilon, device=device) self.filter_value = filter_value self.min_tokens_to_keep = min_tokens_to_keep @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING) def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: probabilities = scores.softmax(dim=-1) entropy = torch.distributions.Categorical(logits=scores).entropy() eta = torch.min(self.epsilon, torch.sqrt(self.epsilon) * torch.exp(-entropy))[..., None] indices_to_remove = probabilities < eta # Keep the words with the 'min_tokens_to_keep'-highest probabilities top_k = min(self.min_tokens_to_keep, scores.size(-1)) # Safety check indices_to_remove = indices_to_remove & (scores < torch.topk(scores, top_k)[0][..., -1, None]) scores_processed = scores.masked_fill(indices_to_remove, self.filter_value) return scores_processed def _get_ngrams(ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int): """ Assume ngram_size=2 and prev_input_ids=tensor([[40, 2883, 2712, 4346]]). The output of generated ngrams look like this {(40,): [2883], (2883,): [2712], (2712,): [4346]}. Args: ngram_size (`int`): The number sequential tokens taken as a group which may only occur once before being banned. prev_input_ids (`torch.Tensor`): Generated token ids for the current hypothesis. num_hypos (`int`): The number of hypotheses for which n-grams need to be generated. Returns: generated_ngrams (`dict`): Dictionary of generated ngrams. """ # Initialize an empty list of dictionaries, one for each hypothesis (index) in the range of num_hypos generated_ngrams = [{} for _ in range(num_hypos)] for idx in range(num_hypos): gen_tokens = prev_input_ids[idx].tolist() generated_ngram = generated_ngrams[idx] # Loop through each n-gram of size ngram_size in the list of tokens (gen_tokens) for ngram in zip(*[gen_tokens[i:] for i in range(ngram_size)]): prev_ngram_tuple = tuple(ngram[:-1]) generated_ngram[prev_ngram_tuple] = generated_ngram.get(prev_ngram_tuple, []) + [ngram[-1]] return generated_ngrams def _get_generated_ngrams(banned_ngrams, prev_input_ids, ngram_size, cur_len): """ Determines the banned tokens for the current hypothesis based on previously generated n-grams. Args: banned_ngrams (`dict`): A dictionary containing previously generated n-grams for each hypothesis. prev_input_ids (`torch.Tensor`): Generated token ids for the current hypothesis. ngram_size (`int`): The number sequential tokens taken as a group which may only occur once before being banned. cur_len (`int`): The current length of the token sequences for which the n-grams are being checked. Returns: List of tokens that are banned. """ # Before decoding the next token, prevent decoding of ngrams that have already appeared start_idx = cur_len + 1 - ngram_size ngram_idx = tuple(prev_input_ids[start_idx:cur_len].tolist()) return banned_ngrams.get(ngram_idx, []) def _calc_banned_ngram_tokens( ngram_size: int, prev_input_ids: torch.Tensor, num_hypos: int, cur_len: int ) -> list[Iterable[int]]: """Copied from fairseq for no_repeat_ngram in beam_search""" if cur_len + 1 < ngram_size: # return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet return [[] for _ in range(num_hypos)] generated_ngrams = _get_ngrams(ngram_size, prev_input_ids, num_hypos) banned_tokens = [ _get_generated_ngrams(generated_ngrams[hypo_idx], prev_input_ids[hypo_idx], ngram_size, cur_len) for hypo_idx in range(num_hypos) ] return banned_tokens
EtaLogitsWarper
python
boto__boto3
tests/unit/s3/test_transfer.py
{ "start": 3369, "end": 9032 }
class ____(unittest.TestCase): def assert_value_of_actual_and_alias( self, config, actual, alias, ref_value ): # Ensure that the name set in the underlying TransferConfig (i.e. # the actual) is the correct value. assert getattr(config, actual) == ref_value # Ensure that backcompat name (i.e. the alias) is the correct value. assert getattr(config, alias) == ref_value def test_alias_max_concurreny(self): ref_value = 10 config = TransferConfig(max_concurrency=ref_value) self.assert_value_of_actual_and_alias( config, 'max_request_concurrency', 'max_concurrency', ref_value ) # Set a new value using the alias new_value = 15 config.max_concurrency = new_value # Make sure it sets the value for both the alias and the actual # value that will be used in the TransferManager self.assert_value_of_actual_and_alias( config, 'max_request_concurrency', 'max_concurrency', new_value ) def test_alias_max_io_queue(self): ref_value = 10 config = TransferConfig(max_io_queue=ref_value) self.assert_value_of_actual_and_alias( config, 'max_io_queue_size', 'max_io_queue', ref_value ) # Set a new value using the alias new_value = 15 config.max_io_queue = new_value # Make sure it sets the value for both the alias and the actual # value that will be used in the TransferManager self.assert_value_of_actual_and_alias( config, 'max_io_queue_size', 'max_io_queue', new_value ) def test_transferconfig_parameters(self): config = TransferConfig( multipart_threshold=8 * MB, max_concurrency=10, multipart_chunksize=8 * MB, num_download_attempts=5, max_io_queue=100, io_chunksize=256 * KB, use_threads=True, max_bandwidth=1024 * KB, preferred_transfer_client="classic", ) assert config.multipart_threshold == 8 * MB assert config.multipart_chunksize == 8 * MB assert config.max_request_concurrency == 10 assert config.num_download_attempts == 5 assert config.max_io_queue_size == 100 assert config.io_chunksize == 256 * KB assert config.use_threads is True assert config.max_bandwidth == 1024 * KB assert config.preferred_transfer_client == "classic" def test_transferconfig_copy(self): config = TransferConfig( multipart_threshold=8 * MB, max_concurrency=10, multipart_chunksize=8 * MB, num_download_attempts=5, max_io_queue=100, io_chunksize=256 * KB, use_threads=True, max_bandwidth=1024 * KB, preferred_transfer_client="classic", ) copied_config = copy.copy(config) assert config is not copied_config assert config.multipart_threshold == copied_config.multipart_threshold assert config.multipart_chunksize == copied_config.multipart_chunksize assert ( config.max_request_concurrency == copied_config.max_request_concurrency ) assert ( config.num_download_attempts == copied_config.num_download_attempts ) assert config.max_io_queue_size == copied_config.max_io_queue_size assert config.io_chunksize == copied_config.io_chunksize assert config.use_threads == copied_config.use_threads assert config.max_bandwidth == copied_config.max_bandwidth assert ( config.preferred_transfer_client == copied_config.preferred_transfer_client ) def test_unset_default(self): config = TransferConfig() defaults = TransferConfig.DEFAULTS # Assert top-level params and aliases return defaults # when accessed via public property. assert config.multipart_threshold == defaults['multipart_threshold'] assert config.max_concurrency == defaults['max_concurrency'] assert ( config.max_request_concurrency == defaults['max_request_concurrency'] ) assert config.multipart_chunksize == defaults['multipart_chunksize'] assert ( config.num_download_attempts == defaults['num_download_attempts'] ) assert config.max_io_queue == defaults['max_io_queue'] assert config.max_io_queue_size == defaults['max_io_queue_size'] assert config.io_chunksize == defaults['io_chunksize'] assert config.use_threads == defaults['use_threads'] assert config.max_bandwidth == defaults['max_bandwidth'] assert ( config.preferred_transfer_client == defaults['preferred_transfer_client'] ) # Assert top-level params and aliases return UNSET_DEFAULT # when directly accessed. for param in defaults: assert config.get_deep_attr(param) == TransferConfig.UNSET_DEFAULT def test_explicit_config_values(self): config = TransferConfig( multipart_threshold=4 * MB, ) config.max_concurrency = 1 assert config.multipart_threshold == 4 * MB assert config.max_concurrency == 1 assert config.max_request_concurrency == 1 assert config.get_deep_attr('multipart_threshold') == 4 * MB assert config.get_deep_attr('max_concurrency') == 1 assert config.get_deep_attr('max_request_concurrency') == 1
TestTransferConfig
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 12184, "end": 12308 }
class ____(BiffRecord): _REC_ID = 0x01AF def __init__(self): self._rec_data = pack('<H', 0x00)
Prot4RevRecord
python
pypa__pipenv
pipenv/vendor/tomlkit/exceptions.py
{ "start": 1033, "end": 1278 }
class ____(ParseError): """ A numeric field was improperly specified. """ def __init__(self, line: int, col: int) -> None: message = "Invalid number" super().__init__(line, col, message=message)
InvalidNumberError
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 13743, "end": 14417 }
class ____(InstallationError): """Multiple HashError instances rolled into one for reporting""" def __init__(self) -> None: self.errors: list[HashError] = [] def append(self, error: HashError) -> None: self.errors.append(error) def __str__(self) -> str: lines = [] self.errors.sort(key=lambda e: e.order) for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__): lines.append(cls.head) lines.extend(e.body() for e in errors_of_cls) if lines: return "\n".join(lines) return "" def __bool__(self) -> bool: return bool(self.errors)
HashErrors
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 25584, "end": 42764 }
class ____(nn.Module): def __init__(self, config: Mask2FormerConfig, weight_dict: dict[str, float]): """ The Mask2Former Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we compute hungarian assignment between ground truth masks and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and mask) Args: config (`Mask2FormerConfig`): The configuration for Mask2Former model also containing loss calculation specific parameters. weight_dict (`dict[str, float]`): A dictionary of weights to be applied to the different losses. """ super().__init__() requires_backends(self, ["scipy"]) self.num_labels = config.num_labels self.weight_dict = weight_dict # Weight to apply to the null class self.eos_coef = config.no_object_weight empty_weight = torch.ones(self.num_labels + 1) empty_weight[-1] = self.eos_coef self.register_buffer("empty_weight", empty_weight) # pointwise mask loss parameters self.num_points = config.train_num_points self.oversample_ratio = config.oversample_ratio self.importance_sample_ratio = config.importance_sample_ratio self.matcher = Mask2FormerHungarianMatcher( cost_class=config.class_weight, cost_dice=config.dice_weight, cost_mask=config.mask_weight, num_points=self.num_points, ) def _max_by_axis(self, sizes: list[list[int]]) -> list[int]: maxes = sizes[0] for sublist in sizes[1:]: for index, item in enumerate(sublist): maxes[index] = max(maxes[index], item) return maxes # Adapted from nested_tensor_from_tensor_list() in original implementation def _pad_images_to_max_in_batch(self, tensors: list[Tensor]) -> tuple[Tensor, Tensor]: # get the maximum size in the batch max_size = self._max_by_axis([list(tensor.shape) for tensor in tensors]) # compute final size batch_shape = [len(tensors)] + max_size batch_size, _, height, width = batch_shape dtype = tensors[0].dtype device = tensors[0].device padded_tensors = torch.zeros(batch_shape, dtype=dtype, device=device) padding_masks = torch.ones((batch_size, height, width), dtype=torch.bool, device=device) # pad the tensors to the size of the biggest one for tensor, padded_tensor, padding_mask in zip(tensors, padded_tensors, padding_masks): padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]].copy_(tensor) padding_mask[: tensor.shape[1], : tensor.shape[2]] = False return padded_tensors, padding_masks def loss_labels( self, class_queries_logits: Tensor, class_labels: list[Tensor], indices: tuple[np.array] ) -> dict[str, Tensor]: """Compute the losses related to the labels using cross entropy. Args: class_queries_logits (`torch.Tensor`): A tensor of shape `batch_size, num_queries, num_labels` class_labels (`list[torch.Tensor]`): List of class labels of shape `(labels)`. indices (`tuple[np.array])`: The indices computed by the Hungarian matcher. Returns: `dict[str, Tensor]`: A dict of `torch.Tensor` containing the following key: - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels. """ pred_logits = class_queries_logits batch_size, num_queries, _ = pred_logits.shape criterion = nn.CrossEntropyLoss(weight=self.empty_weight) idx = self._get_predictions_permutation_indices(indices) # shape of (batch_size, num_queries) target_classes_o = torch.cat( [target[j] for target, (_, j) in zip(class_labels, indices)] ) # shape of (batch_size, num_queries) target_classes = torch.full( (batch_size, num_queries), fill_value=self.num_labels, dtype=torch.int64, device=pred_logits.device ) target_classes[idx] = target_classes_o # Permute target_classes (batch_size, num_queries, num_labels) -> (batch_size, num_labels, num_queries) pred_logits_transposed = pred_logits.transpose(1, 2) loss_ce = criterion(pred_logits_transposed, target_classes) losses = {"loss_cross_entropy": loss_ce} return losses def loss_masks( self, masks_queries_logits: torch.Tensor, mask_labels: list[torch.Tensor], indices: tuple[np.array], num_masks: int, ) -> dict[str, torch.Tensor]: """Compute the losses related to the masks using sigmoid_cross_entropy_loss and dice loss. Args: masks_queries_logits (`torch.Tensor`): A tensor of shape `(batch_size, num_queries, height, width)`. mask_labels (`torch.Tensor`): List of mask labels of shape `(labels, height, width)`. indices (`tuple[np.array])`: The indices computed by the Hungarian matcher. num_masks (`int)`: The number of masks, used for normalization. Returns: losses (`dict[str, Tensor]`): A dict of `torch.Tensor` containing two keys: - **loss_mask** -- The loss computed using sigmoid cross entropy loss on the predicted and ground truth. masks. - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth, masks. """ src_idx = self._get_predictions_permutation_indices(indices) tgt_idx = self._get_targets_permutation_indices(indices) # shape (batch_size * num_queries, height, width) pred_masks = masks_queries_logits[src_idx] # shape (batch_size, num_queries, height, width) # pad all and stack the targets to the num_labels dimension target_masks, _ = self._pad_images_to_max_in_batch(mask_labels) target_masks = target_masks[tgt_idx] # No need to upsample predictions as we are using normalized coordinates pred_masks = pred_masks[:, None] target_masks = target_masks[:, None] # Sample point coordinates with torch.no_grad(): point_coordinates = self.sample_points_using_uncertainty( pred_masks, lambda logits: self.calculate_uncertainty(logits), self.num_points, self.oversample_ratio, self.importance_sample_ratio, ) point_labels = sample_point(target_masks, point_coordinates, align_corners=False).squeeze(1) point_logits = sample_point(pred_masks, point_coordinates, align_corners=False).squeeze(1) losses = { "loss_mask": sigmoid_cross_entropy_loss(point_logits, point_labels, num_masks), "loss_dice": dice_loss(point_logits, point_labels, num_masks), } del pred_masks del target_masks return losses def _get_predictions_permutation_indices(self, indices): # Permute predictions following indices batch_indices = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)]) predictions_indices = torch.cat([src for (src, _) in indices]) return batch_indices, predictions_indices def _get_targets_permutation_indices(self, indices): # Permute labels following indices batch_indices = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)]) target_indices = torch.cat([tgt for (_, tgt) in indices]) return batch_indices, target_indices def calculate_uncertainty(self, logits: torch.Tensor) -> torch.Tensor: """ In Mask2Former paper, uncertainty is estimated as L1 distance between 0.0 and the logit prediction in 'logits' for the foreground class in `classes`. Args: logits (`torch.Tensor`): A tensor of shape (R, 1, ...) for class-specific or class-agnostic, where R is the total number of predicted masks in all images and C is: the number of foreground classes. The values are logits. Returns: scores (`torch.Tensor`): A tensor of shape (R, 1, ...) that contains uncertainty scores with the most uncertain locations having the highest uncertainty score. """ uncertainty_scores = -(torch.abs(logits)) return uncertainty_scores def sample_points_using_uncertainty( self, logits: torch.Tensor, uncertainty_function, num_points: int, oversample_ratio: int, importance_sample_ratio: float, ) -> torch.Tensor: """ This function is meant for sampling points in [0, 1] * [0, 1] coordinate space based on their uncertainty. The uncertainty is calculated for each point using the passed `uncertainty function` that takes points logit prediction as input. Args: logits (`float`): Logit predictions for P points. uncertainty_function: A function that takes logit predictions for P points and returns their uncertainties. num_points (`int`): The number of points P to sample. oversample_ratio (`int`): Oversampling parameter. importance_sample_ratio (`float`): Ratio of points that are sampled via importance sampling. Returns: point_coordinates (`torch.Tensor`): Coordinates for P sampled points. """ num_boxes = logits.shape[0] num_points_sampled = int(num_points * oversample_ratio) # Get random point coordinates point_coordinates = torch.rand(num_boxes, num_points_sampled, 2, device=logits.device) # Get sampled prediction value for the point coordinates point_logits = sample_point(logits, point_coordinates, align_corners=False) # Calculate the uncertainties based on the sampled prediction values of the points point_uncertainties = uncertainty_function(point_logits) num_uncertain_points = int(importance_sample_ratio * num_points) num_random_points = num_points - num_uncertain_points idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1] shift = num_points_sampled * torch.arange(num_boxes, dtype=torch.long, device=logits.device) idx += shift[:, None] point_coordinates = point_coordinates.view(-1, 2)[idx.view(-1), :].view(num_boxes, num_uncertain_points, 2) if num_random_points > 0: point_coordinates = torch.cat( [point_coordinates, torch.rand(num_boxes, num_random_points, 2, device=logits.device)], dim=1, ) return point_coordinates def forward( self, masks_queries_logits: torch.Tensor, class_queries_logits: torch.Tensor, mask_labels: list[torch.Tensor], class_labels: list[torch.Tensor], auxiliary_predictions: Optional[dict[str, torch.Tensor]] = None, ) -> dict[str, torch.Tensor]: """ This performs the loss computation. Args: masks_queries_logits (`torch.Tensor`): A tensor of shape `(batch_size, num_queries, height, width)`. class_queries_logits (`torch.Tensor`): A tensor of shape `(batch_size, num_queries, num_labels)`. mask_labels (`torch.Tensor`): List of mask labels of shape `(labels, height, width)`. class_labels (`list[torch.Tensor]`): List of class labels of shape `(labels)`. auxiliary_predictions (`dict[str, torch.Tensor]`, *optional*): if `use_auxiliary_loss` was set to `true` in [`Mask2FormerConfig`], then it contains the logits from the inner layers of the Mask2FormerMaskedAttentionDecoder. Returns: losses (`dict[str, Tensor]`): A dict of `torch.Tensor` containing three keys: - **loss_cross_entropy** -- The loss computed using cross entropy on the predicted and ground truth labels. - **loss_mask** -- The loss computed using sigmoid cross_entropy loss on the predicted and ground truth masks. - **loss_dice** -- The loss computed using dice loss on the predicted on the predicted and ground truth masks. if `use_auxiliary_loss` was set to `true` in [`Mask2FormerConfig`], the dictionary contains additional losses for each auxiliary predictions. """ # retrieve the matching between the outputs of the last layer and the labels indices = self.matcher(masks_queries_logits, class_queries_logits, mask_labels, class_labels) # compute the average number of target masks for normalization purposes num_masks = self.get_num_masks(class_labels, device=class_labels[0].device) # get all the losses losses: dict[str, Tensor] = { **self.loss_masks(masks_queries_logits, mask_labels, indices, num_masks), **self.loss_labels(class_queries_logits, class_labels, indices), } # in case of auxiliary losses, we repeat this process with the output of each intermediate layer. if auxiliary_predictions is not None: for idx, aux_outputs in enumerate(auxiliary_predictions): masks_queries_logits = aux_outputs["masks_queries_logits"] class_queries_logits = aux_outputs["class_queries_logits"] loss_dict = self.forward(masks_queries_logits, class_queries_logits, mask_labels, class_labels) loss_dict = {f"{key}_{idx}": value for key, value in loss_dict.items()} losses.update(loss_dict) return losses def get_num_masks(self, class_labels: torch.Tensor, device: torch.device) -> torch.Tensor: """ Computes the average number of target masks across the batch, for normalization purposes. """ num_masks = sum(len(classes) for classes in class_labels) num_masks = torch.as_tensor(num_masks, dtype=torch.float, device=device) world_size = 1 if is_accelerate_available(): if PartialState._shared_state != {}: num_masks = reduce(num_masks) world_size = PartialState().num_processes num_masks = torch.clamp(num_masks / world_size, min=1) return num_masks # Copied from transformers.models.oneformer.modeling_oneformer.multi_scale_deformable_attention def multi_scale_deformable_attention( value: Tensor, value_spatial_shapes: Union[Tensor, list[tuple]], sampling_locations: Tensor, attention_weights: Tensor, ) -> Tensor: batch_size, _, num_heads, hidden_dim = value.shape _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape value_list = value.split([height * width for height, width in value_spatial_shapes], dim=1) sampling_grids = 2 * sampling_locations - 1 sampling_value_list = [] for level_id, (height, width) in enumerate(value_spatial_shapes): # batch_size, height*width, num_heads, hidden_dim # -> batch_size, height*width, num_heads*hidden_dim # -> batch_size, num_heads*hidden_dim, height*width # -> batch_size*num_heads, hidden_dim, height, width value_l_ = ( value_list[level_id].flatten(2).transpose(1, 2).reshape(batch_size * num_heads, hidden_dim, height, width) ) # batch_size, num_queries, num_heads, num_points, 2 # -> batch_size, num_heads, num_queries, num_points, 2 # -> batch_size*num_heads, num_queries, num_points, 2 sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1) # batch_size*num_heads, hidden_dim, num_queries, num_points sampling_value_l_ = nn.functional.grid_sample( value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False ) sampling_value_list.append(sampling_value_l_) # (batch_size, num_queries, num_heads, num_levels, num_points) # -> (batch_size, num_heads, num_queries, num_levels, num_points) # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points) attention_weights = attention_weights.transpose(1, 2).reshape( batch_size * num_heads, 1, num_queries, num_levels * num_points ) output = ( (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights) .sum(-1) .view(batch_size, num_heads * hidden_dim, num_queries) ) return output.transpose(1, 2).contiguous() # Copied from transformers.models.maskformer.modeling_maskformer.MaskFormerSinePositionEmbedding with MaskFormer->Mask2Former
Mask2FormerLoss
python
walkccc__LeetCode
solutions/522. Longest Uncommon Subsequence II/522.py
{ "start": 0, "end": 689 }
class ____: def findLUSlength(self, strs: list[str]) -> int: def isSubsequence(a: str, b: str) -> bool: i = 0 j = 0 while i < len(a) and j < len(b): if a[i] == b[j]: i += 1 j += 1 return i == len(a) seen = set() duplicates = set() for s in strs: if s in seen: duplicates.add(s) seen.add(s) strs.sort(key=lambda x: -len(x)) for i in range(len(strs)): if strs[i] in duplicates: continue isASubsequence = False for j in range(i): isASubsequence |= isSubsequence(strs[i], strs[j]) if not isASubsequence: return len(strs[i]) return -1
Solution
python
MorvanZhou__Reinforcement-learning-with-tensorflow
contents/11_Dyna_Q/RL_brain.py
{ "start": 256, "end": 1996 }
class ____: def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9): self.actions = actions # a list self.lr = learning_rate self.gamma = reward_decay self.epsilon = e_greedy ## argmax type error self.q_table = pd.DataFrame(columns=self.actions).astype('float32') def choose_action(self, observation): self.check_state_exist(observation) # action selection if np.random.uniform() < self.epsilon: # choose best action # state_action = self.q_table.ix[observation, :] state_action = self.q_table.loc[observation, :] # for label indexing state_action = state_action.reindex(np.random.permutation(state_action.index)) # some actions have same value action = state_action.argmax() else: # choose random action action = np.random.choice(self.actions) return action def learn(self, s, a, r, s_): self.check_state_exist(s_) q_predict = self.q_table.loc[s, a] if s_ != 'terminal': q_target = r + self.gamma * self.q_table.loc[s_, :].max() # next state is not terminal else: q_target = r # next state is terminal self.q_table.loc[s, a] += self.lr * (q_target - q_predict) # update def check_state_exist(self, state): if state not in self.q_table.index: # append new state to q table self.q_table = self.q_table.append( pd.Series( [0]*len(self.actions), index=self.q_table.columns, name=state, ) )
QLearningTable
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 90459, "end": 93188 }
class ____(TypedDict, total=False): type: Required[Literal['union']] choices: Required[list[Union[CoreSchema, tuple[CoreSchema, str]]]] # default true, whether to automatically collapse unions with one element to the inner validator auto_collapse: bool custom_error_type: str custom_error_message: str custom_error_context: dict[str, Union[str, int, float]] mode: Literal['smart', 'left_to_right'] # default: 'smart' strict: bool ref: str metadata: dict[str, Any] serialization: SerSchema def union_schema( choices: list[CoreSchema | tuple[CoreSchema, str]], *, auto_collapse: bool | None = None, custom_error_type: str | None = None, custom_error_message: str | None = None, custom_error_context: dict[str, str | int] | None = None, mode: Literal['smart', 'left_to_right'] | None = None, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None, ) -> UnionSchema: """ Returns a schema that matches a union value, e.g.: ```py from pydantic_core import SchemaValidator, core_schema schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()]) v = SchemaValidator(schema) assert v.validate_python('hello') == 'hello' assert v.validate_python(1) == 1 ``` Args: choices: The schemas to match. If a tuple, the second item is used as the label for the case. auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true custom_error_type: The custom error type to use if the validation fails custom_error_message: The custom error message to use if the validation fails custom_error_context: The custom error context to use if the validation fails mode: How to select which choice to return * `smart` (default) will try to return the choice which is the closest match to the input value * `left_to_right` will return the first choice in `choices` which succeeds validation ref: optional unique identifier of the schema, used to reference the schema in other places metadata: Any other information you want to include with the schema, not used by pydantic-core serialization: Custom serialization schema """ return _dict_not_none( type='union', choices=choices, auto_collapse=auto_collapse, custom_error_type=custom_error_type, custom_error_message=custom_error_message, custom_error_context=custom_error_context, mode=mode, ref=ref, metadata=metadata, serialization=serialization, )
UnionSchema
python
psf__requests
tests/test_utils.py
{ "start": 11643, "end": 30115 }
class ____: @pytest.mark.parametrize( "encoding", ( "utf-32", "utf-8-sig", "utf-16", "utf-8", "utf-16-be", "utf-16-le", "utf-32-be", "utf-32-le", ), ) def test_encoded(self, encoding): data = "{}".encode(encoding) assert guess_json_utf(data) == encoding def test_bad_utf_like_encoding(self): assert guess_json_utf(b"\x00\x00\x00\x00") is None @pytest.mark.parametrize( ("encoding", "expected"), ( ("utf-16-be", "utf-16"), ("utf-16-le", "utf-16"), ("utf-32-be", "utf-32"), ("utf-32-le", "utf-32"), ), ) def test_guess_by_bom(self, encoding, expected): data = "\ufeff{}".encode(encoding) assert guess_json_utf(data) == expected USER = PASSWORD = "%!*'();:@&=+$,/?#[] " ENCODED_USER = compat.quote(USER, "") ENCODED_PASSWORD = compat.quote(PASSWORD, "") @pytest.mark.parametrize( "url, auth", ( ( f"http://{ENCODED_USER}:{ENCODED_PASSWORD}@request.com/url.html#test", (USER, PASSWORD), ), ("http://user:pass@complex.url.com/path?query=yes", ("user", "pass")), ( "http://user:pass%20pass@complex.url.com/path?query=yes", ("user", "pass pass"), ), ("http://user:pass pass@complex.url.com/path?query=yes", ("user", "pass pass")), ( "http://user%25user:pass@complex.url.com/path?query=yes", ("user%user", "pass"), ), ( "http://user:pass%23pass@complex.url.com/path?query=yes", ("user", "pass#pass"), ), ("http://complex.url.com/path?query=yes", ("", "")), ), ) def test_get_auth_from_url(url, auth): assert get_auth_from_url(url) == auth @pytest.mark.parametrize( "uri, expected", ( ( # Ensure requoting doesn't break expectations "http://example.com/fiz?buz=%25ppicture", "http://example.com/fiz?buz=%25ppicture", ), ( # Ensure we handle unquoted percent signs in redirects "http://example.com/fiz?buz=%ppicture", "http://example.com/fiz?buz=%25ppicture", ), ), ) def test_requote_uri_with_unquoted_percents(uri, expected): """See: https://github.com/psf/requests/issues/2356""" assert requote_uri(uri) == expected @pytest.mark.parametrize( "uri, expected", ( ( # Illegal bytes "http://example.com/?a=%--", "http://example.com/?a=%--", ), ( # Reserved characters "http://example.com/?a=%300", "http://example.com/?a=00", ), ), ) def test_unquote_unreserved(uri, expected): assert unquote_unreserved(uri) == expected @pytest.mark.parametrize( "mask, expected", ( (8, "255.0.0.0"), (24, "255.255.255.0"), (25, "255.255.255.128"), ), ) def test_dotted_netmask(mask, expected): assert dotted_netmask(mask) == expected http_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", } all_proxies = { "all": "socks5://http.proxy", "all://some.host": "socks5://some.host.proxy", } mixed_proxies = { "http": "http://http.proxy", "http://some.host": "http://some.host.proxy", "all": "socks5://http.proxy", } @pytest.mark.parametrize( "url, expected, proxies", ( ("hTTp://u:p@Some.Host/path", "http://some.host.proxy", http_proxies), ("hTTp://u:p@Other.Host/path", "http://http.proxy", http_proxies), ("hTTp:///path", "http://http.proxy", http_proxies), ("hTTps://Other.Host", None, http_proxies), ("file:///etc/motd", None, http_proxies), ("hTTp://u:p@Some.Host/path", "socks5://some.host.proxy", all_proxies), ("hTTp://u:p@Other.Host/path", "socks5://http.proxy", all_proxies), ("hTTp:///path", "socks5://http.proxy", all_proxies), ("hTTps://Other.Host", "socks5://http.proxy", all_proxies), ("http://u:p@other.host/path", "http://http.proxy", mixed_proxies), ("http://u:p@some.host/path", "http://some.host.proxy", mixed_proxies), ("https://u:p@other.host/path", "socks5://http.proxy", mixed_proxies), ("https://u:p@some.host/path", "socks5://http.proxy", mixed_proxies), ("https://", "socks5://http.proxy", mixed_proxies), # XXX: unsure whether this is reasonable behavior ("file:///etc/motd", "socks5://http.proxy", all_proxies), ), ) def test_select_proxies(url, expected, proxies): """Make sure we can select per-host proxies correctly.""" assert select_proxy(url, proxies) == expected @pytest.mark.parametrize( "value, expected", ( ('foo="is a fish", bar="as well"', {"foo": "is a fish", "bar": "as well"}), ("key_without_value", {"key_without_value": None}), ), ) def test_parse_dict_header(value, expected): assert parse_dict_header(value) == expected @pytest.mark.parametrize( "value, expected", ( ("application/xml", ("application/xml", {})), ( "application/json ; charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ( "application/json ; Charset=utf-8", ("application/json", {"charset": "utf-8"}), ), ("text/plain", ("text/plain", {})), ( "multipart/form-data; boundary = something ; boundary2='something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; boundary2="something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( "multipart/form-data; boundary = something ; 'boundary2=something_else' ; no_equals ", ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ( 'multipart/form-data; boundary = something ; "boundary2=something_else" ; no_equals ', ( "multipart/form-data", { "boundary": "something", "boundary2": "something_else", "no_equals": True, }, ), ), ("application/json ; ; ", ("application/json", {})), ), ) def test__parse_content_type_header(value, expected): assert _parse_content_type_header(value) == expected @pytest.mark.parametrize( "value, expected", ( (CaseInsensitiveDict(), None), ( CaseInsensitiveDict({"content-type": "application/json; charset=utf-8"}), "utf-8", ), (CaseInsensitiveDict({"content-type": "text/plain"}), "ISO-8859-1"), ), ) def test_get_encoding_from_headers(value, expected): assert get_encoding_from_headers(value) == expected @pytest.mark.parametrize( "value, length", ( ("", 0), ("T", 1), ("Test", 4), ("Cont", 0), ("Other", -5), ("Content", None), ), ) def test_iter_slices(value, length): if length is None or (length <= 0 and len(value) > 0): # Reads all content at once assert len(list(iter_slices(value, length))) == 1 else: assert len(list(iter_slices(value, 1))) == length @pytest.mark.parametrize( "value, expected", ( ( '<http:/.../front.jpeg>; rel=front; type="image/jpeg"', [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}], ), ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]), ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]), ( '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;', [ {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, {"url": "http://.../back.jpeg"}, ], ), ("", []), ), ) def test_parse_header_links(value, expected): assert parse_header_links(value) == expected @pytest.mark.parametrize( "value, expected", ( ("example.com/path", "http://example.com/path"), ("//example.com/path", "http://example.com/path"), ("example.com:80", "http://example.com:80"), ( "http://user:pass@example.com/path?query", "http://user:pass@example.com/path?query", ), ("http://user@example.com/path?query", "http://user@example.com/path?query"), ), ) def test_prepend_scheme_if_needed(value, expected): assert prepend_scheme_if_needed(value, "http") == expected @pytest.mark.parametrize( "value, expected", ( ("T", "T"), (b"T", "T"), ("T", "T"), ), ) def test_to_native_string(value, expected): assert to_native_string(value) == expected @pytest.mark.parametrize( "url, expected", ( ("http://u:p@example.com/path?a=1#test", "http://example.com/path?a=1"), ("http://example.com/path", "http://example.com/path"), ("//u:p@example.com/path", "//example.com/path"), ("//example.com/path", "//example.com/path"), ("example.com/path", "//example.com/path"), ("scheme:u:p@example.com/path", "scheme://example.com/path"), ), ) def test_urldefragauth(url, expected): assert urldefragauth(url) == expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://google.com:6000/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ("file:///some/path/on/disk", True), ), ) def test_should_bypass_proxies(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not """ monkeypatch.setenv( "no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) monkeypatch.setenv( "NO_PROXY", "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000", ) assert should_bypass_proxies(url, no_proxy=None) == expected @pytest.mark.parametrize( "url, expected", ( ("http://172.16.1.1/", "172.16.1.1"), ("http://172.16.1.1:5000/", "172.16.1.1"), ("http://user:pass@172.16.1.1", "172.16.1.1"), ("http://user:pass@172.16.1.1:5000", "172.16.1.1"), ("http://hostname/", "hostname"), ("http://hostname:5000/", "hostname"), ("http://user:pass@hostname", "hostname"), ("http://user:pass@hostname:5000", "hostname"), ), ) def test_should_bypass_proxies_pass_only_hostname(url, expected): """The proxy_bypass function should be called with a hostname or IP without a port number or auth credentials. """ with mock.patch("requests.utils.proxy_bypass") as proxy_bypass: should_bypass_proxies(url, no_proxy=None) proxy_bypass.assert_called_once_with(expected) @pytest.mark.parametrize( "cookiejar", ( compat.cookielib.CookieJar(), RequestsCookieJar(), ), ) def test_add_dict_to_cookiejar(cookiejar): """Ensure add_dict_to_cookiejar works for non-RequestsCookieJar CookieJars """ cookiedict = {"test": "cookies", "good": "cookies"} cj = add_dict_to_cookiejar(cookiejar, cookiedict) cookies = {cookie.name: cookie.value for cookie in cj} assert cookiedict == cookies @pytest.mark.parametrize( "value, expected", ( ("test", True), ("æíöû", False), ("ジェーピーニック", False), ), ) def test_unicode_is_ascii(value, expected): assert unicode_is_ascii(value) is expected @pytest.mark.parametrize( "url, expected", ( ("http://192.168.0.1:5000/", True), ("http://192.168.0.1/", True), ("http://172.16.1.1/", True), ("http://172.16.1.1:5000/", True), ("http://localhost.localdomain:5000/v1.0/", True), ("http://172.16.1.12/", False), ("http://172.16.1.12:5000/", False), ("http://google.com:5000/v1.0/", False), ), ) def test_should_bypass_proxies_no_proxy(url, expected, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not using the 'no_proxy' argument """ no_proxy = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1" # Test 'no_proxy' argument assert should_bypass_proxies(url, no_proxy=no_proxy) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") @pytest.mark.parametrize( "url, expected, override", ( ("http://192.168.0.1:5000/", True, None), ("http://192.168.0.1/", True, None), ("http://172.16.1.1/", True, None), ("http://172.16.1.1:5000/", True, None), ("http://localhost.localdomain:5000/v1.0/", True, None), ("http://172.16.1.22/", False, None), ("http://172.16.1.22:5000/", False, None), ("http://google.com:5000/v1.0/", False, None), ("http://mylocalhostname:5000/v1.0/", True, "<local>"), ("http://192.168.0.1/", False, ""), ), ) def test_should_bypass_proxies_win_registry(url, expected, override, monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows registry settings """ if override is None: override = "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1" import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() proxyEnableValues = deque([1, "1"]) def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD) proxyEnableValues.rotate() return [proxyEnableValues[0]] elif value_name == "ProxyOverride": return [override] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("ftp_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies(url, None) == expected @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_bad_values(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows invalid registry settings. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": # Invalid response; Should be an int or int-y value return [""] elif value_name == "ProxyOverride": return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"] monkeypatch.setenv("http_proxy", "") monkeypatch.setenv("https_proxy", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setenv("NO_PROXY", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://172.16.1.1/", None) is False @pytest.mark.parametrize( "env_name, value", ( ("no_proxy", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("no_proxy", None), ("a_new_key", "192.168.0.0/24,127.0.0.1,localhost.localdomain"), ("a_new_key", None), ), ) def test_set_environ(env_name, value): """Tests set_environ will set environ values and will restore the environ.""" environ_copy = copy.deepcopy(os.environ) with set_environ(env_name, value): assert os.environ.get(env_name) == value assert os.environ == environ_copy def test_set_environ_raises_exception(): """Tests set_environ will raise exceptions in context when the value parameter is None.""" with pytest.raises(Exception) as exception: with set_environ("test1", None): raise Exception("Expected exception") assert "Expected exception" in str(exception.value) @pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") def test_should_bypass_proxies_win_registry_ProxyOverride_value(monkeypatch): """Tests for function should_bypass_proxies to check if proxy can be bypassed or not with Windows ProxyOverride registry value ending with a semicolon. """ import winreg class RegHandle: def Close(self): pass ie_settings = RegHandle() def OpenKey(key, subkey): return ie_settings def QueryValueEx(key, value_name): if key is ie_settings: if value_name == "ProxyEnable": return [1] elif value_name == "ProxyOverride": return [ "192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1;<-loopback>;" ] monkeypatch.setenv("NO_PROXY", "") monkeypatch.setenv("no_proxy", "") monkeypatch.setattr(winreg, "OpenKey", OpenKey) monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) assert should_bypass_proxies("http://example.com/", None) is False
TestGuessJSONUTF
python
django__django
tests/migration_test_data_persistence/tests.py
{ "start": 130, "end": 514 }
class ____(TransactionTestCase): """ Data loaded in migrations is available if TransactionTestCase.serialized_rollback = True. """ available_apps = ["migration_test_data_persistence"] serialized_rollback = True def test_persistence(self): self.assertEqual( Book.objects.count(), 1, )
MigrationDataPersistenceTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 2680, "end": 2727 }
class ____(Co_TA[Co_TA[T_co]]): ...
CoToCo_WithTA
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py
{ "start": 52518, "end": 55503 }
class ____(TestAssets): DAG_ASSET1_ID = "test_dag_1" DAG_ASSET2_ID_A = "test_dag_2a" DAG_ASSET2_ID_B = "test_dag_2b" DAG_ASSET_NO = "test_dag_no" @pytest.fixture(autouse=True) def create_dags(self, setup, dag_maker, session): # Depend on 'setup' so it runs first. Otherwise it deletes what we create here. assets = { i: am.to_public() for i, am in enumerate(self.create_assets(session=session, num=3), start=1) } with dag_maker(self.DAG_ASSET1_ID, schedule=None, session=session): EmptyOperator(task_id="task", outlets=assets[1]) with dag_maker(self.DAG_ASSET2_ID_A, schedule=None, session=session): EmptyOperator(task_id="task", outlets=assets[2]) with dag_maker(self.DAG_ASSET2_ID_B, schedule=None, session=session): EmptyOperator(task_id="task", outlets=assets[2]) with dag_maker(self.DAG_ASSET_NO, schedule=None, session=session): EmptyOperator(task_id="task") session.commit() @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_should_respond_200(self, test_client): response = test_client.post("/assets/1/materialize") assert response.status_code == 200 assert response.json() == { "bundle_version": None, "dag_display_name": self.DAG_ASSET1_ID, "dag_run_id": mock.ANY, "dag_id": self.DAG_ASSET1_ID, "dag_versions": mock.ANY, "logical_date": None, "partition_key": None, "queued_at": mock.ANY, "run_after": mock.ANY, "start_date": None, "end_date": None, "duration": None, "data_interval_start": None, "data_interval_end": None, "last_scheduling_decision": None, "run_type": "manual", "state": "queued", "triggered_by": "rest_api", "triggering_user_name": "test", "conf": {}, "note": None, } def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.post("/assets/2/materialize") assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.post("/assets/2/materialize") assert response.status_code == 403 def test_should_respond_409_on_multiple_dags(self, test_client): response = test_client.post("/assets/2/materialize") assert response.status_code == 409 assert response.json()["detail"] == "More than one DAG materializes asset with ID: 2" def test_should_respond_404_on_multiple_dags(self, test_client): response = test_client.post("/assets/3/materialize") assert response.status_code == 404 assert response.json()["detail"] == "No DAG materializes asset with ID: 3"
TestPostAssetMaterialize
python
pypa__warehouse
tests/unit/metrics/test_services.py
{ "start": 1530, "end": 5763 }
class ____: def test_verify_service(self): assert verifyClass(IMetricsService, DataDogMetrics) def test_create_service_defaults(self, monkeypatch): datadog_obj = pretend.stub() datadog_cls = pretend.call_recorder(lambda **kw: datadog_obj) monkeypatch.setattr(services, "DogStatsd", datadog_cls) context = pretend.stub() request = pretend.stub(registry=pretend.stub(settings={})) metrics = DataDogMetrics.create_service(context, request) assert metrics._datadog is datadog_obj assert datadog_cls.calls == [ pretend.call(host="127.0.0.1", port=8125, namespace=None, use_ms=True) ] def test_create_service_overrides(self, monkeypatch): datadog_obj = pretend.stub() datadog_cls = pretend.call_recorder(lambda **kw: datadog_obj) monkeypatch.setattr(services, "DogStatsd", datadog_cls) context = pretend.stub() request = pretend.stub( registry=pretend.stub( settings={ "metrics.host": "example.com", "metrics.port": "9152", "metrics.namespace": "thing", } ) ) metrics = DataDogMetrics.create_service(context, request) assert metrics._datadog is datadog_obj assert datadog_cls.calls == [ pretend.call(host="example.com", port=9152, namespace="thing", use_ms=True) ] @pytest.mark.parametrize( "method", [ "gauge", "increment", "decrement", "histogram", "distribution", "timing", "set", ], ) def test_dispatches_basic(self, method): method_fn = pretend.call_recorder(lambda *a, **kw: None) datadog = pretend.stub(**{method: method_fn}) metrics = DataDogMetrics(datadog) getattr(metrics, method)("my metric", 3, tags=["foo", "bar"], sample_rate=0.5) assert method_fn.calls == [ pretend.call("my metric", 3, tags=["foo", "bar"], sample_rate=0.5) ] def test_dispatches_timed(self): timer = pretend.stub() datadog = pretend.stub(timed=pretend.call_recorder(lambda *a, **k: timer)) metrics = DataDogMetrics(datadog) assert ( metrics.timed("thing.timed", tags=["wat"], sample_rate=0.4, use_ms=True) is timer ) assert datadog.timed.calls == [ pretend.call("thing.timed", tags=["wat"], sample_rate=0.4, use_ms=True) ] def test_dispatches_event(self): datadog = pretend.stub(event=pretend.call_recorder(lambda *a, **k: None)) metrics = DataDogMetrics(datadog) metrics.event( "my title", "this is text", alert_type="thing", aggregation_key="wat", source_type_name="ok?", date_happened="now?", priority="who knows", tags=["one", "two"], hostname="example.com", ) assert datadog.event.calls == [ pretend.call( "my title", "this is text", alert_type="thing", aggregation_key="wat", source_type_name="ok?", date_happened="now?", priority="who knows", tags=["one", "two"], hostname="example.com", ) ] def test_dispatches_service_check(self): datadog = pretend.stub( service_check=pretend.call_recorder(lambda *a, **k: None) ) metrics = DataDogMetrics(datadog) metrics.service_check( "name!", "ok", tags=["one", "two"], timestamp="now", hostname="example.com", message="my message", ) assert datadog.service_check.calls == [ pretend.call( "name!", "ok", tags=["one", "two"], timestamp="now", hostname="example.com", message="my message", ) ]
TestDataDogMetrics
python
PyCQA__pylint
tests/functional/t/try_except_raise.py
{ "start": 480, "end": 544 }
class ____(Exception): """AAAException""" pass
AAAException
python
django__django
tests/utils_tests/test_datastructures.py
{ "start": 341, "end": 1687 }
class ____(SimpleTestCase): def test_init_with_iterable(self): s = OrderedSet([1, 2, 3]) self.assertEqual(list(s.dict.keys()), [1, 2, 3]) def test_remove(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.remove(2) self.assertEqual(len(s), 1) self.assertNotIn(2, s) def test_discard(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.discard(2) self.assertEqual(len(s), 1) def test_reversed(self): s = reversed(OrderedSet([1, 2, 3])) self.assertIsInstance(s, collections.abc.Iterator) self.assertEqual(list(s), [3, 2, 1]) def test_contains(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) self.assertIn(1, s) def test_bool(self): # Refs #23664 s = OrderedSet() self.assertFalse(s) s.add(1) self.assertTrue(s) def test_len(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.add(2) self.assertEqual(len(s), 2) def test_repr(self): self.assertEqual(repr(OrderedSet()), "OrderedSet()") self.assertEqual(repr(OrderedSet([2, 3, 2, 1])), "OrderedSet([2, 3, 1])")
OrderedSetTests
python
mlflow__mlflow
mlflow/store/artifact/databricks_models_artifact_repo.py
{ "start": 1349, "end": 10035 }
class ____(ArtifactRepository): """ Performs storage operations on artifacts controlled by a Databricks-hosted model registry. Signed access URIs for the appropriate cloud storage locations are fetched from the MLflow service and used to download model artifacts. The artifact_uri is expected to be of the form - `models:/<model_name>/<model_version>` - `models:/<model_name>/<stage>` (refers to the latest model version in the given stage) - `models:/<model_name>/latest` (refers to the latest of all model versions) - `models://<profile>/<model_name>/<model_version or stage or 'latest'>` Note : This artifact repository is meant is to be instantiated by the ModelsArtifactRepository when the client is pointing to a Databricks-hosted model registry. """ def __init__( self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | None = None ) -> None: if not is_using_databricks_registry(artifact_uri, registry_uri): raise MlflowException( message="A valid databricks profile is required to instantiate this repository", error_code=INVALID_PARAMETER_VALUE, ) super().__init__(artifact_uri, tracking_uri, registry_uri) from mlflow.tracking.client import MlflowClient self.databricks_profile_uri = ( get_databricks_profile_uri_from_artifact_uri(artifact_uri) or registry_uri or mlflow.get_registry_uri() ) warn_on_deprecated_cross_workspace_registry_uri(self.databricks_profile_uri) client = MlflowClient(registry_uri=self.databricks_profile_uri) self.model_name, self.model_version = get_model_name_and_version(client, artifact_uri) # Use an isolated thread pool executor for chunk uploads/downloads to avoid a deadlock # caused by waiting for a chunk-upload/download task within a file-upload/download task. # See https://superfastpython.com/threadpoolexecutor-deadlock/#Deadlock_1_Submit_and_Wait_for_a_Task_Within_a_Task # for more details self.chunk_thread_pool = self._create_thread_pool() def _call_endpoint(self, json, endpoint): db_creds = get_databricks_host_creds(self.databricks_profile_uri) return http_request(host_creds=db_creds, endpoint=endpoint, method="GET", params=json) def _make_json_body(self, path, page_token=None): body = {"name": self.model_name, "version": self.model_version, "path": path} if page_token: body["page_token"] = page_token return body def list_artifacts(self, path: str | None = None) -> list[FileInfo]: infos = [] page_token = None if not path: path = "" while True: json_body = self._make_json_body(path, page_token) response = self._call_endpoint(json_body, REGISTRY_LIST_ARTIFACTS_ENDPOINT) try: response.raise_for_status() json_response = json.loads(response.text) except Exception: raise MlflowException( f"API request to list files under path `{path}` failed with status code " f"{response.status_code}. Response body: {response.text}" ) artifact_list = json_response.get("files", []) next_page_token = json_response.get("next_page_token", None) # If `path` is a file, ListArtifacts returns a single list element with the # same name as `path`. The list_artifacts API expects us to return an empty list in this # case, so we do so here. if ( len(artifact_list) == 1 and artifact_list[0]["path"] == path and not artifact_list[0]["is_dir"] ): return [] for output_file in artifact_list: artifact_size = None if output_file["is_dir"] else output_file["file_size"] infos.append(FileInfo(output_file["path"], output_file["is_dir"], artifact_size)) if len(artifact_list) == 0 or not next_page_token: break page_token = next_page_token return infos # TODO: Change the implementation of this to match how databricks_artifact_repo.py handles this def _get_signed_download_uri(self, path=None): if not path: path = "" json_body = self._make_json_body(path) response = self._call_endpoint(json_body, REGISTRY_ARTIFACT_PRESIGNED_URI_ENDPOINT) try: json_response = json.loads(response.text) except ValueError: raise MlflowException( f"API request to get presigned uri to for file under path `{path}` failed with" f" status code {response.status_code}. Response body: {response.text}" ) return json_response.get("signed_uri", None), json_response.get("headers", None) def _extract_headers_from_signed_url(self, headers): if headers is None: return {} filtered_headers = filter(lambda h: "name" in h and "value" in h, headers) return {header.get("name"): header.get("value") for header in filtered_headers} def _parallelized_download_from_cloud( self, signed_uri, headers, file_size, dst_local_file_path, dst_run_relative_artifact_path ): from mlflow.utils.databricks_utils import get_databricks_env_vars with remove_on_error(dst_local_file_path): parallel_download_subproc_env = os.environ.copy() parallel_download_subproc_env.update( get_databricks_env_vars(self.databricks_profile_uri) ) failed_downloads = parallelized_download_file_using_http_uri( thread_pool_executor=self.chunk_thread_pool, http_uri=signed_uri, download_path=dst_local_file_path, remote_file_path=dst_run_relative_artifact_path, file_size=file_size, # URI type is not known in this context uri_type=None, chunk_size=MLFLOW_MULTIPART_DOWNLOAD_CHUNK_SIZE.get(), env=parallel_download_subproc_env, headers=headers, ) if failed_downloads: new_signed_uri, new_headers = self._get_signed_download_uri( dst_run_relative_artifact_path ) new_headers = self._extract_headers_from_signed_url(new_headers) download_chunk_retries( chunks=list(failed_downloads), http_uri=new_signed_uri, headers=new_headers, download_path=dst_local_file_path, ) def _download_file(self, remote_file_path, local_path): try: parent_dir, _ = posixpath.split(remote_file_path) file_infos = self.list_artifacts(parent_dir) file_info = [info for info in file_infos if info.path == remote_file_path] file_size = file_info[0].file_size if len(file_info) == 1 else None signed_uri, raw_headers = self._get_signed_download_uri(remote_file_path) headers = {} if raw_headers is not None: # Don't send None to _extract_headers_from_signed_url headers = self._extract_headers_from_signed_url(raw_headers) if ( not file_size or file_size <= MLFLOW_MULTIPART_DOWNLOAD_CHUNK_SIZE.get() or not MLFLOW_ENABLE_MULTIPART_DOWNLOAD.get() ): download_file_using_http_uri( signed_uri, local_path, MLFLOW_MULTIPART_DOWNLOAD_CHUNK_SIZE.get(), headers ) else: self._parallelized_download_from_cloud( signed_uri, headers, file_size, local_path, remote_file_path, ) except Exception as err: raise MlflowException(err) def log_artifact(self, local_file, artifact_path=None): raise MlflowException("This repository does not support logging artifacts.") def log_artifacts(self, local_dir, artifact_path=None): raise MlflowException("This repository does not support logging artifacts.") def delete_artifacts(self, artifact_path=None): raise NotImplementedError("This artifact repository does not support deleting artifacts")
DatabricksModelsArtifactRepository
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 291907, "end": 293400 }
class ____(AssignmentNode): # A combined packing/unpacking assignment: # # a, b, c = d, e, f # # This has been rearranged by the parser into # # a = d ; b = e ; c = f # # but we must evaluate all the right hand sides # before assigning to any of the left hand sides. # # stats [AssignmentNode] The constituent assignments child_attrs = ["stats"] def analyse_declarations(self, env): for stat in self.stats: stat.analyse_declarations(env) def analyse_expressions(self, env): self.stats = [stat.analyse_types(env, use_temp=1) for stat in self.stats] for stat in self.stats: stat._check_const_assignment(stat) return self # def analyse_expressions(self, env): # for stat in self.stats: # stat.analyse_expressions_1(env, use_temp=1) # for stat in self.stats: # stat.analyse_expressions_2(env) def generate_execution_code(self, code): code.mark_pos(self.pos) for stat in self.stats: stat.generate_rhs_evaluation_code(code) for stat in self.stats: stat.generate_assignment_code(code) def generate_function_definitions(self, env, code): for stat in self.stats: stat.generate_function_definitions(env, code) def annotate(self, code): for stat in self.stats: stat.annotate(code)
ParallelAssignmentNode
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0070_make_md5_field_nullable.py
{ "start": 149, "end": 526 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0069_migrate_protected_projects"), ] operations = [ migrations.AlterField( model_name="importedfile", name="md5", field=models.CharField(max_length=255, null=True, verbose_name="MD5 checksum"), ), ]
Migration
python
scrapy__scrapy
scrapy/exporters.py
{ "start": 901, "end": 3825 }
class ____(ABC): def __init__(self, *, dont_fail: bool = False, **kwargs: Any): self._kwargs: dict[str, Any] = kwargs self._configure(kwargs, dont_fail=dont_fail) def _configure(self, options: dict[str, Any], dont_fail: bool = False) -> None: """Configure the exporter by popping options from the ``options`` dict. If dont_fail is set, it won't raise an exception on unexpected options (useful for using with keyword arguments in subclasses ``__init__`` methods) """ self.encoding: str | None = options.pop("encoding", None) self.fields_to_export: Mapping[str, str] | Iterable[str] | None = options.pop( "fields_to_export", None ) self.export_empty_fields: bool = options.pop("export_empty_fields", False) self.indent: int | None = options.pop("indent", None) if not dont_fail and options: raise TypeError(f"Unexpected options: {', '.join(options.keys())}") @abstractmethod def export_item(self, item: Any) -> None: raise NotImplementedError def serialize_field( self, field: Mapping[str, Any] | Field, name: str, value: Any ) -> Any: serializer: Callable[[Any], Any] = field.get("serializer", lambda x: x) return serializer(value) def start_exporting(self) -> None: # noqa: B027 pass def finish_exporting(self) -> None: # noqa: B027 pass def _get_serialized_fields( self, item: Any, default_value: Any = None, include_empty: bool | None = None ) -> Iterable[tuple[str, Any]]: """Return the fields to export as an iterable of tuples (name, serialized_value) """ item = ItemAdapter(item) if include_empty is None: include_empty = self.export_empty_fields if self.fields_to_export is None: field_iter = item.field_names() if include_empty else item.keys() elif isinstance(self.fields_to_export, Mapping): if include_empty: field_iter = self.fields_to_export.items() else: field_iter = ( (x, y) for x, y in self.fields_to_export.items() if x in item ) elif include_empty: field_iter = self.fields_to_export else: field_iter = (x for x in self.fields_to_export if x in item) for field_name in field_iter: if isinstance(field_name, str): item_field, output_field = field_name, field_name else: item_field, output_field = field_name if item_field in item: field_meta = item.get_field_meta(item_field) value = self.serialize_field(field_meta, output_field, item[item_field]) else: value = default_value yield output_field, value
BaseItemExporter
python
google__jax
jax/experimental/mosaic/gpu/layout_inference.py
{ "start": 61009, "end": 73738 }
class ____: type: ir.Type layout: cs.Constant def assign_layouts(solution: dict[ValueSite, cs.Constant]) -> None: """Assigns the layouts in `solution` to the MLIR ops they belong to. This function requires that, for each MLIR op that appears in `solution`, `solution` contains a layout assignment for all of its `vector`, TMEM, and SMEM operands and results. Block arguments are ignored. """ solution_sorted_by_op = sorted( solution.items(), key=lambda kv: id(kv[0].operation) ) solution_per_op = itertools.groupby( solution_sorted_by_op, key=lambda kv: kv[0].operation ) for op, assignments in solution_per_op: assignments_sorted_by_type = sorted(assignments, key=lambda kv: kv[0].type) assignments_by_type = { ty: list(group) for ty, group in itertools.groupby( assignments_sorted_by_type, key=lambda kv: kv[0].type ) } in_assignments = assignments_by_type.get(VariableType.OPERAND, []) out_assignments = assignments_by_type.get(VariableType.RESULT, []) index = lambda kv: kv[0].index in_tls = [ _TypeAndLayout(v.value.type, ce) for v, ce in sorted(in_assignments, key=index) ] out_tls = [ _TypeAndLayout(v.value.type, ce) for v, ce in sorted(out_assignments, key=index) ] in_layouts = [ tl.layout.value for tl in in_tls if isinstance(tl.layout, cs.RegisterLayout) ] out_layouts = [ tl.layout.value for tl in out_tls if isinstance(tl.layout, cs.RegisterLayout) ] in_tmem_layouts = [ tl.layout.value for tl in in_tls if isinstance(tl.layout, cs.TMEMLayout) ] out_tmem_layouts = [ tl.layout.value for tl in out_tls if isinstance(tl.layout, cs.TMEMLayout) ] in_transforms = [ tl for tl in in_tls if isinstance(tl.layout, cs.SMEMTiling) ] out_transforms = [ tl for tl in out_tls if isinstance(tl.layout, cs.SMEMTiling) ] if inference_utils.should_have_in_layout(op): attrs = [layouts_lib.to_layout_attr(l) for l in in_layouts] op.attributes["in_layouts"] = ir.ArrayAttr.get(attrs) if inference_utils.should_have_out_layout(op): attrs = [layouts_lib.to_layout_attr(l) for l in out_layouts] op.attributes["out_layouts"] = ir.ArrayAttr.get(attrs) if inference_utils.should_have_in_tmem_layout(op): attrs = [layouts_lib.to_layout_attr(l) for l in in_tmem_layouts] op.attributes["in_tmem_layouts"] = ir.ArrayAttr.get(attrs) if inference_utils.should_have_out_tmem_layout(op): attrs = [layouts_lib.to_layout_attr(l) for l in out_tmem_layouts] op.attributes["out_tmem_layouts"] = ir.ArrayAttr.get(attrs) def _to_transform_attrs( transforms: list[_TypeAndLayout], ) -> list[ir.ArrayAttr]: all_attrs: list[ir.ArrayAttr] = [] for tl in transforms: assert isinstance(tl.layout, cs.SMEMTiling) # make pytype happy attrs = [] if tl.layout.value is not None: attrs.append(layouts_lib.to_transform_attr(tl.layout.value)) swizzle = _compute_swizzle(tl.type, tl.layout.value) attrs.append(layouts_lib.to_transform_attr(swizzle)) all_attrs.append(ir.ArrayAttr.get(attrs)) return all_attrs if inference_utils.should_have_in_transforms(op): attrs = _to_transform_attrs(in_transforms) op.attributes["in_transforms"] = ir.ArrayAttr.get(attrs) if inference_utils.should_have_out_transforms(op): attrs = _to_transform_attrs(out_transforms) op.attributes["out_transforms"] = ir.ArrayAttr.get(attrs) _ensure_all_layouts_are_set(op) def vector_value_sites(op: ir.OpView) -> list[ValueSite]: """Returns all the vector operands and results for the given op.""" value_sites = [ ValueSite(op, VariableType.OPERAND, i) for i, o in enumerate(op.operands) if is_vector(o) ] value_sites.extend([ ValueSite(op, VariableType.RESULT, i) for i, o in enumerate(op.results) if is_vector(o) ]) return value_sites def producer_result(operand: ValueSite) -> ValueSite: """Given an operand, returns the corresponding result in its producer. When the producer is a block, we return the corresponding operand in the operation that owns the block. """ assert operand.type == VariableType.OPERAND value = operand.value producer = value.owner if isinstance(producer, ir.Operation): index = list(producer.results).index(value) return ValueSite(producer.opview, VariableType.RESULT, index) if isinstance(producer, ir.Block): index = list(producer.arguments).index(value) region_index = list(producer.owner.regions).index(producer.region) return ValueSite(producer.owner, VariableType.ARGUMENT, index, region_index) raise TypeError( f"Producer {producer} is not an operation nor a block: {type(producer)}." ) def consumer_operands(result: ValueSite) -> Sequence[ValueSite]: """Given a result or an argument, returns the corresponding operands in its consumers.""" assert result.type in (VariableType.RESULT, VariableType.ARGUMENT) consumer_operands: list[ValueSite] = [] # The layout can also be chosen from the layout of the consumers of the # results. for use in result.value.uses: consumer = use.owner.opview # pytype: disable=attribute-error index = use.operand_number consumer_operands.append(ValueSite(consumer, VariableType.OPERAND, index)) return consumer_operands def derive_hints_and_constraints( value_sites_for_variable: ValueSitesForVariable, ) -> tuple[list[Hint], list[cs.Relayout]]: """Derives propagation hints from the given variable mapping.""" hints: list[Hint] = [] constraints: list[cs.Relayout] = [] variable_for_value_site: dict[ValueSite, cs.Variable] = {} for variable, value_sites in value_sites_for_variable.items(): for value_site in value_sites: if value_site in variable_for_value_site: raise ValueError( f"{value_site} is mapped to both {variable} and " f"{variable_for_value_site[value_site]}" ) variable_for_value_site |= {k: variable for k in value_sites} visited: set[cs.Variable] = set() for variable, value_sites in value_sites_for_variable.items(): producers: list[cs.Variable] = [] consumers: list[cs.Variable] = [] for value_site in value_sites: # We can only relayout variables that are in registers. if value_site.memory_space != MemorySpace.REG: continue if value_site.type == VariableType.OPERAND: pr = producer_result(value_site) producer_variable = variable_for_value_site[pr] producers.append(producer_variable) # Only add the constraint if we haven't already created that constraint # when processing this variable as one of the producer's consumers. if producer_variable not in visited: # The producer of a variable must be relayout-able to the variable. constraints.append(cs.Relayout(producer_variable, variable)) elif value_site.type in (VariableType.RESULT, VariableType.ARGUMENT): for co in consumer_operands(value_site): consumer_variable = variable_for_value_site[co] consumers.append(consumer_variable) # Only add the constraint if we haven't already created that # constraint when processing this variable as the consumer's producer. if consumer_variable not in visited: # A variable must be relayout-able to its consumers. constraints.append(cs.Relayout(variable, consumer_variable)) visited.add(variable) if producers: least_replicated_producer = cs.LeastReplicated(tuple(producers)) hint_expr = cs.MostReplicated((least_replicated_producer, *consumers)) hints.append(Hint(variable, hint_expr)) elif consumers: hint_expr = cs.MostReplicated(tuple(consumers)) hints.append(Hint(variable, hint_expr)) return hints, constraints def is_terminator(op: ir.OpView) -> bool: return isinstance(op, (scf.YieldOp, scf.ConditionOp)) def traverse_op( op: ir.OpView, callback: Callable[[ir.OpView], None], ): """Traverses the operation and applies the callback in pre-order fashion. Skips recursing into `mgpu.CustomPrimitiveOp`s, and assumes that the values iterated on are not being modified. """ callback(op) # The block of a mosaic_gpu.custom_primitive op is already lowered so it # should not be traversed. if not isinstance(op, mgpu.CustomPrimitiveOp): for region in op.operation.regions: for block in region: for block_op in block.operations: traverse_op(block_op, callback) def infer_layout( module: ir.Module, *, fuel: int = _DEFAULT_LAYOUT_INFERENCE_FUEL ): """Infers layouts for the given module. * If there are vector (respectively SMEM refs, TMEM refs) operands, `in_layouts` (respectively `in_transforms`, `in_tmem_layouts`) will be set and contain one element per relevant argument in the memory space. * If there are vector (respectively SMEM refs, TMEM refs) outputs, `out_layouts` (respectively `out_transforms`, `out_tmem_layouts`) will be set and contain one element per relevant argument in the memory space. * Any of these attributes is guaranteed to not be set if there is no relevant input/output in the corresponding memory space. The fuel is provided in order to limit the number of attempts made by the solver. """ global_constraint_system: cs.ConstraintSystem | cs.Unsatisfiable global_constraint_system = cs.ConstraintSystem() hints: list[Hint] = [] ctx = DerivationContext() def gather_constraints(op: ir.Operation): # Terminator ops are handled directly by the op whose region they belong to. # This is because they need to be in sync with their parent op's inputs and # outputs---and the parent op's constraints therefore need to take them into # account. if is_terminator(op): return should_have_layout = ( inference_utils.should_have_layout(op) or inference_utils.should_have_tmem_layout(op) or inference_utils.should_have_transforms(op) ) if not should_have_layout: return rule = _constraint_system_derivation_rules.get(op.OPERATION_NAME, None) # pytype: disable=attribute-error if rule is None: raise NotImplementedError(f"No layout inference rule defined for {op}") constraint_system, mapping, op_hints = rule(ctx, op) ctx.update(mapping) nonlocal global_constraint_system global_constraint_system &= constraint_system hints.extend(op_hints) for op in module.body: traverse_op(op, gather_constraints) if isinstance(global_constraint_system, cs.Unsatisfiable): raise ValueError( "Failed to infer a possible set of layouts. This should only happen if " "user-provided layout casts are unsatisfiable." ) propagation_hints, constraints = derive_hints_and_constraints(ctx.value_sites_for_variable) hints = reduce_hints(hints + propagation_hints, global_constraint_system.assignments) # pytype: disable=attribute-error global_constraint_system &= cs.ConstraintSystem(constraints=constraints) assert not isinstance(global_constraint_system, cs.Unsatisfiable) # Add additional (redundant) constraints which helps the search converge # faster. global_constraint_system = cs.saturate_distinct_from_splat( global_constraint_system ) assert not isinstance(global_constraint_system, cs.Unsatisfiable) global_constraint_system = cs.saturate_divides_constraints_for_equal_vars( global_constraint_system ) # Attempt to find assignments that satisfy the constraint system. solution, remaining_fuel = find_assignments_for( list(ctx.value_sites_for_variable.keys()), global_constraint_system, hints, fuel=fuel, ) if logging.vlog_is_on(1): print("Finding a solution (or exhausting the entire search space) " f"consumed {fuel - remaining_fuel}/{fuel} fuel.") if isinstance(solution, cs.Unsatisfiable): raise ValueError( "Failed to infer a possible set of layouts. This should only happen if " "user-provided layout casts are unsatisfiable." ) layout_for_value_site = { k: solution[v] for v, ks in ctx.value_sites_for_variable.items() for k in ks } # Assigns the layouts that we found to the ops. assign_layouts(layout_for_value_site) # Sanity check: ensure that all ops have the right number of in/out layouts. for op in module.body: traverse_op(op, _ensure_all_layouts_are_set)
_TypeAndLayout
python
pytest-dev__pytest-cov
src/pytest_cov/plugin.py
{ "start": 2236, "end": 6915 }
class ____(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): report_type, file = values namespace.cov_report[report_type] = file # coverage.py doesn't set a default file for markdown output_format if report_type in ['markdown', 'markdown-append'] and file is None: namespace.cov_report[report_type] = 'coverage.md' if all(x in namespace.cov_report for x in ['markdown', 'markdown-append']): self._validate_markdown_dest_files(namespace.cov_report, parser) def _validate_markdown_dest_files(self, cov_report_options, parser): markdown_file = cov_report_options['markdown'] markdown_append_file = cov_report_options['markdown-append'] if markdown_file == markdown_append_file: error_message = f"markdown and markdown-append options cannot point to the same file: '{markdown_file}'." error_message += ' Please redirect one of them using :DEST (e.g. --cov-report=markdown:dest_file.md)' parser.error(error_message) def pytest_addoption(parser): """Add options to control coverage.""" group = parser.getgroup('cov', 'coverage reporting with distributed testing support') group.addoption( '--cov', action='append', default=[], metavar='SOURCE', nargs='?', const=True, dest='cov_source', help='Path or package name to measure during execution (multi-allowed). ' 'Use --cov= to not do any source filtering and record everything.', ) group.addoption( '--cov-reset', action='store_const', const=[], dest='cov_source', help='Reset cov sources accumulated in options so far. ', ) group.addoption( '--cov-report', action=StoreReport, default={}, metavar='TYPE', type=validate_report, help='Type of report to generate: term, term-missing, ' 'annotate, html, xml, json, markdown, markdown-append, lcov (multi-allowed). ' 'term, term-missing may be followed by ":skip-covered". ' 'annotate, html, xml, json, markdown, markdown-append and lcov may be followed by ":DEST" ' 'where DEST specifies the output location. ' 'Use --cov-report= to not generate any output.', ) group.addoption( '--cov-config', action='store', default='.coveragerc', metavar='PATH', help='Config file for coverage. Default: .coveragerc', ) group.addoption( '--no-cov-on-fail', action='store_true', default=False, help='Do not report coverage if test run fails. Default: False', ) group.addoption( '--no-cov', action='store_true', default=False, help='Disable coverage report completely (useful for debuggers). Default: False', ) group.addoption( '--cov-fail-under', action='store', metavar='MIN', type=validate_fail_under, help='Fail if the total coverage is less than MIN.', ) group.addoption( '--cov-append', action='store_true', default=False, help='Do not delete coverage but append to current. Default: False', ) group.addoption( '--cov-branch', action='store_true', default=None, help='Enable branch coverage.', ) group.addoption( '--cov-precision', type=int, default=None, help='Override the reporting precision.', ) group.addoption( '--cov-context', action='store', metavar='CONTEXT', type=validate_context, help='Dynamic contexts to use. "test" for now.', ) def _prepare_cov_source(cov_source): """ Prepare cov_source so that: --cov --cov=foobar is equivalent to --cov (cov_source=None) --cov=foo --cov=bar is equivalent to cov_source=['foo', 'bar'] """ return None if True in cov_source else [path for path in cov_source if path is not True] @pytest.hookimpl(tryfirst=True) def pytest_load_initial_conftests(early_config, parser, args): options = early_config.known_args_namespace no_cov = options.no_cov_should_warn = False for arg in args: arg = str(arg) if arg == '--no-cov': no_cov = True elif arg.startswith('--cov') and no_cov: options.no_cov_should_warn = True break if early_config.known_args_namespace.cov_source: plugin = CovPlugin(options, early_config.pluginmanager) early_config.pluginmanager.register(plugin, '_cov')
StoreReport
python
has2k1__plotnine
plotnine/scales/scale_xy.py
{ "start": 7202, "end": 7279 }
class ____(scale_y_discrete): pass @dataclass(kw_only=True)
scale_y_ordinal
python
python-pillow__Pillow
Tests/test_imagegrab.py
{ "start": 208, "end": 5499 }
class ____: @pytest.mark.skipif( os.environ.get("USERNAME") == "ContainerAdministrator", reason="can't grab screen when running in Docker", ) @pytest.mark.skipif( sys.platform not in ("win32", "darwin"), reason="requires Windows or macOS" ) def test_grab(self) -> None: ImageGrab.grab() ImageGrab.grab(include_layered_windows=True) ImageGrab.grab(all_screens=True) im = ImageGrab.grab(bbox=(10, 20, 50, 80)) assert im.size == (40, 60) @skip_unless_feature("xcb") def test_grab_x11(self) -> None: try: if sys.platform not in ("win32", "darwin"): ImageGrab.grab() ImageGrab.grab(xdisplay="") except OSError as e: pytest.skip(str(e)) @pytest.mark.skipif(Image.core.HAVE_XCB, reason="tests missing XCB") def test_grab_no_xcb(self) -> None: if ( sys.platform not in ("win32", "darwin") and not shutil.which("gnome-screenshot") and not shutil.which("grim") and not shutil.which("spectacle") ): with pytest.raises(OSError) as e: ImageGrab.grab() assert str(e.value).startswith("Pillow was built without XCB support") with pytest.raises(OSError) as e: ImageGrab.grab(xdisplay="") assert str(e.value).startswith("Pillow was built without XCB support") @skip_unless_feature("xcb") def test_grab_invalid_xdisplay(self) -> None: with pytest.raises(OSError) as e: ImageGrab.grab(xdisplay="error.test:0.0") assert str(e.value).startswith("X connection failed") @pytest.mark.skipif(sys.platform != "win32", reason="Windows only") def test_grab_invalid_handle(self) -> None: with pytest.raises(OSError, match="unable to get device context for handle"): ImageGrab.grab(window=-1) with pytest.raises(OSError, match="screen grab failed"): ImageGrab.grab(window=0) def test_grabclipboard(self) -> None: if sys.platform == "darwin": subprocess.call(["screencapture", "-cx"]) ImageGrab.grabclipboard() elif sys.platform == "win32": p = subprocess.Popen(["powershell", "-command", "-"], stdin=subprocess.PIPE) p.stdin.write( b"""[Reflection.Assembly]::LoadWithPartialName("System.Drawing") [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $bmp = New-Object Drawing.Bitmap 200, 200 [Windows.Forms.Clipboard]::SetImage($bmp)""" ) p.communicate() ImageGrab.grabclipboard() else: if not shutil.which("wl-paste") and not shutil.which("xclip"): with pytest.raises( NotImplementedError, match="wl-paste or xclip is required for" r" ImageGrab.grabclipboard\(\) on Linux", ): ImageGrab.grabclipboard() @pytest.mark.skipif(sys.platform != "win32", reason="Windows only") def test_grabclipboard_file(self) -> None: p = subprocess.Popen(["powershell", "-command", "-"], stdin=subprocess.PIPE) assert p.stdin is not None p.stdin.write(rb'Set-Clipboard -Path "Tests\images\hopper.gif"') p.communicate() im = ImageGrab.grabclipboard() assert isinstance(im, list) assert len(im) == 1 assert os.path.samefile(im[0], "Tests/images/hopper.gif") @pytest.mark.skipif(sys.platform != "win32", reason="Windows only") def test_grabclipboard_png(self) -> None: p = subprocess.Popen(["powershell", "-command", "-"], stdin=subprocess.PIPE) assert p.stdin is not None p.stdin.write( rb"""$bytes = [System.IO.File]::ReadAllBytes("Tests\images\hopper.png") $ms = new-object System.IO.MemoryStream(, $bytes) [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [Windows.Forms.Clipboard]::SetData("PNG", $ms)""" ) p.communicate() im = ImageGrab.grabclipboard() assert isinstance(im, Image.Image) assert_image_equal_tofile(im, "Tests/images/hopper.png") @pytest.mark.skipif( ( sys.platform != "linux" or not all(shutil.which(cmd) for cmd in ("wl-paste", "wl-copy")) ), reason="Linux with wl-clipboard only", ) @pytest.mark.parametrize("ext", ("gif", "png", "ico")) def test_grabclipboard_wl_clipboard(self, ext: str) -> None: image_path = "Tests/images/hopper." + ext with open(image_path, "rb") as fp: subprocess.call(["wl-copy"], stdin=fp) im = ImageGrab.grabclipboard() assert isinstance(im, Image.Image) assert_image_equal_tofile(im, image_path) @pytest.mark.skipif( ( sys.platform != "linux" or not all(shutil.which(cmd) for cmd in ("wl-paste", "wl-copy")) ), reason="Linux with wl-clipboard only", ) @pytest.mark.parametrize("arg", ("text", "--clear")) def test_grabclipboard_wl_clipboard_errors(self, arg: str) -> None: subprocess.call(["wl-copy", arg]) assert ImageGrab.grabclipboard() is None
TestImageGrab
python
pytransitions__transitions
transitions/extensions/asyncio.py
{ "start": 7742, "end": 10410 }
class ____(Event): """A collection of transitions assigned to the same trigger""" async def trigger(self, model, *args, **kwargs): """Serially execute all transitions that match the current state, halting as soon as one successfully completes. Note that `AsyncEvent` triggers must be awaited. Args: args and kwargs: Optional positional or named arguments that will be passed onto the EventData object, enabling arbitrary state information to be passed on to downstream triggered functions. Returns: boolean indicating whether or not a transition was successfully executed (True if successful, False if not). """ func = partial(self._trigger, EventData(None, self, self.machine, model, args=args, kwargs=kwargs)) return await self.machine.process_context(func, model) async def _trigger(self, event_data): event_data.state = self.machine.get_state(getattr(event_data.model, self.machine.model_attribute)) try: if self._is_valid_source(event_data.state): await self._process(event_data) except BaseException as err: # pylint: disable=broad-except; Exception will be handled elsewhere _LOGGER.error("%sException was raised while processing the trigger '%s': %s", self.machine.name, event_data.event.name, repr(err)) event_data.error = err if self.machine.on_exception: await self.machine.callbacks(self.machine.on_exception, event_data) else: raise finally: try: await self.machine.callbacks(self.machine.finalize_event, event_data) _LOGGER.debug("%sExecuted machine finalize callbacks", self.machine.name) except BaseException as err: # pylint: disable=broad-except; Exception will be handled elsewhere _LOGGER.error("%sWhile executing finalize callbacks a %s occurred: %s.", self.machine.name, type(err).__name__, str(err)) return event_data.result async def _process(self, event_data): await self.machine.callbacks(self.machine.prepare_event, event_data) _LOGGER.debug("%sExecuted machine preparation callbacks before conditions.", self.machine.name) for trans in self.transitions[event_data.state.name]: event_data.transition = trans event_data.result = await trans.execute(event_data) if event_data.result: break
AsyncEvent
python
huggingface__transformers
tests/models/olmo2/test_modeling_olmo2.py
{ "start": 6773, "end": 14812 }
class ____(unittest.TestCase): def setUp(self): cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) def test_model_1b_logits_bfloat16(self): input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]] model = Olmo2ForCausalLM.from_pretrained("allenai/OLMo-2-0425-1B").to(torch_device, torch.bfloat16) out = model(torch.tensor(input_ids, device=torch_device)).logits.float() # Expected mean on dim = -1 expectations = Expectations( { ("cuda", 8): [[-5.6700, -6.5557, -3.1545, -2.7418, -5.5887, -4.5179, -4.9077, -4.6530]], } ) EXPECTED_MEAN = torch.tensor(expectations.get_expectation(), device=torch_device) torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2) # slicing logits[0, 0, 0:30] expectations = Expectations( { ("cuda", 8): [2.65625, -5.25, -4.9375, -4.53125, -6.5, -3.828125, -4.15625, -4.1875, -7.0625, -4.71875, -3.609375, -3.09375, -4.59375, -2.640625, -5.25, 0.39453125, 1.3828125, 1.2265625, 1.0078125, 0.57421875, 0.330078125, -0.287109375, -0.3671875, 0.1943359375, -0.0732421875, -6.6875, -4.75, -6.4375, -0.625, -2.625], } ) # fmt: skip EXPECTED_SLICE = torch.tensor(expectations.get_expectation(), device=torch_device) torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2) def test_model_7b_logits(self): input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]] model = Olmo2ForCausalLM.from_pretrained("shanearora/OLMo2-7B-1124-hf").to(torch_device, dtype=torch.bfloat16) out = model(torch.tensor(input_ids, device=torch_device)).logits.float() # Expected mean on dim = -1 expectations = Expectations( { ("cuda", 8): [[-13.0518, -13.8897, -11.7999, -11.3222, -12.3441, -12.3884, -15.4874, -12.7365]], } ) EXPECTED_MEAN = torch.tensor(expectations.get_expectation(), device=torch_device) torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2) # slicing logits[0, 0, 0:30] expectations = Expectations( { ("cuda", 8): [-5.5, -14.4375, -13.8125, -14.875, -14.125, -13.4375, -13.8125, -12.25, -9.5, -12.9375, -11.6875, -6.09375, -12.1875, -6.5, -11.3125, -7.34375, -6.5625, -6.71875, -7.375, -7.96875, -8.0625, -8.1875, -8.75, -8.75, -8.875, -9.9375, -8.1875, -12.875, -7.84375, -11.625], } ) # fmt: skip EXPECTED_SLICE = torch.tensor(expectations.get_expectation(), device=torch_device) torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2) def test_model_7b_greedy_generation(self): EXPECTED_TEXT_COMPLETION = """Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light is the fastest speed possible, and 3) the speed of light is the same for all observers, regardless of their relative motion. The theory of relativity is based on the idea that the speed of light is constant. This means that""" prompt = "Simply put, the theory of relativity states that " tokenizer = AutoTokenizer.from_pretrained("shanearora/OLMo2-7B-1124-hf", device_map="auto") model = Olmo2ForCausalLM.from_pretrained("shanearora/OLMo2-7B-1124-hf", device_map="auto") input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.device) # greedy generation outputs generated_ids = model.generate(input_ids, max_new_tokens=64, top_p=None, temperature=1, do_sample=False) text = tokenizer.decode(generated_ids[0], skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, text) @require_tokenizers def test_simple_encode_decode(self): rust_tokenizer = AutoTokenizer.from_pretrained("shanearora/OLMo2-7B-1124-hf") self.assertEqual(rust_tokenizer.encode("This is a test"), [2028, 374, 264, 1296]) self.assertEqual(rust_tokenizer.decode([2028, 374, 264, 1296], skip_special_tokens=True), "This is a test") # bytefallback showcase self.assertEqual(rust_tokenizer.encode("生活的真谛是"), [21990, 76706, 9554, 89151, 39013, 249, 21043]) # fmt: skip self.assertEqual( rust_tokenizer.decode([21990, 76706, 9554, 89151, 39013, 249, 21043], skip_special_tokens=True), "生活的真谛是", ) # Inner spaces showcase self.assertEqual(rust_tokenizer.encode("Hi Hello"), [13347, 220, 22691]) self.assertEqual(rust_tokenizer.decode([13347, 220, 22691], skip_special_tokens=True), "Hi Hello") self.assertEqual(rust_tokenizer.encode("Hi Hello"), [13347, 256, 22691]) self.assertEqual(rust_tokenizer.decode([13347, 256, 22691], skip_special_tokens=True), "Hi Hello") self.assertEqual(rust_tokenizer.encode(""), []) self.assertEqual(rust_tokenizer.encode(" "), [220]) self.assertEqual(rust_tokenizer.encode(" "), [256]) self.assertEqual(rust_tokenizer.encode(" Hello"), [22691]) @pytest.mark.torch_export_test def test_export_static_cache(self): if version.parse(torch.__version__) < version.parse("2.4.0"): self.skipTest(reason="This test requires torch >= 2.4 to run.") from transformers.integrations.executorch import ( TorchExportableModuleWithStaticCache, convert_and_export_with_cache, ) olmo2_model = "shanearora/OLMo2-7B-1124-hf" tokenizer = AutoTokenizer.from_pretrained(olmo2_model, pad_token="</s>", padding_side="right") EXPECTED_TEXT_COMPLETION = [ "Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light", ] max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[ "input_ids" ].shape[-1] # Load model device = "cpu" # TODO (joao / export experts): should be on `torch_device`, but causes GPU OOM dtype = torch.bfloat16 cache_implementation = "static" attn_implementation = "sdpa" batch_size = 1 generation_config = GenerationConfig( use_cache=True, cache_implementation=cache_implementation, max_length=max_generation_length, cache_config={ "batch_size": batch_size, "max_cache_len": max_generation_length, }, ) model = Olmo2ForCausalLM.from_pretrained( olmo2_model, device_map=device, dtype=dtype, attn_implementation=attn_implementation, generation_config=generation_config, ) prompts = ["Simply put, the theory of relativity states that "] prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device) prompt_token_ids = prompt_tokens["input_ids"] max_new_tokens = max_generation_length - prompt_token_ids.shape[-1] # Static Cache + eager eager_generated_ids = model.generate( **prompt_tokens, max_new_tokens=max_new_tokens, do_sample=False, cache_implementation=cache_implementation ) eager_generated_text = tokenizer.batch_decode(eager_generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, eager_generated_text) # Static Cache + export exported_program = convert_and_export_with_cache(model) ep_generated_ids = TorchExportableModuleWithStaticCache.generate( exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens ) ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True) self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text)
Olmo2IntegrationTest
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 30414, "end": 32504 }
class ____(TestCase): def test_basic(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] D = mi.bucket(iterable, key=lambda x: 10 * (x // 10)) # In-order access self.assertEqual(list(D[10]), [10, 11, 12]) # Out of order access self.assertEqual(list(D[30]), [30, 31, 33]) self.assertEqual(list(D[20]), [20, 21, 22, 23]) self.assertEqual(list(D[40]), []) # Nothing in here! def test_in(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] D = mi.bucket(iterable, key=lambda x: 10 * (x // 10)) self.assertIn(10, D) self.assertNotIn(40, D) self.assertIn(20, D) self.assertNotIn(21, D) # Checking in-ness shouldn't advance the iterator self.assertEqual(next(D[10]), 10) def test_validator(self): iterable = count(0) key = lambda x: int(str(x)[0]) # First digit of each number validator = lambda x: 0 < x < 10 # No leading zeros D = mi.bucket(iterable, key, validator=validator) self.assertEqual(mi.take(3, D[1]), [1, 10, 11]) self.assertNotIn(0, D) # Non-valid entries don't return True self.assertNotIn(0, D._cache) # Don't store non-valid entries self.assertEqual(list(D[0]), []) def test_list(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] D = mi.bucket(iterable, key=lambda x: 10 * (x // 10)) self.assertEqual(list(D[10]), [10, 11, 12]) self.assertEqual(list(D[20]), [20, 21, 22, 23]) self.assertEqual(list(D[30]), [30, 31, 33]) self.assertEqual(set(D), {10, 20, 30}) def test_list_validator(self): iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33] key = lambda x: 10 * (x // 10) validator = lambda x: x != 20 D = mi.bucket(iterable, key, validator=validator) self.assertEqual(set(D), {10, 30}) self.assertEqual(list(D[10]), [10, 11, 12]) self.assertEqual(list(D[20]), []) self.assertEqual(list(D[30]), [30, 31, 33])
BucketTests
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 6390, "end": 7644 }
class ____(torch.autograd.Function): @staticmethod def forward(x, dim): device = x.device x = to_numpy(x) ind = np.argsort(x, axis=dim) ind_inv = np.argsort(ind, axis=dim) return ( torch.tensor(x, device=device), torch.tensor(ind, device=device), torch.tensor(ind_inv, device=device), ) @staticmethod def setup_context(ctx, inputs, output): _x, dim = inputs _, ind, ind_inv = output ctx.mark_non_differentiable(ind, ind_inv) ctx.save_for_backward(ind, ind_inv) ctx.save_for_forward(ind, ind_inv) ctx.dim = dim @staticmethod def backward(ctx, grad_output, _0, _1): ind, ind_inv = ctx.saved_tensors return NumpyTake.apply(grad_output, ind_inv, ind, ctx.dim), None @staticmethod def vmap(info, in_dims, x, dim): x_bdim, _ = in_dims x = x.movedim(x_bdim, 0) # wrap dim dim = dim if dim >= 0 else dim + x.dim() - 1 return NumpySort.apply(x, dim + 1), (0, 0, 0) @staticmethod def jvp(ctx, x_tangent, _): ind, ind_inv = ctx.saved_tensors return NumpyTake.apply(x_tangent, ind, ind_inv, ctx.dim), None, None
NumpySort
python
pytorch__pytorch
test/dynamo/test_fx_graph_runnable.py
{ "start": 2387, "end": 2564 }
class ____(logging.Formatter): def format(self, record): return record.payload.strip() trace_log = logging.getLogger("torch.__trace")
StructuredTracePayloadFormatter
python
coleifer__peewee
tests/extra_fields.py
{ "start": 1055, "end": 1488 }
class ____(ModelTestCase): requires = [Pickled] def test_pickle_field(self): a = {'k1': 'v1', 'k2': [0, 1, 2], 'k3': None} b = 'just a string' Pickled.create(data=a, key='a') Pickled.create(data=b, key='b') a_db = Pickled.get(Pickled.key == 'a') self.assertEqual(a_db.data, a) b_db = Pickled.get(Pickled.key == 'b') self.assertEqual(b_db.data, b)
TestPickleField
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10515, "end": 10936 }
class ____(_TenantsPermission): pass PermissionsOutputType = Union[ AliasPermissionOutput, ClusterPermissionOutput, CollectionsPermissionOutput, DataPermissionOutput, RolesPermissionOutput, UsersPermissionOutput, BackupsPermissionOutput, NodesPermissionOutput, TenantsPermissionOutput, ReplicatePermissionOutput, GroupsPermissionOutput, ] @dataclass
TenantsPermissionOutput
python
doocs__leetcode
solution/3100-3199/3102.Minimize Manhattan Distances/Solution.py
{ "start": 0, "end": 462 }
class ____: def minimumDistance(self, points: List[List[int]]) -> int: sl1 = SortedList() sl2 = SortedList() for x, y in points: sl1.add(x + y) sl2.add(x - y) ans = inf for x, y in points: sl1.remove(x + y) sl2.remove(x - y) ans = min(ans, max(sl1[-1] - sl1[0], sl2[-1] - sl2[0])) sl1.add(x + y) sl2.add(x - y) return ans
Solution
python
paramiko__paramiko
paramiko/_winapi.py
{ "start": 3634, "end": 7308 }
class ____: """ A memory map object which can have security attributes overridden. """ def __init__(self, name, length, security_attributes=None): self.name = name self.length = length self.security_attributes = security_attributes self.pos = 0 def __enter__(self): p_SA = ( ctypes.byref(self.security_attributes) if self.security_attributes else None ) INVALID_HANDLE_VALUE = -1 PAGE_READWRITE = 0x4 FILE_MAP_WRITE = 0x2 filemap = ctypes.windll.kernel32.CreateFileMappingW( INVALID_HANDLE_VALUE, p_SA, PAGE_READWRITE, 0, self.length, u(self.name), ) handle_nonzero_success(filemap) if filemap == INVALID_HANDLE_VALUE: raise Exception("Failed to create file mapping") self.filemap = filemap self.view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0) return self def seek(self, pos): self.pos = pos def write(self, msg): assert isinstance(msg, bytes) n = len(msg) if self.pos + n >= self.length: # A little safety. raise ValueError(f"Refusing to write {n} bytes") dest = self.view + self.pos length = ctypes.c_size_t(n) ctypes.windll.kernel32.RtlMoveMemory(dest, msg, length) self.pos += n def read(self, n): """ Read n bytes from mapped view. """ out = ctypes.create_string_buffer(n) source = self.view + self.pos length = ctypes.c_size_t(n) ctypes.windll.kernel32.RtlMoveMemory(out, source, length) self.pos += n return out.raw def __exit__(self, exc_type, exc_val, tb): ctypes.windll.kernel32.UnmapViewOfFile(self.view) ctypes.windll.kernel32.CloseHandle(self.filemap) ############################# # jaraco.windows.api.security # from WinNT.h READ_CONTROL = 0x00020000 STANDARD_RIGHTS_REQUIRED = 0x000F0000 STANDARD_RIGHTS_READ = READ_CONTROL STANDARD_RIGHTS_WRITE = READ_CONTROL STANDARD_RIGHTS_EXECUTE = READ_CONTROL STANDARD_RIGHTS_ALL = 0x001F0000 # from NTSecAPI.h POLICY_VIEW_LOCAL_INFORMATION = 0x00000001 POLICY_VIEW_AUDIT_INFORMATION = 0x00000002 POLICY_GET_PRIVATE_INFORMATION = 0x00000004 POLICY_TRUST_ADMIN = 0x00000008 POLICY_CREATE_ACCOUNT = 0x00000010 POLICY_CREATE_SECRET = 0x00000020 POLICY_CREATE_PRIVILEGE = 0x00000040 POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080 POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100 POLICY_AUDIT_LOG_ADMIN = 0x00000200 POLICY_SERVER_ADMIN = 0x00000400 POLICY_LOOKUP_NAMES = 0x00000800 POLICY_NOTIFICATION = 0x00001000 POLICY_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | POLICY_VIEW_LOCAL_INFORMATION | POLICY_VIEW_AUDIT_INFORMATION | POLICY_GET_PRIVATE_INFORMATION | POLICY_TRUST_ADMIN | POLICY_CREATE_ACCOUNT | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE | POLICY_SET_DEFAULT_QUOTA_LIMITS | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN | POLICY_SERVER_ADMIN | POLICY_LOOKUP_NAMES ) POLICY_READ = ( STANDARD_RIGHTS_READ | POLICY_VIEW_AUDIT_INFORMATION | POLICY_GET_PRIVATE_INFORMATION ) POLICY_WRITE = ( STANDARD_RIGHTS_WRITE | POLICY_TRUST_ADMIN | POLICY_CREATE_ACCOUNT | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE | POLICY_SET_DEFAULT_QUOTA_LIMITS | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN | POLICY_SERVER_ADMIN ) POLICY_EXECUTE = ( STANDARD_RIGHTS_EXECUTE | POLICY_VIEW_LOCAL_INFORMATION | POLICY_LOOKUP_NAMES )
MemoryMap
python
aio-libs__aiohttp
aiohttp/web_urldispatcher.py
{ "start": 14062, "end": 14863 }
class ____(AbstractResource): def __init__(self, prefix: str, *, name: str | None = None) -> None: assert not prefix or prefix.startswith("/"), prefix assert prefix in ("", "/") or not prefix.endswith("/"), prefix super().__init__(name=name) self._prefix = _requote_path(prefix) self._prefix2 = self._prefix + "/" @property def canonical(self) -> str: return self._prefix def add_prefix(self, prefix: str) -> None: assert prefix.startswith("/") assert not prefix.endswith("/") assert len(prefix) > 1 self._prefix = prefix + self._prefix self._prefix2 = self._prefix + "/" def raw_match(self, prefix: str) -> bool: return False # TODO: impl missing abstract methods
PrefixResource
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 21572, "end": 21942 }
class ____(TestCase): def test_with_iter(self): s = StringIO('One fish\nTwo fish') initial_words = [line.split()[0] for line in mi.with_iter(s)] # Iterable's items should be faithfully represented self.assertEqual(initial_words, ['One', 'Two']) # The file object should be closed self.assertTrue(s.closed)
WithIterTests
python
scrapy__scrapy
scrapy/middleware.py
{ "start": 916, "end": 6812 }
class ____(ABC): """Base class for implementing middleware managers""" component_name: str _compat_spider: Spider | None = None def __init__(self, *middlewares: Any, crawler: Crawler | None = None) -> None: self.crawler: Crawler | None = crawler if crawler is None: warnings.warn( f"MiddlewareManager.__init__() was called without the crawler argument" f" when creating {global_object_name(self.__class__)}." f" This is deprecated and the argument will be required in future Scrapy versions.", category=ScrapyDeprecationWarning, stacklevel=2, ) self.middlewares: tuple[Any, ...] = middlewares # Only process_spider_output and process_spider_exception can be None. # Only process_spider_output can be a tuple, and only until _async compatibility methods are removed. self.methods: dict[str, deque[Callable | tuple[Callable, Callable] | None]] = ( defaultdict(deque) ) self._mw_methods_requiring_spider: set[Callable] = set() for mw in middlewares: self._add_middleware(mw) @property def _spider(self) -> Spider: if self.crawler is not None: if self.crawler.spider is None: raise ValueError( f"{type(self).__name__} needs to access self.crawler.spider but it is None." ) return self.crawler.spider if self._compat_spider is not None: return self._compat_spider raise ValueError(f"{type(self).__name__} has no known Spider instance.") def _set_compat_spider(self, spider: Spider | None) -> None: if spider is None or self.crawler is not None: return # printing a deprecation warning is the caller's responsibility if self._compat_spider is None: self._compat_spider = spider elif self._compat_spider is not spider: raise RuntimeError( f"Different instances of Spider were passed to {type(self).__name__}:" f" {self._compat_spider} and {spider}" ) def _warn_spider_arg(self, method_name: str) -> None: if self.crawler: msg = ( f"Passing a spider argument to {type(self).__name__}.{method_name}() is deprecated" " and the passed value is ignored." ) else: msg = ( f"Passing a spider argument to {type(self).__name__}.{method_name}() is deprecated," f" {type(self).__name__} should be instantiated with a Crawler instance instead." ) warnings.warn(msg, category=ScrapyDeprecationWarning, stacklevel=3) @classmethod @abstractmethod def _get_mwlist_from_settings(cls, settings: Settings) -> list[Any]: raise NotImplementedError @classmethod def from_crawler(cls, crawler: Crawler) -> Self: mwlist = cls._get_mwlist_from_settings(crawler.settings) middlewares = [] enabled = [] for clspath in mwlist: try: mwcls = load_object(clspath) mw = build_from_crawler(mwcls, crawler) middlewares.append(mw) enabled.append(clspath) except NotConfigured as e: if e.args: logger.warning( "Disabled %(clspath)s: %(eargs)s", {"clspath": clspath, "eargs": e.args[0]}, extra={"crawler": crawler}, ) logger.info( "Enabled %(componentname)ss:\n%(enabledlist)s", { "componentname": cls.component_name, "enabledlist": pprint.pformat(enabled), }, extra={"crawler": crawler}, ) return cls(*middlewares, crawler=crawler) def _add_middleware(self, mw: Any) -> None: # noqa: B027 pass def _check_mw_method_spider_arg(self, method: Callable) -> None: if argument_is_required(method, "spider"): warnings.warn( f"{method.__qualname__}() requires a spider argument," f" this is deprecated and the argument will not be passed in future Scrapy versions." f" If you need to access the spider instance you can save the crawler instance" f" passed to from_crawler() and use its spider attribute.", category=ScrapyDeprecationWarning, stacklevel=2, ) self._mw_methods_requiring_spider.add(method) async def _process_chain( self, methodname: str, obj: _T, *args: Any, add_spider: bool = False, always_add_spider: bool = False, ) -> _T: methods = cast( "Iterable[Callable[Concatenate[_T, _P], _T]]", self.methods[methodname] ) for method in methods: if always_add_spider or ( add_spider and method in self._mw_methods_requiring_spider ): obj = await ensure_awaitable(method(obj, *(*args, self._spider))) else: obj = await ensure_awaitable(method(obj, *args)) return obj def open_spider(self, spider: Spider) -> Deferred[list[None]]: # pragma: no cover raise NotImplementedError( "MiddlewareManager.open_spider() is no longer implemented" " and will be removed in a future Scrapy version." ) def close_spider(self, spider: Spider) -> Deferred[list[None]]: # pragma: no cover raise NotImplementedError( "MiddlewareManager.close_spider() is no longer implemented" " and will be removed in a future Scrapy version." )
MiddlewareManager
python
allegroai__clearml
clearml/backend_api/services/v2_9/projects.py
{ "start": 83283, "end": 88259 }
class ____(Request): """ Update project information :param project: Project id :type project: str :param name: Project name. Unique within the company. :type name: str :param description: Project description :type description: str :param tags: User-defined tags list :type tags: Sequence[str] :param system_tags: System tags list. This field is reserved for system use, please don't use it. :type system_tags: Sequence[str] :param default_output_destination: The default output destination URL for new tasks under this project :type default_output_destination: str """ _service = "projects" _action = "update" _version = "2.9" _schema = { "definitions": {}, "properties": { "default_output_destination": { "description": "The default output destination URL for new tasks under this project", "type": "string", }, "description": {"description": "Project description", "type": "string"}, "name": { "description": "Project name. Unique within the company.", "type": "string", }, "project": {"description": "Project id", "type": "string"}, "system_tags": { "description": "System tags list. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": "array", }, "tags": { "description": "User-defined tags list", "items": {"type": "string"}, "type": "array", }, }, "required": ["project"], "type": "object", } def __init__( self, project: str, name: Optional[str] = None, description: Optional[str] = None, tags: Optional[List[str]] = None, system_tags: Optional[List[str]] = None, default_output_destination: Optional[str] = None, **kwargs: Any ) -> None: super(UpdateRequest, self).__init__(**kwargs) self.project = project self.name = name self.description = description self.tags = tags self.system_tags = system_tags self.default_output_destination = default_output_destination @schema_property("project") def project(self) -> str: return self._property_project @project.setter def project(self, value: str) -> None: if value is None: self._property_project = None return self.assert_isinstance(value, "project", six.string_types) self._property_project = value @schema_property("name") def name(self) -> Optional[str]: return self._property_name @name.setter def name(self, value: Optional[str]) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("description") def description(self) -> Optional[str]: return self._property_description @description.setter def description(self, value: Optional[str]) -> None: if value is None: self._property_description = None return self.assert_isinstance(value, "description", six.string_types) self._property_description = value @schema_property("tags") def tags(self) -> Optional[List[str]]: return self._property_tags @tags.setter def tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_tags = None return self.assert_isinstance(value, "tags", (list, tuple)) self.assert_isinstance(value, "tags", six.string_types, is_array=True) self._property_tags = value @schema_property("system_tags") def system_tags(self) -> Optional[List[str]]: return self._property_system_tags @system_tags.setter def system_tags(self, value: Optional[List[str]]) -> None: if value is None: self._property_system_tags = None return self.assert_isinstance(value, "system_tags", (list, tuple)) self.assert_isinstance(value, "system_tags", six.string_types, is_array=True) self._property_system_tags = value @schema_property("default_output_destination") def default_output_destination(self) -> Optional[str]: return self._property_default_output_destination @default_output_destination.setter def default_output_destination(self, value: Optional[str]) -> None: if value is None: self._property_default_output_destination = None return self.assert_isinstance(value, "default_output_destination", six.string_types) self._property_default_output_destination = value
UpdateRequest
python
getsentry__sentry
src/sentry/web/frontend/auth_channel_login.py
{ "start": 568, "end": 3271 }
class ____(AuthOrganizationLoginView): @method_decorator(never_cache) def handle(self, request, channel, resource_id): # type: ignore[override] # intentional signature change if request.subdomain is not None: return self.redirect(reverse("sentry-auth-organization", args=[request.subdomain])) config_data = request.GET.get("config_data", "") if not config_data: # NOTE: This provider_config may differ per provider # Allow providers to supply their own config_data, otherwise # construct one with the resource_id (NOT the sentry org id) provider = CHANNEL_PROVIDER_MAP[channel] config_data = provider.build_config(resource={"id": resource_id}) # Checking for duplicate orgs auth_provider_model = AuthProvider.objects.filter(provider=channel, config=config_data) if not auth_provider_model.exists(): # After moving away from partner plan we append "-non-partner" to the provider name # But coming to Sentry from partner's website would still use the partner provider name # So we need to check both auth_provider_model = AuthProvider.objects.filter( provider=f"{channel}-non-partner", config=config_data ) if not auth_provider_model.exists() or len(auth_provider_model) > 1: return self.redirect(reverse("sentry-login")) organization_id = auth_provider_model[0].organization_id try: slug = OrganizationMapping.objects.get(organization_id=organization_id).slug except OrganizationMapping.DoesNotExist: return self.redirect(reverse("sentry-login")) next_uri = self.get_next_uri(request) # If user has an active session within the same organization skip login if request.user.is_authenticated: if self.active_organization is not None: if self.active_organization.organization.id == organization_id: if is_valid_redirect(next_uri, allowed_hosts=(request.get_host())): return self.redirect(next_uri) return self.redirect(Organization.get_url(slug=slug)) # If user doesn't have active session within the same organization redirect to login for the # organization in the url org_auth_url = reverse("sentry-auth-organization", args=[slug]) redirect_url = ( org_auth_url + "?next=" + next_uri if is_valid_redirect(next_uri, allowed_hosts=(request.get_host())) else org_auth_url ) return self.redirect(redirect_url)
AuthChannelLoginView
python
pypa__pip
tests/unit/test_build_constraints.py
{ "start": 352, "end": 4271 }
class ____: """Test SubprocessBuildEnvironmentInstaller build constraints functionality.""" @mock.patch.dict(os.environ, {}, clear=True) def test_deprecation_check_no_pip_constraint(self) -> None: """Test no deprecation warning when PIP_CONSTRAINT is not set.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=False, ) # Should not raise any warning installer._deprecation_constraint_check() @mock.patch.dict(os.environ, {"PIP_CONSTRAINT": ""}) def test_deprecation_check_empty_pip_constraint(self) -> None: """Test no deprecation warning for empty PIP_CONSTRAINT.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=False, ) # Should not raise any warning since PIP_CONSTRAINT is empty installer._deprecation_constraint_check() @mock.patch.dict(os.environ, {"PIP_CONSTRAINT": " "}) def test_deprecation_check_whitespace_pip_constraint(self) -> None: """Test no deprecation warning for whitespace-only PIP_CONSTRAINT.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=False, ) # Should not raise any warning since PIP_CONSTRAINT is only whitespace installer._deprecation_constraint_check() @mock.patch.dict(os.environ, {"PIP_CONSTRAINT": "constraints.txt"}) def test_deprecation_check_feature_enabled(self) -> None: """Test no deprecation warning when build-constraint feature is enabled.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=True, ) # Should not raise any warning installer._deprecation_constraint_check() @mock.patch.dict(os.environ, {"PIP_CONSTRAINT": "constraints.txt"}) def test_deprecation_check_warning_shown(self) -> None: """Test deprecation warning emitted when PIP_CONSTRAINT is set and build-constraint is not enabled.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=False, ) with pytest.warns(PipDeprecationWarning) as warning_info: installer._deprecation_constraint_check() assert len(warning_info) == 1 message = str(warning_info[0].message) assert ( "Setting PIP_CONSTRAINT will not affect build constraints in the future" in message ) assert ( "to specify build constraints using " "--build-constraint or PIP_BUILD_CONSTRAINT" in message ) @mock.patch("pip._internal.build_env.call_subprocess") @mock.patch.dict(os.environ, {"PIP_CONSTRAINT": "constraints.txt"}) def test_install_calls_deprecation_check( self, mock_call_subprocess: mock.Mock, tmp_path: Path ) -> None: """Test install method calls deprecation check and proceeds with warning.""" finder = make_test_finder() installer = SubprocessBuildEnvironmentInstaller( finder, build_constraint_feature_enabled=False, ) prefix = _Prefix(str(tmp_path)) with pytest.warns(PipDeprecationWarning): installer.install( requirements=["setuptools"], prefix=prefix, kind="build dependencies", for_req=None, ) # Verify that call_subprocess was called (install proceeded after warning) mock_call_subprocess.assert_called_once()
TestSubprocessBuildEnvironmentInstaller
python
ansible__ansible
test/units/parsing/test_dataloader.py
{ "start": 7406, "end": 12328 }
class ____(unittest.TestCase): def setUp(self): self._loader = DataLoader() vault_secrets = [('default', TextVaultSecret('ansible'))] self._loader.set_vault_secrets(vault_secrets) self.test_vault_data_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'vault.yml') def tearDown(self): pass def test_get_text_file_contents_vaulted_yaml(self) -> None: content = self._loader.get_text_file_contents(self.test_vault_data_path) assert SourceWasEncrypted.is_tagged_on(content) def test_get_text_file_contents_non_vaulted_file(self) -> None: content = self._loader.get_text_file_contents(__file__) assert not SourceWasEncrypted.is_tagged_on(content) def test_get_real_file_vault(self): real_file_path = self._loader.get_real_file(self.test_vault_data_path) self.assertTrue(os.path.exists(real_file_path)) def test_get_real_file_vault_no_vault(self): self._loader.set_vault_secrets(None) self.assertRaises(AnsibleParserError, self._loader.get_real_file, self.test_vault_data_path) def test_get_real_file_vault_wrong_password(self): wrong_vault = [('default', TextVaultSecret('wrong_password'))] self._loader.set_vault_secrets(wrong_vault) self.assertRaises(AnsibleVaultError, self._loader.get_real_file, self.test_vault_data_path) def test_parse_from_vault_1_1_file(self): vaulted_data = """$ANSIBLE_VAULT;1.1;AES256 33343734386261666161626433386662623039356366656637303939306563376130623138626165 6436333766346533353463636566313332623130383662340a393835656134633665333861393331 37666233346464636263636530626332623035633135363732623332313534306438393366323966 3135306561356164310a343937653834643433343734653137383339323330626437313562306630 3035 """ with tempfile.NamedTemporaryFile(mode='w') as file: file.write(vaulted_data) file.flush() output = self._loader.load_from_file(file.name, cache='none') self.assertEqual(output, dict(foo='bar')) # no cache used self.assertFalse(self._loader._FILE_CACHE) # vault cache entry written output = self._loader.load_from_file(file.name, cache='vaulted') self.assertEqual(output, dict(foo='bar')) self.assertTrue(self._loader._FILE_CACHE) # cache entry used key = next(iter(self._loader._FILE_CACHE.keys())) modified = {'changed': True} self._loader._FILE_CACHE[key] = modified output = self._loader.load_from_file(file.name, cache='vaulted') self.assertEqual(output, modified) def test_get_text_file_contents(tmp_path: pathlib.Path) -> None: original_contents = 'Hello World' temp_file = tmp_path / 'valid.txt' temp_file.write_text(original_contents) loader = DataLoader() read_contents = loader.get_text_file_contents(str(temp_file)) assert read_contents == original_contents origin = Origin.get_tag(read_contents) assert origin.path == str(temp_file) assert origin.line_num is None assert origin.col_num is None assert origin.description is None @pytest.mark.parametrize("content,encoding", ( (b'\xa4\xa4\xb0\xea\xa4H', 'utf-8'), (b'\xa4\xa4\xb0\xea\xa4H', None), )) def test_get_text_file_contents_encoding_deprecation(content: bytes, encoding: str | None, tmp_path: pathlib.Path) -> None: temp = tmp_path / 'bogus_file' temp.write_bytes(content) loader = DataLoader() if encoding: # help text will imply that encoding is settable if non-empty expected_warning_pattern = f"could not be decoded as {encoding!r}.*Ensure the correct encoding was specified" else: expected_warning_pattern = "could not be decoded as 'utf-8'.*must be UTF-8 encoded" with emits_warnings(deprecation_pattern=expected_warning_pattern): loaded = loader.get_text_file_contents(str(temp), encoding=encoding) assert loaded == content.decode(encoding or 'utf-8', errors='surrogateescape') assert Origin.is_tagged_on(loaded) assert not SourceWasEncrypted.is_tagged_on(loaded) assert not TrustedAsTemplate.is_tagged_on(loaded) @pytest.mark.parametrize("encoding", ( None, 'utf-8', 'big5', )) def test_get_text_file_contents_strict(encoding: str | None) -> None: text_content = '中文' content = text_content.encode(encoding or 'utf-8') with tempfile.NamedTemporaryFile(mode='wb') as temp: temp.write(content) temp.flush() loader = DataLoader() loaded = loader.get_text_file_contents(temp.name, encoding=encoding) assert loaded == text_content assert Origin.is_tagged_on(loaded) assert not SourceWasEncrypted.is_tagged_on(loaded) assert not TrustedAsTemplate.is_tagged_on(loaded)
TestDataLoaderWithVault
python
langchain-ai__langchain
libs/langchain/langchain_classic/output_parsers/combining.py
{ "start": 220, "end": 1980 }
class ____(BaseOutputParser[dict[str, Any]]): """Combine multiple output parsers into one.""" parsers: list[BaseOutputParser] @classmethod @override def is_lc_serializable(cls) -> bool: return True @pre_init def validate_parsers(cls, values: dict[str, Any]) -> dict[str, Any]: """Validate the parsers.""" parsers = values["parsers"] if len(parsers) < _MIN_PARSERS: msg = "Must have at least two parsers" raise ValueError(msg) for parser in parsers: if parser._type == "combining": # noqa: SLF001 msg = "Cannot nest combining parsers" raise ValueError(msg) if parser._type == "list": # noqa: SLF001 msg = "Cannot combine list parsers" raise ValueError(msg) return values @property def _type(self) -> str: """Return the type key.""" return "combining" def get_format_instructions(self) -> str: """Instructions on how the LLM output should be formatted.""" initial = f"For your first output: {self.parsers[0].get_format_instructions()}" subsequent = "\n".join( f"Complete that output fully. Then produce another output, separated by two newline characters: {p.get_format_instructions()}" # noqa: E501 for p in self.parsers[1:] ) return f"{initial}\n{subsequent}" def parse(self, text: str) -> dict[str, Any]: """Parse the output of an LLM call.""" texts = text.split("\n\n") output = {} for txt, parser in zip(texts, self.parsers, strict=False): output.update(parser.parse(txt.strip())) return output
CombiningOutputParser
python
charliermarsh__ruff
scripts/ty_benchmark/src/benchmark/venv.py
{ "start": 107, "end": 2597 }
class ____: project_path: Path def __init__(self, path: Path): self.project_path = path @property def path(self) -> Path: return self.project_path / "venv" @property def name(self) -> str: """The name of the virtual environment directory.""" return self.path.name @property def python(self) -> Path: """Returns the path to the python executable""" return self.script("python") @property def bin(self) -> Path: bin_dir = "scripts" if sys.platform == "win32" else "bin" return self.path / bin_dir def script(self, name: str) -> Path: extension = ".exe" if sys.platform == "win32" else "" return self.bin / f"{name}{extension}" @staticmethod def create(parent: Path, python_version: str) -> Venv: """Creates a new, empty virtual environment.""" command = [ "uv", "venv", "--quiet", "--python", python_version, "venv", ] try: subprocess.run( command, cwd=parent, check=True, capture_output=True, text=True ) except subprocess.CalledProcessError as e: raise RuntimeError(f"Failed to create venv: {e.stderr}") return Venv(parent) def install(self, pip_install_args: list[str]) -> None: """Installs the dependencies required to type check the project.""" logging.debug(f"Installing dependencies: {', '.join(pip_install_args)}") command = [ "uv", "pip", "install", "--python", self.python.as_posix(), "--quiet", # We pass `--exclude-newer` to ensure that type-checking of one of # our projects isn't unexpectedly broken by a change in the # annotations of one of that project's dependencies "--exclude-newer", "2025-11-17T00:00:00Z", "mypy", # We need to install mypy into the virtual environment or it fails to load plugins. *pip_install_args, ] try: subprocess.run( command, cwd=self.project_path, check=True, capture_output=True, text=True, ) except subprocess.CalledProcessError as e: raise RuntimeError(f"Failed to install dependencies: {e.stderr}")
Venv
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/oracle/cx_oracle.py
{ "start": 24040, "end": 24162 }
class ____(sqltypes.Unicode): def get_dbapi_type(self, dbapi): return dbapi.LONG_STRING
_OracleUnicodeStringCHAR
python
walkccc__LeetCode
solutions/2423. Remove Letter To Equalize Frequency/2423.py
{ "start": 0, "end": 404 }
class ____: def equalFrequency(self, word: str) -> bool: count = collections.Counter(word) # Try to remove each letter, then check if the frequency of all the letters # in `word` are equal. for c in word: count[c] -= 1 if count[c] == 0: del count[c] if min(count.values()) == max(count.values()): return True count[c] += 1 return False
Solution
python
pypa__pipenv
pipenv/patched/pip/_internal/models/link.py
{ "start": 1031, "end": 3125 }
class ____: """Links to content may have embedded hash values. This class parses those. `name` must be any member of `_SUPPORTED_HASHES`. This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to be JSON-serializable to conform to PEP 610, this class contains the logic for parsing a hash name and value for correctness, and then checking whether that hash conforms to a schema with `.is_hash_allowed()`.""" name: str value: str _hash_url_fragment_re = re.compile( # NB: we do not validate that the second group (.*) is a valid hex # digest. Instead, we simply keep that string in this class, and then check it # against Hashes when hash-checking is needed. This is easier to debug than # proactively discarding an invalid hex digest, as we handle incorrect hashes # and malformed hashes in the same place. r"[#&]({choices})=([^&]*)".format( choices="|".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES) ), ) def __post_init__(self) -> None: assert self.name in _SUPPORTED_HASHES @classmethod @functools.lru_cache(maxsize=None) def find_hash_url_fragment(cls, url: str) -> Optional["LinkHash"]: """Search a string for a checksum algorithm name and encoded output value.""" match = cls._hash_url_fragment_re.search(url) if match is None: return None name, value = match.groups() return cls(name=name, value=value) def as_dict(self) -> Dict[str, str]: return {self.name: self.value} def as_hashes(self) -> Hashes: """Return a Hashes instance which checks only for the current hash.""" return Hashes({self.name: [self.value]}) def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool: """ Return True if the current hash is allowed by `hashes`. """ if hashes is None: return False return hashes.is_hash_allowed(self.name, hex_digest=self.value) @dataclass(frozen=True)
LinkHash
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/attributes_foo_app/package.py
{ "start": 222, "end": 324 }
class ____(BundlePackage): version("1.0") depends_on("bar") depends_on("baz")
AttributesFooApp
python
getsentry__sentry
src/sentry/snuba/metrics/fields/base.py
{ "start": 12718, "end": 16193 }
class ____(MetricOperation): def validate_can_orderby(self) -> None: return def validate_can_groupby(self) -> bool: return False def validate_can_filter(self) -> bool: return False def get_meta_type(self) -> str | None: # If we have a percentile operation then we want to convert its type from Array(float64) to Float64 # because once we receive a percentile result from ClickHouse we automatically pop from the array the # first element thus the datatype itself must also be changed in the metadata. if self.op in OPERATIONS_PERCENTILES: return "Float64" return None def run_post_query_function( self, data: SnubaDataType, metric_mri: str, alias: str, idx: int | None = None, params: MetricOperationParams | None = None, ) -> SnubaDataType: return data def _wrap_quantiles(self, function: Function, alias: str) -> Function: # In case we have a percentile we want to take the first element of the array. This is done because we are # using quantilesIf instead of quantileIf, therefore we have an array as a result. if self.op in OPERATIONS_PERCENTILES: function = Function( "arrayElement", [ # We remove the alias from the function in order to avoid multiple aliases with the same name. replace(function, alias=None), # First element is 1 because ClickHouse arrays are indexed starting from 1. 1, ], alias=alias, ) return function def _gauge_avg(self, aggregate_filter: Function, alias: str) -> Function: return Function( "divide", [ Function("sumIf", [Column("value"), aggregate_filter]), Function("countIf", [Column("value"), aggregate_filter]), ], alias=alias, ) def generate_snql_function( self, entity: MetricEntity, use_case_id: UseCaseID, alias: str, aggregate_filter: Function, org_id: int, params: MetricOperationParams | None = None, ) -> Function: if use_case_id in [ UseCaseID.TRANSACTIONS, UseCaseID.SPANS, UseCaseID.ESCALATING_ISSUES, ]: snuba_function = GENERIC_OP_TO_SNUBA_FUNCTION[entity][self.op] else: snuba_function = OP_TO_SNUBA_FUNCTION[entity][self.op] # The average of a gauge is a special case of operation that is derived of two sub-operations # , and it could have been implemented with `DerivedOp` but in order to disambiguate between `avg` of # a gauge or `avg` of a distribution, significant code changes would have to be done, since metric # factory is used all over the code and lacks the entity parameter that would make the dataset inference # simpler. if entity == "generic_metrics_gauges" and self.op == "avg": function = self._gauge_avg(aggregate_filter, alias) else: function = Function(snuba_function, [Column("value"), aggregate_filter], alias=alias) return self._wrap_quantiles(function, alias) def get_default_null_values(self) -> int | list[tuple[float]] | None: return copy.copy(DEFAULT_AGGREGATES[self.op])
RawOp
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 987119, "end": 987615 }
class ____(sgqlc.types.Type): """Required status check""" __schema__ = github_schema __field_names__ = ("context", "integration_id") context = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="context") """The status check context name that must be present on the commit.""" integration_id = sgqlc.types.Field(Int, graphql_name="integrationId") """The optional integration ID that this status check must originate from. """
StatusCheckConfiguration
python
huggingface__transformers
src/transformers/models/sam_hq/configuration_sam_hq.py
{ "start": 8600, "end": 11780 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`SamHQMaskDecoder`]. It is used to instantiate a SAM_HQ mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the SAM_HQ-vit-h [facebook/sam_hq-vit-huge](https://huggingface.co/facebook/sam_hq-vit-huge) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the hidden states. hidden_act (`str`, *optional*, defaults to `"relu"`): The non-linear activation function used inside the `SamHQMaskDecoder` module. mlp_dim (`int`, *optional*, defaults to 2048): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hidden_layers (`int`, *optional*, defaults to 2): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 8): Number of attention heads for each attention layer in the Transformer encoder. attention_downsample_rate (`int`, *optional*, defaults to 2): The downsampling rate of the attention layer. num_multimask_outputs (`int`, *optional*, defaults to 3): The number of outputs from the `SamHQMaskDecoder` module. In the Segment Anything paper, this is set to 3. iou_head_depth (`int`, *optional*, defaults to 3): The number of layers in the IoU head module. iou_head_hidden_dim (`int`, *optional*, defaults to 256): The dimensionality of the hidden states in the IoU head module. layer_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the layer normalization layers. vit_dim (`int`, *optional*, defaults to 768): Dimensionality of the Vision Transformer (ViT) used in the `SamHQMaskDecoder` module. """ base_config_key = "mask_decoder_config" def __init__( self, hidden_size=256, hidden_act="relu", mlp_dim=2048, num_hidden_layers=2, num_attention_heads=8, attention_downsample_rate=2, num_multimask_outputs=3, iou_head_depth=3, iou_head_hidden_dim=256, layer_norm_eps=1e-6, vit_dim=768, **kwargs, ): super().__init__(**kwargs) self.hidden_size = hidden_size self.hidden_act = hidden_act self.mlp_dim = mlp_dim self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.attention_downsample_rate = attention_downsample_rate self.num_multimask_outputs = num_multimask_outputs self.iou_head_depth = iou_head_depth self.iou_head_hidden_dim = iou_head_hidden_dim self.layer_norm_eps = layer_norm_eps self.vit_dim = vit_dim
SamHQMaskDecoderConfig
python
kamyu104__LeetCode-Solutions
Python/latest-time-by-replacing-hidden-digits.py
{ "start": 29, "end": 591 }
class ____(object): def maximumTime(self, time): """ :type time: str :rtype: str """ result = list(time) for i, c in enumerate(time): if c != "?": continue if i == 0: result[i] = '2' if result[i+1] in "?0123" else '1' elif i == 1: result[i] = '3' if result[0] == '2' else '9' elif i == 3: result[i] = '5' elif i == 4: result[i] = '9' return "".join(result)
Solution
python
getsentry__sentry
src/sentry/incidents/endpoints/serializers/query_subscription.py
{ "start": 349, "end": 1350 }
class ____(Serializer): def get_attrs( self, item_list: Sequence[SnubaQuery], user, **kwargs ) -> MutableMapping[SnubaQuery, dict[str, Any]]: prefetch_related_objects(item_list, "environment", "snubaqueryeventtype_set") return {} def serialize( self, obj: SnubaQuery, attrs: Mapping[str, Any], user, **kwargs ) -> dict[str, Any]: return { "id": str(obj.id), "dataset": obj.dataset, "query": obj.query, "aggregate": obj.aggregate, "timeWindow": obj.time_window, "environment": obj.environment.name if obj.environment else None, "eventTypes": [event_type.name.lower() for event_type in obj.event_types], "extrapolationMode": ( ExtrapolationMode(obj.extrapolation_mode).name.lower() if obj.extrapolation_mode is not None else None ), } @register(QuerySubscription)
SnubaQuerySerializer
python
pytorch__pytorch
test/nn/test_dropout.py
{ "start": 3491, "end": 13656 }
class ____(NNTestCase): def _test_dropout(self, cls, device, input, memory_format=torch.contiguous_format): p = 0.2 input = input.to(device).fill_(1 - p) module = cls(p) input_var = input.clone(memory_format=memory_format).requires_grad_() output = module(input_var) self.assertTrue(output.is_contiguous(memory_format=memory_format)) self.assertLess(abs(output.data.mean() - (1 - p)), 0.05) output.backward(input) self.assertTrue(input_var.grad.is_contiguous(memory_format=memory_format)) self.assertLess(abs(input_var.grad.data.mean() - (1 - p)), 0.05) module = cls(p, True) input_var = input.clone(memory_format=memory_format).requires_grad_() output = module(input_var + 0) self.assertTrue(output.is_contiguous(memory_format=memory_format)) self.assertLess(abs(output.data.mean() - (1 - p)), 0.05) output.backward(input) self.assertTrue(input_var.grad.is_contiguous(memory_format=memory_format)) self.assertLess(abs(input_var.grad.data.mean() - (1 - p)), 0.05) # check eval mode doesn't change anything for inplace in [True, False]: module = cls(p, inplace).eval() self.assertEqual(input, module(input)) # Check that these don't raise errors module.__repr__() str(module) def _test_dropout_discontiguous( self, cls, device, memory_format=torch.contiguous_format ): # In this test, we verify that dropout preserves the layout and data for different memory formats. # We check whether, we get same values for the output of dropout, when the probability # of dropout is 0 or very close to 0. # Reference: https://github.com/pytorch/pytorch/issues/47176 close_to_zero_p = 1e-10 # Should be almost zero but not zero, as for p=0 different path is taken for p in [0, close_to_zero_p]: inp = torch.ones(2, 3, 3, 3, device=device) inp_discontiguous = torch.empty( 2, 3, 3, 6, device=device, memory_format=memory_format )[..., ::2] inp_discontiguous.copy_(inp) mod = cls(p=p) out = mod(inp_discontiguous) if p != 0: # Zero will keep strides as is based on input. # When prob == 0, input stride (54, 18, 6, 2) -> output stride (54, 18, 6, 2) # When prob != 0, input stride (54, 18, 6, 2) -> output stride (27, 9, 3, 1) self.assertTrue(out.is_contiguous(memory_format=memory_format)) self.assertEqual(inp_discontiguous, out) def _test_dropout_stride_mean_preserve(self, cls, device): def invert_perm(p): d = {x: i for i, x in enumerate(p)} return (d[0], d[1], d[2], d[3]) inp = torch.ones(2, 3, 4, 5, device=device) shifts = [(0, 0), (1, 0), (0, 1), (1, 1)] for perm in itertools.permutations((0, 1, 2, 3), r=4): for shift in shifts: for p in [1e-10, 0.3, 0.5, 0.7]: mod = cls(p=p) permuted_inp = ( inp.permute(perm).contiguous().permute(invert_perm(perm)) ) permuted_inp = permuted_inp[shift[0] :, shift[1] :, :, :] out = mod(permuted_inp) self.assertTrue(out.permute(perm).is_contiguous()) self.assertEqual(inp.mean(), out.mean(), rtol=0.5, atol=0.5) if p == 1e-10: self.assertEqual(permuted_inp, out) else: self.assertNotEqual(permuted_inp, out) def test_Dropout(self, device): input = torch.empty(1000) self._test_dropout(nn.Dropout, device, input) self._test_dropout_discontiguous(nn.Dropout, device) self._test_dropout_discontiguous( nn.Dropout, device, memory_format=torch.channels_last ) self._test_dropout_stride_mean_preserve(nn.Dropout, device) if self.device_type == "cuda" or self.device_type == "cpu": input = input.bfloat16() self._test_dropout(nn.Dropout, device, input) def _test_dropoutNd_no_batch(self, dropout, input): input_clone = input.clone() with freeze_rng_state(): res_no_batch = dropout(input) with freeze_rng_state(): res_batched = dropout(input_clone.unsqueeze(0)).squeeze(0) self.assertEqual(res_no_batch, res_batched) def _test_dropoutNd_channel_zero(self, dropout, input): # Verify the number of zeros in a channel is 0 or the number of elements in the channel # for a fully positive input tensor shape = input.shape B = shape[0] C = shape[1] channel_numel = torch.tensor(shape[2:]).prod() result = dropout(input) for b, c in product(range(B), range(C)): self.assertTrue(result[b, c].count_nonzero() in (0, channel_numel)) @expectedFailureXLA # seems like freeze_rng_state is not honoured by XLA @dtypes(torch.double) @dtypesIfMPS(torch.float32) @expectedFailureMPS def test_Dropout1d(self, device, dtype): with set_default_dtype(dtype): N, C, L = ( random.randint(10, 15), random.randint(10, 15), random.randint(10, 15), ) input = torch.empty(N, C, L) self._test_dropout(nn.Dropout1d, device, input) with self.assertRaisesRegex( RuntimeError, "Expected 2D or 3D input, but received a 4D input" ): nn.Dropout1d(p=0.5)(torch.rand(1, 2, 2, 2, device=device)) with self.assertRaisesRegex( RuntimeError, "Expected 2D or 3D input, but received a 1D input" ): nn.Dropout1d(p=0.5)(torch.rand(2, device=device)) # no batch dims input = torch.rand(50, 2, device=device) self._test_dropoutNd_no_batch(nn.Dropout1d(p=0.5), input) self._test_dropoutNd_no_batch(nn.Dropout1d(p=0.5, inplace=True), input) # check that complete channels are dropped input = torch.ones(10, 4, 2, device=device) self._test_dropoutNd_channel_zero(nn.Dropout1d(p=0.5), input) self._test_dropoutNd_channel_zero(nn.Dropout1d(p=0.5, inplace=True), input) @expectedFailureXLA # seems like freeze_rng_state is not honoured by XLA def test_Dropout2d(self, device): b = random.randint(1, 5) w = random.randint(1, 5) h = random.randint(1, 5) num_features = 1000 input = torch.empty(num_features, b, w, h) self._test_dropout(nn.Dropout2d, device, input) self._test_dropout( nn.Dropout2d, device, input, memory_format=torch.channels_last ) self._test_dropout_discontiguous(nn.Dropout2d, device) self._test_dropout_discontiguous( nn.Dropout2d, device, memory_format=torch.channels_last ) with self.assertWarnsRegex(UserWarning, "Received a 5-D input to dropout2d"): nn.Dropout2d(p=0.5)(torch.rand(1, 2, 2, 2, 2, device=device)) with self.assertWarnsRegex(UserWarning, "Received a 2-D input to dropout2d"): nn.Dropout2d(p=0.5)(torch.rand(1, 2, device=device)) # TODO: Uncomment these lines once no-batch-dim inputs are supported. # For now, the historical dropout1d behavior is performed for 3D inputs. # See https://github.com/pytorch/pytorch/issues/77081 # input = torch.rand(50, 2, 2, device=device) # self._test_dropoutNd_no_batch(nn.Dropout2d(p=0.5), input) # self._test_dropoutNd_no_batch(nn.Dropout2d(p=0.5, inplace=True), input) with self.assertWarnsRegex( UserWarning, "assuming that channel-wise 1D dropout behavior is desired" ): nn.Dropout2d(p=0.5)(torch.rand(1, 2, 2, device=device)) # check that complete channels are dropped input = torch.ones(10, 4, 2, 2, device=device) self._test_dropoutNd_channel_zero(nn.Dropout2d(p=0.5), input) self._test_dropoutNd_channel_zero(nn.Dropout2d(p=0.5, inplace=True), input) @expectedFailureXLA # seems like freeze_rng_state is not honoured by XLA @expectedFailureMPS # Failing on current pytorch MPS def test_Dropout3d(self, device): b = random.randint(1, 5) w = random.randint(1, 5) h = random.randint(1, 5) d = random.randint(1, 2) num_features = 1000 input = torch.empty(num_features, b, d, w, h) self._test_dropout(nn.Dropout3d, device, input) self._test_dropout_discontiguous(nn.Dropout3d, device) self._test_dropout_discontiguous( nn.Dropout3d, device, memory_format=torch.channels_last ) with self.assertWarnsRegex(UserWarning, "Received a 6-D input to dropout3d"): nn.Dropout3d(p=0.5)(torch.rand(1, 2, 2, 2, 2, 2, device=device)) with self.assertWarnsRegex(UserWarning, "Received a 3-D input to dropout3d"): nn.Dropout3d(p=0.5)(torch.rand(1, 2, 2, device=device)) # no batch dims input = torch.rand(50, 2, 2, 2, device=device) self._test_dropoutNd_no_batch(nn.Dropout3d(p=0.5), input) self._test_dropoutNd_no_batch(nn.Dropout3d(p=0.5, inplace=True), input) # check that complete channels are dropped input = torch.ones(10, 4, 2, 2, 2, device=device) self._test_dropoutNd_channel_zero(nn.Dropout3d(p=0.5), input) self._test_dropoutNd_channel_zero(nn.Dropout3d(p=0.5, inplace=True), input) def test_empty_dropout(self, device): x = torch.tensor([]).to(device) out = torch.nn.functional.dropout(x) self.assertEqual(out.size(), x.size()) instantiate_device_type_tests(TestDropoutNNDeviceType, globals(), allow_mps=True) instantiate_parametrized_tests(TestDropoutNN) if __name__ == "__main__": run_tests()
TestDropoutNNDeviceType
python
ethereum__web3.py
web3/types.py
{ "start": 5887, "end": 5984 }
class ____(SubscriptionResponse): result: HexBytes | TxData
TransactionTypeSubscriptionResponse
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 65526, "end": 66743 }
class ____(TestCase): """Tests for ``stagger()``""" def test_default(self): iterable = [0, 1, 2, 3] actual = list(mi.stagger(iterable)) expected = [(None, 0, 1), (0, 1, 2), (1, 2, 3)] self.assertEqual(actual, expected) def test_offsets(self): iterable = [0, 1, 2, 3] for offsets, expected in [ ((-2, 0, 2), [('', 0, 2), ('', 1, 3)]), ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3)]), ((1, 2), [(1, 2), (2, 3)]), ]: all_groups = mi.stagger(iterable, offsets=offsets, fillvalue='') self.assertEqual(list(all_groups), expected) def test_longest(self): iterable = [0, 1, 2, 3] for offsets, expected in [ ( (-1, 0, 1), [('', 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, ''), (3, '', '')], ), ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3), (3, '')]), ((1, 2), [(1, 2), (2, 3), (3, '')]), ]: all_groups = mi.stagger( iterable, offsets=offsets, fillvalue='', longest=True ) self.assertEqual(list(all_groups), expected)
StaggerTest
python
catalyst-team__catalyst
examples/engines/train_resnet.py
{ "start": 1406, "end": 4792 }
class ____(dl.IRunner): def __init__(self, logdir: str, engine: str, **engine_params: Any): super().__init__() self._logdir = logdir self._engine = engine self._engine_params = engine_params def get_engine(self): return E2E[self._engine](**self._engine_params) def get_loggers(self): return { "console": dl.ConsoleLogger(), "csv": dl.CSVLogger(logdir=self._logdir), "tensorboard": dl.TensorboardLogger(logdir=self._logdir), } @property def num_epochs(self) -> int: return 10 def get_loaders(self): transform = Compose( [ImageToTensor(), NormalizeImage((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] ) train_data = CIFAR10(os.getcwd(), train=True, download=True, transform=transform) valid_data = CIFAR10( os.getcwd(), train=False, download=True, transform=transform ) if self.engine.is_ddp: train_sampler = DistributedSampler( train_data, num_replicas=self.engine.num_processes, rank=self.engine.process_index, shuffle=True, ) valid_sampler = DistributedSampler( valid_data, num_replicas=self.engine.num_processes, rank=self.engine.process_index, shuffle=False, ) else: train_sampler = valid_sampler = None return { "train": DataLoader( train_data, batch_size=32, sampler=train_sampler, num_workers=4 ), "valid": DataLoader( valid_data, batch_size=32, sampler=valid_sampler, num_workers=4 ), } def get_model(self): model = ( self.model if self.model is not None else resnet9(in_channels=3, num_classes=10) ) return model def get_criterion(self): return nn.CrossEntropyLoss() def get_optimizer(self, model): return optim.Adam(model.parameters(), lr=1e-3) def get_scheduler(self, optimizer): return optim.lr_scheduler.MultiStepLR(optimizer, [5, 8], gamma=0.3) def get_callbacks(self): return { "criterion": dl.CriterionCallback( metric_key="loss", input_key="logits", target_key="targets" ), "backward": dl.BackwardCallback(metric_key="loss"), "optimizer": dl.OptimizerCallback(metric_key="loss"), "scheduler": dl.SchedulerCallback(loader_key="valid", metric_key="loss"), "accuracy": dl.AccuracyCallback( input_key="logits", target_key="targets", topk=(1, 3, 5) ), "checkpoint": dl.CheckpointCallback( self._logdir, loader_key="valid", metric_key="accuracy01", minimize=False, topk=1, ), "tqdm": dl.TqdmCallback(), } def handle_batch(self, batch): x, y = batch logits = self.model(x) self.batch = { "features": x, "targets": y, "logits": logits, } if __name__ == "__main__": kwargs, _ = parse_params("resnet") runner = CustomRunner(**kwargs) runner.run()
CustomRunner
python
allegroai__clearml
clearml/backend_api/services/v2_9/models.py
{ "start": 27028, "end": 28077 }
class ____(Response): """ Response of models.delete endpoint. :param deleted: Indicates whether the model was deleted :type deleted: bool """ _service = "models" _action = "delete" _version = "2.9" _schema = { "definitions": {}, "properties": { "deleted": { "description": "Indicates whether the model was deleted", "type": ["boolean", "null"], } }, "type": "object", } def __init__(self, deleted: Optional[bool] = None, **kwargs: Any) -> None: super(DeleteResponse, self).__init__(**kwargs) self.deleted = deleted @schema_property("deleted") def deleted(self) -> Optional[bool]: return self._property_deleted @deleted.setter def deleted(self, value: Optional[bool]) -> None: if value is None: self._property_deleted = None return self.assert_isinstance(value, "deleted", (bool,)) self._property_deleted = value
DeleteResponse
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/formatters/latex.py
{ "start": 4972, "end": 16227 }
class ____(Formatter): r""" Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages. Without the `full` option, code is formatted as one ``Verbatim`` environment, like this: .. sourcecode:: latex \begin{Verbatim}[commandchars=\\\{\}] \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}): \PY{k}{pass} \end{Verbatim} Wrapping can be disabled using the `nowrap` option. The special command used here (``\PY``) and all the other macros it needs are output by the `get_style_defs` method. With the `full` option, a complete LaTeX document is output, including the command definitions in the preamble. The `get_style_defs()` method of a `LatexFormatter` returns a string containing ``\def`` commands defining the macros needed inside the ``Verbatim`` environments. Additional options accepted: `nowrap` If set to ``True``, don't wrap the tokens at all, not even inside a ``\begin{Verbatim}`` environment. This disables most other options (default: ``False``). `style` The style to use, can be a string or a Style subclass (default: ``'default'``). `full` Tells the formatter to output a "full" document, i.e. a complete self-contained document (default: ``False``). `title` If `full` is true, the title that should be used to caption the document (default: ``''``). `docclass` If the `full` option is enabled, this is the document class to use (default: ``'article'``). `preamble` If the `full` option is enabled, this can be further preamble commands, e.g. ``\usepackage`` (default: ``''``). `linenos` If set to ``True``, output line numbers (default: ``False``). `linenostart` The line number for the first line (default: ``1``). `linenostep` If set to a number n > 1, only every nth line number is printed. `verboptions` Additional options given to the Verbatim environment (see the *fancyvrb* docs for possible values) (default: ``''``). `commandprefix` The LaTeX commands used to produce colored output are constructed using this prefix and some letters (default: ``'PY'``). .. versionadded:: 0.7 .. versionchanged:: 0.10 The default is now ``'PY'`` instead of ``'C'``. `texcomments` If set to ``True``, enables LaTeX comment lines. That is, LaTex markup in comment tokens is not escaped so that LaTeX can render it (default: ``False``). .. versionadded:: 1.2 `mathescape` If set to ``True``, enables LaTeX math mode escape in comments. That is, ``'$...$'`` inside a comment will trigger math mode (default: ``False``). .. versionadded:: 1.2 `escapeinside` If set to a string of length 2, enables escaping to LaTeX. Text delimited by these 2 characters is read as LaTeX code and typeset accordingly. It has no effect in string literals. It has no effect in comments if `texcomments` or `mathescape` is set. (default: ``''``). .. versionadded:: 2.0 `envname` Allows you to pick an alternative environment name replacing Verbatim. The alternate environment still has to support Verbatim's option syntax. (default: ``'Verbatim'``). .. versionadded:: 2.0 """ name = 'LaTeX' aliases = ['latex', 'tex'] filenames = ['*.tex'] def __init__(self, **options): Formatter.__init__(self, **options) self.nowrap = get_bool_opt(options, 'nowrap', False) self.docclass = options.get('docclass', 'article') self.preamble = options.get('preamble', '') self.linenos = get_bool_opt(options, 'linenos', False) self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) self.verboptions = options.get('verboptions', '') self.nobackground = get_bool_opt(options, 'nobackground', False) self.commandprefix = options.get('commandprefix', 'PY') self.texcomments = get_bool_opt(options, 'texcomments', False) self.mathescape = get_bool_opt(options, 'mathescape', False) self.escapeinside = options.get('escapeinside', '') if len(self.escapeinside) == 2: self.left = self.escapeinside[0] self.right = self.escapeinside[1] else: self.escapeinside = '' self.envname = options.get('envname', 'Verbatim') self._create_stylesheet() def _create_stylesheet(self): t2n = self.ttype2name = {Token: ''} c2d = self.cmd2def = {} cp = self.commandprefix def rgbcolor(col): if col: return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0) for i in (0, 2, 4)]) else: return '1,1,1' for ttype, ndef in self.style: name = _get_ttype_name(ttype) cmndef = '' if ndef['bold']: cmndef += r'\let\$$@bf=\textbf' if ndef['italic']: cmndef += r'\let\$$@it=\textit' if ndef['underline']: cmndef += r'\let\$$@ul=\underline' if ndef['roman']: cmndef += r'\let\$$@ff=\textrm' if ndef['sans']: cmndef += r'\let\$$@ff=\textsf' if ndef['mono']: cmndef += r'\let\$$@ff=\textsf' if ndef['color']: cmndef += (r'\def\$$@tc##1{{\textcolor[rgb]{{{}}}{{##1}}}}'.format(rgbcolor(ndef['color']))) if ndef['border']: cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}' r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']), rgbcolor(ndef['bgcolor']))) elif ndef['bgcolor']: cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{0pt}}' r'\colorbox[rgb]{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['bgcolor']))) if cmndef == '': continue cmndef = cmndef.replace('$$', cp) t2n[ttype] = name c2d[name] = cmndef def get_style_defs(self, arg=''): """ Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored. """ cp = self.commandprefix styles = [] for name, definition in self.cmd2def.items(): styles.append(rf'\@namedef{{{cp}@tok@{name}}}{{{definition}}}') return STYLE_TEMPLATE % {'cp': self.commandprefix, 'styles': '\n'.join(styles)} def format_unencoded(self, tokensource, outfile): # TODO: add support for background colors t2n = self.ttype2name cp = self.commandprefix if self.full: realoutfile = outfile outfile = StringIO() if not self.nowrap: outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}') if self.linenos: start, step = self.linenostart, self.linenostep outfile.write(',numbers=left' + (start and ',firstnumber=%d' % start or '') + (step and ',stepnumber=%d' % step or '')) if self.mathescape or self.texcomments or self.escapeinside: outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7' '\\catcode`\\_=8\\relax}') if self.verboptions: outfile.write(',' + self.verboptions) outfile.write(']\n') for ttype, value in tokensource: if ttype in Token.Comment: if self.texcomments: # Try to guess comment starting lexeme and escape it ... start = value[0:1] for i in range(1, len(value)): if start[0] != value[i]: break start += value[i] value = value[len(start):] start = escape_tex(start, cp) # ... but do not escape inside comment. value = start + value elif self.mathescape: # Only escape parts not inside a math environment. parts = value.split('$') in_math = False for i, part in enumerate(parts): if not in_math: parts[i] = escape_tex(part, cp) in_math = not in_math value = '$'.join(parts) elif self.escapeinside: text = value value = '' while text: a, sep1, text = text.partition(self.left) if sep1: b, sep2, text = text.partition(self.right) if sep2: value += escape_tex(a, cp) + b else: value += escape_tex(a + sep1 + b, cp) else: value += escape_tex(a, cp) else: value = escape_tex(value, cp) elif ttype not in Token.Escape: value = escape_tex(value, cp) styles = [] while ttype is not Token: try: styles.append(t2n[ttype]) except KeyError: # not in current style styles.append(_get_ttype_name(ttype)) ttype = ttype.parent styleval = '+'.join(reversed(styles)) if styleval: spl = value.split('\n') for line in spl[:-1]: if line: outfile.write(f"\\{cp}{{{styleval}}}{{{line}}}") outfile.write('\n') if spl[-1]: outfile.write(f"\\{cp}{{{styleval}}}{{{spl[-1]}}}") else: outfile.write(value) if not self.nowrap: outfile.write('\\end{' + self.envname + '}\n') if self.full: encoding = self.encoding or 'utf8' # map known existings encodings from LaTeX distribution encoding = { 'utf_8': 'utf8', 'latin_1': 'latin1', 'iso_8859_1': 'latin1', }.get(encoding.replace('-', '_'), encoding) realoutfile.write(DOC_TEMPLATE % dict(docclass = self.docclass, preamble = self.preamble, title = self.title, encoding = encoding, styledefs = self.get_style_defs(), code = outfile.getvalue()))
LatexFormatter
python
django-guardian__django-guardian
guardian/testapp/models.py
{ "start": 927, "end": 1073 }
class ____(GroupObjectPermissionAbstract): class Meta(GroupObjectPermissionAbstract.Meta): abstract = False
GenericGroupObjectPermission
python
simonw__datasette
datasette/filters.py
{ "start": 7201, "end": 8443 }
class ____(Filter): def __init__( self, key, display, sql_template, human_template, format="{}", numeric=False, no_argument=False, ): self.key = key self.display = display self.sql_template = sql_template self.human_template = human_template self.format = format self.numeric = numeric self.no_argument = no_argument def where_clause(self, table, column, value, param_counter): converted = self.format.format(value) if self.numeric and converted.isdigit(): converted = int(converted) if self.no_argument: kwargs = {"c": column} converted = None else: kwargs = {"c": column, "p": f"p{param_counter}", "t": table} return self.sql_template.format(**kwargs), converted def human_clause(self, column, value): if callable(self.human_template): template = self.human_template(column, value) else: template = self.human_template if self.no_argument: return template.format(c=column) else: return template.format(c=column, v=value)
TemplatedFilter
python
patrick-kidger__equinox
equinox/nn/_stateful.py
{ "start": 3326, "end": 13746 }
class ____: """Stores the state of a model. For example, the running statistics of all [`equinox.nn.BatchNorm`][] layers in the model. This is essentially a dictionary mapping from [`equinox.nn.StateIndex`][]s to PyTrees of arrays. This class should be initialised via [`equinox.nn.make_with_state`][]. """ def __init__(self, model: PyTree): """**Arguments:** - `model`: any PyTree. All stateful layers (e.g. [`equinox.nn.BatchNorm`][]) will have their initial state stored inside the `State` object. """ # Note that de/serialisation depends on the ordered-ness of this dictionary, # between serialisation and deserialisation. state = {} leaves = jtu.tree_leaves(model, is_leaf=_is_index) for leaf in leaves: if _is_index(leaf): if isinstance(leaf.init, _Sentinel): raise ValueError( "Do not call `eqx.nn.State(model)` directly. You should call " "`eqx.nn.make_with_state(ModelClass)(...args...)` instead." ) state[leaf.marker] = jtu.tree_map(jnp.asarray, leaf.init) self._state: _Sentinel | dict[object | int, Any] = state def get(self, item: StateIndex[_Value]) -> _Value: """Given an [`equinox.nn.StateIndex`][], returns the value of its state. **Arguments:** - `item`: an [`equinox.nn.StateIndex`][]. **Returns:** The current state associated with that index. """ if isinstance(self._state, _Sentinel): raise ValueError(_state_error) if type(item) is not StateIndex: raise ValueError("Can only use `eqx.nn.StateIndex`s as state keys.") return self._state[item.marker] def set(self, item: StateIndex[_Value], value: _Value) -> "State": """Sets a new value for an [`equinox.nn.StateIndex`][], **and returns the updated state**. **Arguments:** - `item`: an [`equinox.nn.StateIndex`][]. - `value`: the new value associated with that index. **Returns:** A new [`equinox.nn.State`][] object, with the update. As a safety guard against accidentally writing `state.set(item, value)` without assigning it to a new value, then the old object (`self`) will become invalid. """ if isinstance(self._state, _Sentinel): raise ValueError(_state_error) if type(item) is not StateIndex: raise ValueError("Can only use `eqx.nn.StateIndex`s as state keys.") old_value = self._state[item.marker] value = jtu.tree_map(jnp.asarray, value) old_struct = jax.eval_shape(lambda: old_value) new_struct = jax.eval_shape(lambda: value) if tree_equal(old_struct, new_struct) is not True: old_repr = tree_pformat(old_struct, struct_as_array=True) new_repr = tree_pformat(new_struct, struct_as_array=True) raise ValueError( "Old and new values have different structures/shapes/dtypes. The old " f"value is {old_repr} and the new value is {new_repr}." ) state = self._state.copy() # pyright: ignore state[item.marker] = value new_self = object.__new__(State) new_self._state = state self._state = _sentinel return new_self def substate(self, pytree: PyTree) -> "State": """Creates a smaller `State` object, that tracks only the states of some smaller part of the overall model. **Arguments:** - `pytree`: any PyTree. It will be iterated over to check for [`equinox.nn.StateIndex`]s. **Returns:** A new [`equinox.nn.State`][] object, which tracks only some of the overall states. """ if isinstance(self._state, _Sentinel): raise ValueError(_state_error) leaves = jtu.tree_leaves(pytree, is_leaf=_is_index) markers = [x.marker for x in leaves if _is_index(x)] substate = {k: self._state[k] for k in markers} # pyright: ignore subself = object.__new__(State) subself._state = substate return subself def update(self, substate: "State") -> "State": """Takes a smaller `State` object (typically produces via `.substate`), and updates states by using all of its values. **Arguments:** - `substate`: a `State` object whose keys are a subset of the keys of `self`. **Returns:** A new [`equinox.nn.State`][] object, containing all of the updated values. As a safety guard against accidentally writing `state.set(item, value)` without assigning it to a new value, then the old object (`self`) will become invalid. """ if isinstance(self._state, _Sentinel): raise ValueError(_state_error) if type(substate) is not State: raise ValueError("Can only use `eqx.nn.State`s in `update`.") state = self._state.copy() # pyright: ignore for key, value in substate._state.items(): # pyright: ignore if key not in state: raise ValueError( "Cannot call `state1.update(state2)` unless `state2` is a substate " "of `state1`." ) state[key] = value new_self = object.__new__(State) new_self._state = state self._state = _sentinel return new_self def __repr__(self): return tree_pformat(self) def __pdoc__(self, **kwargs): if isinstance(self._state, _Sentinel): return wl.TextDoc("State(~old~)") else: docs = wl.named_objs(self._state.items(), **kwargs) # pyright: ignore return wl.bracketed( begin=wl.TextDoc("State("), docs=docs, sep=wl.comma, end=wl.TextDoc(")"), indent=kwargs["indent"], ) def tree_flatten(self): if isinstance(self._state, _Sentinel): raise ValueError(_state_error) keys = tuple(self._state.keys()) # pyright: ignore values = tuple(self._state[k] for k in keys) # pyright: ignore return values, keys @classmethod def tree_unflatten(cls, keys, values): self = object.__new__(cls) state = {} assert len(keys) == len(values) for key, value in zip(keys, values): state[key] = value self._state = state return self def _delete_init_state(x): if _is_index(x): return tree_at(lambda y: y.init, x, _sentinel) else: return x def delete_init_state(model: PyTree) -> PyTree: """For memory efficiency, this deletes the initial state stored within a model. Every stateful layer keeps a copy of the initial value of its state. This is then collected by [`equinox.nn.State`][], when it is called on the model. However, this means that the model must keep a copy of the initial state around, in case `eqx.nn.State` is called on it again. This extra copy consumes extra memory. But in practice, it is quite common to only need to initialise the state once. In this case, we can use this function to delete this extra copy, and in doing so save some memory. !!! Example Here is the typical pattern in which this is used: ```python model_and_state = eqx.nn.BatchNorm(...) state = eqx.nn.State(model_and_state) model = eqx.nn.delete_init_state(model) del model_and_state # ensure this goes out of scope and is garbage collected ``` Indeed the above is precisely what [`equinox.nn.make_with_state`][] does. **Arguments:** - `model`: any PyTree. **Returns:** A copy of `model`, with all the initial states stripped out. (As in the examples above, you should then dispose of the original `model` object.) """ return jtu.tree_map(_delete_init_state, model, is_leaf=_is_index) def make_with_state(make_model: Callable[_P, _T]) -> Callable[_P, tuple[_T, State]]: """This function is the most common API for working with stateful models. This initialises both the parameters and the state of a stateful model. `eqx.nn.make_with_state(Model)(*args, **kwargs)` simply calls `model_with_state = Model(*args, **kwargs)`, and then partitions the resulting PyTree into two pieces: the parameters, and the state. **Arguments:** - `make_model`: some callable returning a PyTree. **Returns:** A callable, which when evaluated returns a 2-tuple of `(model, state)`, where `model` is the result of `make_model(*args, **kwargs)` but with all of the initial states stripped out, and `state` is an [`equinox.nn.State`][] object encapsulating the initial states. !!! Example See [the stateful example](../../examples/stateful.ipynb) for a runnable example. ```python class Model(eqx.Module): def __init__(self, foo, bar): ... ... model, state = eqx.nn.make_with_state(Model)(foo=3, bar=4) ``` """ # _P.{args, kwargs} not supported by beartype if TYPE_CHECKING: def make_with_state_impl( *args: _P.args, **kwargs: _P.kwargs ) -> tuple[_T, State]: ... else: def make_with_state_impl(*args, **kwargs) -> tuple[_T, State]: model = make_model(*args, **kwargs) # Replace all markers with stringified key paths. This is needed to ensure # that two calls to `make_with_state` produce compatible models and states. key_leaves, treedef = jtu.tree_flatten_with_path(model, is_leaf=_is_index) new_leaves = [] for key, leaf in key_leaves: if _is_index(leaf): leaf = StateIndex(leaf.init) path_str = model.__class__.__name__ + jtu.keystr(key) object.__setattr__(leaf, "marker", path_str) new_leaves.append(leaf) model = jtu.tree_unflatten(treedef, new_leaves) state = State(model) model = delete_init_state(model) return model, state return make_with_state_impl
State
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 519916, "end": 520815 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "reviewers") field = sgqlc.types.Field( sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field" ) reviewers = sgqlc.types.Field( "RequestedReviewerConnection", graphql_name="reviewers", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), )
ProjectV2ItemFieldReviewerValue
python
spack__spack
var/spack/test_repos/spack_repo/duplicates_test/packages/pkg_config/package.py
{ "start": 216, "end": 517 }
class ____(Package): """A package providing a virtual, which is frequently used as a pure build dependency.""" homepage = "http://www.example.com" url = "http://www.example.com/tdep-1.0.tar.gz" version("1.0.0", md5="0123456789abcdef0123456789abcdef") provides("pkgconfig")
PkgConfig
python
Textualize__textual
src/textual/scroll_view.py
{ "start": 360, "end": 6447 }
class ____(ScrollableContainer): """ A base class for a Widget that handles its own scrolling (i.e. doesn't rely on the compositor to render children). !!! note This is the typically wrong class for making something scrollable. If you want to make something scroll, set its `overflow` style to auto or scroll. Or use one of the pre-defined scrolling containers such as [VerticalScroll][textual.containers.VerticalScroll]. """ ALLOW_MAXIMIZE = True DEFAULT_CSS = """ ScrollView { overflow-y: auto; overflow-x: auto; } """ @property def is_scrollable(self) -> bool: """Always scrollable.""" return True @property def is_container(self) -> bool: """Since a ScrollView should be a line-api widget, it won't have children, and therefore isn't a container.""" return False def watch_scroll_x(self, old_value: float, new_value: float) -> None: if self.show_horizontal_scrollbar: self.horizontal_scrollbar.position = new_value if round(old_value) != round(new_value): self.refresh(self.size.region) def watch_scroll_y(self, old_value: float, new_value: float) -> None: if self.show_vertical_scrollbar: self.vertical_scrollbar.position = new_value if round(old_value) != round(new_value): self.refresh(self.size.region) def on_mount(self): self._refresh_scrollbars() def get_content_width(self, container: Size, viewport: Size) -> int: """Gets the width of the content area. Args: container: Size of the container (immediate parent) widget. viewport: Size of the viewport. Returns: The optimal width of the content. """ return self.virtual_size.width def get_content_height(self, container: Size, viewport: Size, width: int) -> int: """Gets the height (number of lines) in the content area. Args: container: Size of the container (immediate parent) widget. viewport: Size of the viewport. width: Width of renderable. Returns: The height of the content. """ return self.virtual_size.height def _size_updated( self, size: Size, virtual_size: Size, container_size: Size, layout: bool = True ) -> bool: """Called when size is updated. Args: size: New size. virtual_size: New virtual size. container_size: New container size. layout: Perform layout if required. Returns: True if a resize event should be sent, otherwise False. """ if size_changed := self._size != size: self._set_dirty() if ( size_changed or virtual_size != self.virtual_size or container_size != self.container_size ): self._scrollbar_changes.clear() self._size = size virtual_size = self.virtual_size self._container_size = size - self.styles.gutter.totals self._scroll_update(virtual_size) return size_changed or self._container_size != container_size def render(self) -> RenderableType: """Render the scrollable region (if `render_lines` is not implemented). Returns: Renderable object. """ from rich.panel import Panel return Panel(f"{self.scroll_offset} {self.show_vertical_scrollbar}") # Custom scroll to which doesn't require call_after_refresh def scroll_to( self, x: float | None = None, y: float | None = None, *, animate: bool = True, speed: float | None = None, duration: float | None = None, easing: EasingFunction | str | None = None, force: bool = False, on_complete: CallbackType | None = None, level: AnimationLevel = "basic", immediate: bool = False, ) -> None: """Scroll to a given (absolute) coordinate, optionally animating. Args: x: X coordinate (column) to scroll to, or `None` for no change. y: Y coordinate (row) to scroll to, or `None` for no change. animate: Animate to new scroll position. speed: Speed of scroll if `animate` is `True`; or `None` to use `duration`. duration: Duration of animation, if `animate` is `True` and `speed` is `None`. easing: An easing method for the scrolling animation. force: Force scrolling even when prohibited by overflow styling. on_complete: A callable to invoke when the animation is finished. level: Minimum level required for the animation to take place (inclusive). immediate: If `False` the scroll will be deferred until after a screen refresh, set to `True` to scroll immediately. """ self._scroll_to( x, y, animate=animate, speed=speed, duration=duration, easing=easing, force=force, on_complete=on_complete, level=level, ) def refresh_line(self, y: int) -> None: """Refresh a single line. Args: y: Coordinate of line. """ self.refresh( Region( 0, y - self.scroll_offset.y, max(self.virtual_size.width, self.size.width), 1, ) ) def refresh_lines(self, y_start: int, line_count: int = 1) -> None: """Refresh one or more lines. Args: y_start: First line to refresh. line_count: Total number of lines to refresh. """ refresh_region = Region( 0, y_start - self.scroll_offset.y, max(self.virtual_size.width, self.size.width), line_count, ) self.refresh(refresh_region)
ScrollView
python
PyCQA__pylint
tests/functional/c/classes_meth_could_be_a_function.py
{ "start": 206, "end": 235 }
class ____(XAsub): pass
XBsub
python
doocs__leetcode
solution/0300-0399/0322.Coin Change/Solution.py
{ "start": 0, "end": 436 }
class ____: def coinChange(self, coins: List[int], amount: int) -> int: m, n = len(coins), amount f = [[inf] * (n + 1) for _ in range(m + 1)] f[0][0] = 0 for i, x in enumerate(coins, 1): for j in range(n + 1): f[i][j] = f[i - 1][j] if j >= x: f[i][j] = min(f[i][j], f[i][j - x] + 1) return -1 if f[m][n] >= inf else f[m][n]
Solution