_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q15100
FakedHbaManager.add
train
def add(self, properties): """ Add a faked HBA resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'hba', if not specified. * 'adapter-port-uri' identifies the backing FCP port for this HBA and is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'hba-uris' property in the parent faked Partition resource, by adding the URI for the faked HBA resource. Returns: :class:`~zhmcclient_mock.FakedHba`: The faked HBA resource. Raises: :exc:`zhmcclient_mock.InputError`: Some issue
python
{ "resource": "" }
q15101
FakedHbaManager.remove
train
def remove(self, oid): """ Remove a faked HBA resource. This method also updates the 'hba-uris' property in the parent Partition resource, by removing the URI for the faked HBA resource. Parameters: oid (string): The object ID of the faked HBA resource. """
python
{ "resource": "" }
q15102
FakedNicManager.add
train
def add(self, properties): """ Add a faked NIC resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'nic', if not specified. * Either 'network-adapter-port-uri' (for backing ROCE adapters) or 'virtual-switch-uri'(for backing OSA or Hipersockets adapters) is required to be specified. * 'device-number' will be auto-generated with a unique value within the partition in the range 0x8000 to 0xFFFF, if not specified. This method also updates the 'nic-uris' property in the parent faked Partition resource, by adding the URI for the faked NIC resource. This method also updates the 'connected-vnic-uris' property in the virtual switch referenced
python
{ "resource": "" }
q15103
FakedNicManager.remove
train
def remove(self, oid): """ Remove a faked NIC resource. This method also updates the 'nic-uris' property in the parent Partition resource, by removing the URI for the faked NIC resource. Parameters: oid (string): The object ID of the faked
python
{ "resource": "" }
q15104
FakedPartition.devno_alloc
train
def devno_alloc(self): """ Allocates a device number unique to this partition, in the range of 0x8000 to 0xFFFF. Returns: string: The device number as four hexadecimal digits in upper case. Raises: ValueError: No more device numbers available in
python
{ "resource": "" }
q15105
FakedPartition.wwpn_alloc
train
def wwpn_alloc(self): """ Allocates a WWPN unique to this partition, in the range of 0xAFFEAFFE00008000 to 0xAFFEAFFE0000FFFF. Returns: string: The WWPN as 16 hexadecimal digits in upper case. Raises: ValueError: No more WWPNs available in
python
{ "resource": "" }
q15106
FakedPortManager.add
train
def add(self, properties): """ Add a faked Port resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'network-port' or 'storage-port', if not specified. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by
python
{ "resource": "" }
q15107
FakedPortManager.remove
train
def remove(self, oid): """ Remove a faked Port resource. This method also updates the 'network-port-uris' or 'storage-port-uris' property in the parent Adapter resource, by removing the URI for the faked Port resource. Parameters: oid (string): The object ID of the
python
{ "resource": "" }
q15108
FakedVirtualFunctionManager.add
train
def add(self, properties): """ Add a faked Virtual Function resource. Parameters: properties (dict): Resource properties. Special handling and requirements for certain properties: * 'element-id' will be auto-generated with a unique value across all instances of this resource type, if not specified. * 'element-uri' will be auto-generated based upon the element ID, if not specified. * 'class' will be auto-generated to 'virtual-function', if not specified. * 'device-number' will
python
{ "resource": "" }
q15109
FakedVirtualFunctionManager.remove
train
def remove(self, oid): """ Remove a faked Virtual Function resource. This method also updates the 'virtual-function-uris' property in the parent Partition resource, by removing the URI for the faked Virtual Function resource. Parameters: oid (string): The object ID of the faked Virtual Function
python
{ "resource": "" }
q15110
FakedMetricsContextManager.add_metric_group_definition
train
def add_metric_group_definition(self, definition): """ Add a faked metric group definition. The definition will be used: * For later addition of faked metrics responses. * For returning the metric-group-info objects in the response of the Create Metrics Context operations. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: definition (:class:~zhmcclient.FakedMetricGroupDefinition`): Definition of the metric group. Raises: ValueError: A metric group definition with this name already exists.
python
{ "resource": "" }
q15111
FakedMetricsContextManager.get_metric_group_definition
train
def get_metric_group_definition(self, group_name): """ Get a faked metric group definition by its group name. Parameters: group_name (:term:`string`): Name of the metric group. Returns: :class:~zhmcclient.FakedMetricGroupDefinition`: Definition of the
python
{ "resource": "" }
q15112
FakedMetricsContextManager.add_metric_values
train
def add_metric_values(self, values): """ Add one set of faked metric values for a particular resource to the metrics response for a particular metric group, for later retrieval. For defined metric groups, see chapter "Metric groups" in the :term:`HMC API` book. Parameters: values (:class:`~zhmclient.FakedMetricObjectValues`): The set of metric values to be added. It specifies the resource URI and the targeted metric group name. """ assert isinstance(values, FakedMetricObjectValues) group_name =
python
{ "resource": "" }
q15113
FakedMetricsContextManager.get_metric_values
train
def get_metric_values(self, group_name): """ Get the faked metric values for a metric group, by its metric group name. The result includes all metric object values added earlier for that metric group name, using :meth:`~zhmcclient.FakedMetricsContextManager.add_metric_object_values` i.e. the metric values for all resources and all points in time that were added. Parameters: group_name (:term:`string`): Name of the metric group. Returns: iterable of :class:`~zhmclient.FakedMetricObjectValues`: The metric
python
{ "resource": "" }
q15114
FakedMetricsContext.get_metric_group_definitions
train
def get_metric_group_definitions(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation. If a 'metric-groups' property had been specified for this context, only those faked metric group definitions of its manager object that are in that list, are included in the result. Otherwise, all metric group definitions of its manager are included in the result. Returns: iterable of :class:~zhmcclient.FakedMetricGroupDefinition`: The faked metric group definitions, in the order they had been added. """ group_names = self.properties.get('metric-groups', None)
python
{ "resource": "" }
q15115
FakedMetricsContext.get_metric_group_infos
train
def get_metric_group_infos(self): """ Get the faked metric group definitions for this context object that are to be returned from its create operation, in the format needed for the "Create Metrics Context" operation response. Returns: "metric-group-infos" JSON object as described for the "Create Metrics Context "operation response. """ mg_defs = self.get_metric_group_definitions() mg_infos = [] for mg_def in mg_defs: metric_infos = [] for metric_name,
python
{ "resource": "" }
q15116
FakedMetricsContext.get_metric_values
train
def get_metric_values(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object. Returns: iterable of tuple (group_name, iterable of values): The faked metrics, in the order they had been added, where: group_name (string): Metric group name. values (:class:~zhmcclient.FakedMetricObjectValues`): The metric values for one resource at one point in time. """ group_names = self.properties.get('metric-groups', None) if not group_names: group_names = self.manager.get_metric_values_group_names()
python
{ "resource": "" }
q15117
FakedMetricsContext.get_metric_values_response
train
def get_metric_values_response(self): """ Get the faked metrics, for all metric groups and all resources that have been prepared on the manager object of this context object, as a string in the format needed for the "Get Metrics" operation response. Returns: "MetricsResponse" string as described for the "Get Metrics" operation response. """ mv_list = self.get_metric_values() resp_lines = [] for mv in mv_list: group_name = mv[0] resp_lines.append('"{}"'.format(group_name)) mo_vals = mv[1] for mo_val in mo_vals: resp_lines.append('"{}"'.format(mo_val.resource_uri)) resp_lines.append( str(timestamp_from_datetime(mo_val.timestamp))) v_list = [] for n, v in mo_val.values:
python
{ "resource": "" }
q15118
StorageVolume.update_properties
train
def update_properties(self, properties, email_to_addresses=None, email_cc_addresses=None, email_insert=None): """ Update writeable properties of this storage volume on the HMC, and optionally send emails to storage administrators requesting modification of the storage volume on the storage subsystem and of any resources related to the storage volume. This method performs the "Modify Storage Group Properties" operation, requesting modification of the volume. Authorization requirements: * Object-access permission to the storage group owning this storage volume. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): New property values for the volume. Allowable properties are the fields defined in the "storage-volume-request-info" nested object for the "modify" operation. That nested object is described in section "Request body contents" for operation "Modify Storage Group Properties" in the :term:`HMC API` book. The properties provided in this parameter will be copied and then amended with the `operation="modify"` and `element-uri` properties, and then used as a single array item for the `storage-volumes` field in the request body of the "Modify Storage Group Properties" operation. email_to_addresses (:term:`iterable` of :term:`string`): Email addresses of one or more storage administrator to be notified. If `None` or empty, no email will be sent. email_cc_addresses (:term:`iterable` of :term:`string`): Email addresses of one or more storage administrator to be copied on the notification email. If `None` or empty, nobody will be copied on the email. Must be `None` or empty if `email_to_addresses` is `None` or empty. email_insert (:term:`string`): Additional text to be inserted in the notification email. The text can include HTML formatting tags. If `None`, no additional text will be inserted. Must be `None` or empty if `email_to_addresses` is `None` or empty. Raises: :exc:`~zhmcclient.HTTPError`
python
{ "resource": "" }
q15119
VirtualFunctionManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the Virtual Functions of this Partition. Authorization requirements: * Object-access permission to this Partition. Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only the short set as returned by the list operation. filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.VirtualFunction` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ resource_obj_list = [] uris = self.partition.get_property('virtual-function-uris') if uris:
python
{ "resource": "" }
q15120
PortManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the Ports of this Adapter. If the adapter does not have any ports, an empty list is returned. Authorization requirements: * Object-access permission to this Adapter. Parameters: full_properties (bool): Controls whether the full set of resource properties should be retrieved, vs. only the short set as returned by the list operation. filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.Port` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ uris_prop = self.adapter.port_uris_prop if not uris_prop: # Adapter does not have any ports return [] uris
python
{ "resource": "" }
q15121
User.add_user_role
train
def add_user_role(self, user_role): """ Add the specified User Role to this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be added. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError`
python
{ "resource": "" }
q15122
User.remove_user_role
train
def remove_user_role(self, user_role): """ Remove the specified User Role from this User. This User must not be a system-defined or pattern-based user. Authorization requirements: * Task permission to the "Manage Users" task to modify a standard user or the "Manage User Templates" task to modify a template user. Parameters: user_role (:class:`~zhmcclient.UserRole`): User Role to be removed. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError`
python
{ "resource": "" }
q15123
FakedSession.get
train
def get(self, uri, logon_required=True): """ Perform the HTTP GET method against the resource identified by a URI, on the faked HMC. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session
python
{ "resource": "" }
q15124
FakedSession.post
train
def post(self, uri, body=None, logon_required=True, wait_for_completion=True, operation_timeout=None): """ Perform the HTTP POST method against the resource identified by a URI, using a provided request body, on the faked HMC. HMC operations using HTTP POST are either synchronous or asynchronous. Asynchronous operations return the URI of an asynchronously executing job that can be queried for status and result. Examples for synchronous operations: * With no response body: "Logon", "Update CPC Properties" * With a response body: "Create Partition" Examples for asynchronous operations: * With no ``job-results`` field in the completed job status response: "Start Partition" * With a ``job-results`` field in the completed job status response (under certain conditions): "Activate a Blade", or "Set CPC Power Save" The `wait_for_completion` parameter of this method can be used to deal with asynchronous HMC operations in a synchronous way. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. body (:term:`json object`): JSON object to be used as the HTTP request body (payload). `None` means the same as an empty dictionary, namely that no HTTP body is included in the request. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, the "Logon" operation does not require that. Because this is a faked HMC, this does not perform a real logon, but it is still used to update the state in the faked HMC. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested HMC operation, as follows: * If `True`, this method will wait for completion of the requested operation, regardless of whether the operation is synchronous or asynchronous. This will cause an additional entry in the time statistics to be created for the asynchronous operation and waiting for its completion. This entry will have a URI that is the targeted URI, appended with "+completion". * If `False`, this method will immediately return the result of the HTTP POST method, regardless of whether the operation is synchronous or asynchronous. operation_timeout (:term:`number`): Timeout in seconds, when waiting
python
{ "resource": "" }
q15125
_NotificationListener.on_disconnected
train
def on_disconnected(self): """ Event method that gets called when the JMS session has been disconnected. It hands over a termination notification (headers and message are None). """ with self._handover_cond: # Wait until receiver has processed the previous notification while len(self._handover_dict) > 0:
python
{ "resource": "" }
q15126
Console.restart
train
def restart(self, force=False, wait_for_available=True, operation_timeout=None): """ Restart the HMC represented by this Console object. Once the HMC is online again, this Console object, as well as any other resource objects accessed through this HMC, can continue to be used. An automatic re-logon will be performed under the covers, because the HMC restart invalidates the currently used HMC session. Authorization requirements: * Task permission for the "Shutdown/Restart" task. * "Remote Restart" must be enabled on the HMC. Parameters: force (bool): Boolean controlling whether the restart operation is processed when users are connected (`True`) or not (`False`). Users in this sense are local or remote GUI users. HMC WS API clients do not count as users for this purpose. wait_for_available (bool): Boolean controlling whether this method should wait for the HMC to become available again after the restart, as follows: * If `True`, this method will wait until the HMC has restarted and is available again. The :meth:`~zhmcclient.Client.query_api_version` method will be used to check for availability of the HMC. * If `False`, this method will return immediately once the HMC
python
{ "resource": "" }
q15127
Console.shutdown
train
def shutdown(self, force=False): """ Shut down and power off the HMC represented by this Console object. While the HMC is powered off, any Python resource objects retrieved from this HMC may raise exceptions upon further use. In order to continue using Python resource objects retrieved from this HMC, the HMC needs to be started again (e.g. by powering it on locally). Once the HMC is available again, Python resource objects retrieved from that HMC can continue to be used. An automatic re-logon will be performed under the covers, because the
python
{ "resource": "" }
q15128
Console._time_query_parms
train
def _time_query_parms(begin_time, end_time): """Return the URI query paramterer string for the specified begin time and end time.""" query_parms = [] if begin_time is not None: begin_ts = timestamp_from_datetime(begin_time)
python
{ "resource": "" }
q15129
Console.get_audit_log
train
def get_audit_log(self, begin_time=None, end_time=None): """ Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:class:`~py:datetime.datetime`): Begin time for filtering. Log entries with a creation time older than the begin time will be omitted from the results. If `None`, no such filtering is performed (and the oldest available log entries will be included). end_time (:class:`~py:datetime.datetime`): End time for filtering. Log entries with a creation time newer than the end time will be omitted from the results. If `None`, no such filtering is performed (and the newest available log entries will be included). Returns: :term:`json object`: A JSON object with the log entries, as described in section 'Response
python
{ "resource": "" }
q15130
Console.list_unmanaged_cpcs
train
def list_unmanaged_cpcs(self, name=None): """ List the unmanaged CPCs of this HMC. For details, see :meth:`~zhmcclient.UnmanagedCpc.list`. Authorization requirements: * None Parameters: name (:term:`string`): Regular expression pattern for the CPC name, as a filter that narrows the list of returned CPCs to those whose name property matches the specified pattern. `None` causes no filtering to happen, i.e. all unmanaged CPCs discovered by the HMC are returned. Returns:
python
{ "resource": "" }
q15131
Cpc.feature_info
train
def feature_info(self): """ Returns information about the features available for this CPC. Authorization requirements: * Object-access permission to this CPC. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for this CPC. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature. * `description` (:term:`unicode string`): Short description of the feature. * `state` (bool): Enablement state of the feature (`True` if the enabled, `False` if disabled).
python
{ "resource": "" }
q15132
Cpc.start
train
def start(self, wait_for_completion=True, operation_timeout=None): """ Start this CPC, using the HMC operation "Start CPC". Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Start (start a single DPM system)" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`:
python
{ "resource": "" }
q15133
Cpc.get_free_crypto_domains
train
def get_free_crypto_domains(self, crypto_adapters=None): """ Return a list of crypto domains that are free for usage on a list of crypto adapters in this CPC. A crypto domain is considered free for usage if it is not assigned to any defined partition of this CPC in access mode 'control-usage' on any of the specified crypto adapters. For this test, all currently defined partitions of this CPC are checked, regardless of whether or not they are active. This ensures that a crypto domain that is found to be free for usage can be assigned to a partition for 'control-usage' access to the specified crypto adapters, without causing a crypto domain conflict when activating that partition. Note that a similar notion of free domains does not exist for access mode 'control', because a crypto domain on a crypto adapter can be in control access by multiple active partitions. This method requires the CPC to be in DPM mode. **Example:** .. code-block:: text crypto domains adapters 0 1 2 3 +---+---+---+---+ c1 |A,c|a,c| | C | +---+---+---+---+ c2 |b,c|B,c| B | C | +---+---+---+---+ In this example, the CPC has two crypto adapters c1 and c2. For simplicity of the example, we assume these crypto adapters support only 4 crypto domains. Partition A uses only adapter c1 and has domain 0 in 'control-usage' access (indicated by an upper case letter 'A' in the corresponding cell) and has domain 1 in 'control' access (indicated by a lower case letter 'a' in the corresponding cell). Partition B uses only adapter c2 and has domain 0 in 'control' access and domains 1 and 2 in 'control-usage' access. Partition C uses both adapters, and has domains 0 and 1 in 'control' access and domain 3 in 'control-usage' access. The domains free for usage in this example are shown in the following table, for each combination of crypto adapters to be investigated: ===============
python
{ "resource": "" }
q15134
Cpc.set_power_save
train
def set_power_save(self, power_saving, wait_for_completion=True, operation_timeout=None): """ Set the power save setting of this CPC. The current power save setting in effect for a CPC is described in the "cpc-power-saving" property of the CPC. This method performs the HMC operation "Set CPC Power Save". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-save-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Save" task. Parameters: power_saving (:term:`string`): The new power save setting, with the possible values: * "high-performance" - The power consumption and performance of the CPC are not reduced. This is the default setting. * "low-power" - Low power consumption for all components of the CPC enabled for power saving. * "custom" - Components may have their own settings changed individually. No component settings are actually changed when this mode is entered. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. Returns: `None` or :class:`~zhmcclient.Job`: If `wait_for_completion` is `True`, returns `None`.
python
{ "resource": "" }
q15135
Cpc.set_power_capping
train
def set_power_capping(self, power_capping_state, power_cap=None, wait_for_completion=True, operation_timeout=None): """ Set the power capping settings of this CPC. The power capping settings of a CPC define whether or not the power consumption of the CPC is limited and if so, what the limit is. Use this method to limit the peak power consumption of a CPC, or to remove a power consumption limit for a CPC. The current power capping settings in effect for a CPC are described in the "cpc-power-capping-state" and "cpc-power-cap-current" properties of the CPC. This method performs the HMC operation "Set CPC Power Capping". It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and fails otherwise. This method will also fail if the CPC is under group control. Whether a CPC currently allows this method is described in the "cpc-power-cap-allowed" property of the CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission for the "Power Capping" task. Parameters: power_capping_state (:term:`string`): The power capping state to be set, with the possible values: * "disabled" - The power cap of the CPC is not set and the peak power consumption is not limited. This is the default setting. * "enabled" - The peak power consumption of the CPC is limited to the specified power cap value. * "custom" - Individually configure the components for power capping. No component settings are actually changed when this mode is entered. power_cap (:term:`integer`): The power cap value to be set, as a power consumption in Watt. This parameter is required not to be `None` if `power_capping_state="enabled"`. The specified value must be between the values of the CPC properties "cpc-power-cap-minimum" and "cpc-power-cap-maximum". wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing
python
{ "resource": "" }
q15136
Cpc.get_energy_management_properties
train
def get_energy_management_properties(self): """ Return the energy management properties of the CPC. The returned energy management properties are a subset of the properties of the CPC resource, and are also available as normal properties of the CPC resource. In so far, there is no new data provided by this method. However, because only a subset of the properties is returned, this method is faster than retrieving the complete set of CPC properties (e.g. via :meth:`~zhmcclient.BaseResource.pull_full_properties`). This method performs the HMC operation "Get CPC Energy Management Data", and returns only the energy management properties for this CPC from the operation result. Note that in non-ensemble mode of a CPC, the HMC operation result will only contain data for the CPC alone. It requires that the feature "Automate/advanced management suite" (FC 0020) is installed and enabled, and returns empty values for most properties, otherwise. Authorization requirements: * Object-access permission to this CPC. Returns: dict: A dictionary of properties of the CPC that are related to energy management. For details, see section "Energy management related additional properties" in the data model for the CPC resource in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError`: See the HTTP status and reason codes of operation "Get CPC Energy Management Data" in the :term:`HMC API`
python
{ "resource": "" }
q15137
Cpc.validate_lun_path
train
def validate_lun_path(self, host_wwpn, host_port, wwpn, lun): """ Validate if an FCP storage volume on an actual storage subsystem is reachable from this CPC, through a specified host port and using a specified host WWPN. This method performs the "Validate LUN Path" HMC operation. If the volume is reachable, the method returns. If the volume is not reachable (and no other errors occur), an :exc:`~zhmcclient.HTTPError` is raised, and its :attr:`~zhmcclient.HTTPError.reason` property indicates the reason as follows: * 484: Target WWPN cannot be reached. * 485: Target WWPN can be reached, but LUN cannot be reached. The CPC must have the "dpm-storage-management" feature enabled. Parameters: host_wwpn (:term:`string`): World wide port name (WWPN) of the host (CPC), as a hexadecimal number of up to 16 characters in any lexical case. This may be the WWPN of the physical storage port, or a WWPN of a virtual HBA. In any case, it must be the kind of WWPN that is used
python
{ "resource": "" }
q15138
UserPatternManager.reorder
train
def reorder(self, user_patterns): """ Reorder the User Patterns of the HMC as specified. The order of User Patterns determines the search order during logon processing. Authorization requirements: * Task permission to the "Manage User Patterns" task. Parameters: user_patterns (list of :class:`~zhmcclient.UserPattern`): The User Patterns in the desired order. Must not be `None`. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError`
python
{ "resource": "" }
q15139
TimeStats.reset
train
def reset(self): """ Reset the time statistics data for the operation. """ self._count
python
{ "resource": "" }
q15140
TimeStatsKeeper.get_stats
train
def get_stats(self, name): """ Get the time statistics for a name. If a time statistics for that name does not exist yet, create one. Parameters: name (string): Name of the time statistics. Returns: TimeStats: The time statistics for the specified name. If the statistics keeper is disabled, a dummy time statistics object is
python
{ "resource": "" }
q15141
UnmanagedCpcManager.list
train
def list(self, full_properties=False, filter_args=None): """ List the unmanaged CPCs exposed by the HMC this client is connected to. Because the CPCs are unmanaged, the returned :class:`~zhmcclient.UnmanagedCpc` objects cannot perform any operations and will have only the following properties: * ``object-uri`` * ``name`` Authorization requirements: * None Parameters: full_properties (bool): Ignored (exists for consistency with other list() methods). filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : A list of :class:`~zhmcclient.UnmanagedCpc` objects. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ resource_obj_list = [] resource_obj = self._try_optimized_lookup(filter_args) if resource_obj: resource_obj_list.append(resource_obj)
python
{ "resource": "" }
q15142
parse_query_parms
train
def parse_query_parms(method, uri, query_str): """ Parse the specified query parms string and return a dictionary of query parameters. The key of each dict item is the query parameter name, and the value of each dict item is the query parameter value. If a query parameter shows up more than once, the resulting dict item value is a list of all those values. query_str is the query string from the URL, everything after the '?'. If it is empty or None, None is returned. If a query parameter is not of the format "name=value", an HTTPError 400,1 is raised. """ if not query_str: return None query_parms = {} for query_item in query_str.split('&'): # Example for these items: 'name=a%20b' if query_item == '': continue items = query_item.split('=') if len(items) != 2: raise BadRequestError( method, uri, reason=1, message="Invalid format for URI query parameter: {!r} "
python
{ "resource": "" }
q15143
check_required_fields
train
def check_required_fields(method, uri, body, field_names): """ Check required fields in the request body. Raises: BadRequestError with reason 3: Missing request body BadRequestError with reason 5: Missing required field in request body """ # Check presence of request body if body is None: raise BadRequestError(method, uri, reason=3, message="Missing request body") # Check required input fields for field_name in field_names:
python
{ "resource": "" }
q15144
check_valid_cpc_status
train
def check_valid_cpc_status(method, uri, cpc): """ Check that the CPC is in a valid status, as indicated by its 'status' property. If the Cpc object does not have a 'status' property set, this function does nothing (in order to make the mock support easy to use). Raises: ConflictError with reason 1: The CPC itself has been targeted by the operation. ConflictError with reason 6: The CPC is hosting the resource targeted by the operation. """ status = cpc.properties.get('status', None) if status is None: # Do nothing if no status is set on the faked CPC return valid_statuses = ['active', 'service-required', 'degraded', 'exceptions'] if status not in valid_statuses: if uri.startswith(cpc.uri): # The uri targets the CPC (either is the CPC uri or some # multiplicity under the CPC uri) raise ConflictError(method, uri, reason=1, message="The operation cannot be performed "
python
{ "resource": "" }
q15145
ensure_crypto_config
train
def ensure_crypto_config(partition): """ Ensure that the 'crypto-configuration' property on the faked partition is initialized. """ if 'crypto-configuration' not in partition.properties or \ partition.properties['crypto-configuration'] is None: partition.properties['crypto-configuration'] = {} crypto_config = partition.properties['crypto-configuration'] if 'crypto-adapter-uris' not in crypto_config or \ crypto_config['crypto-adapter-uris'] is None: crypto_config['crypto-adapter-uris']
python
{ "resource": "" }
q15146
PartitionManager.create
train
def create(self, properties): """ Create and configure a Partition in this CPC. Authorization requirements: * Object-access permission to this CPC. * Task permission to the "New Partition" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Partition' in the :term:`HMC API` book. Returns: Partition: The resource object for the new Partition. The object will
python
{ "resource": "" }
q15147
Partition.feature_enabled
train
def feature_enabled(self, feature_name): """ Indicates whether the specified feature is enabled for the CPC of this partition. The HMC must generally support features, and the specified feature must be available for the CPC. For a list of available features, see section "Features" in the :term:`HMC API`, or use the :meth:`feature_info` method. Authorization requirements: * Object-access permission to this partition. Parameters: feature_name (:term:`string`): The name of the feature. Returns: bool: `True` if the feature is enabled, or `False` if the feature is
python
{ "resource": "" }
q15148
Partition.feature_info
train
def feature_info(self): """ Returns information about the features available for the CPC of this partition. Authorization requirements: * Object-access permission to this partition. Returns: :term:`iterable`: An iterable where each item represents one feature that is available for the CPC of this partition. Each item is a dictionary with the following items: * `name` (:term:`unicode string`): Name of the feature.
python
{ "resource": "" }
q15149
Partition.dump_partition
train
def dump_partition(self, parameters, wait_for_completion=True, operation_timeout=None): """ Dump this Partition, by loading a standalone dump program from a SCSI device and starting its execution, using the HMC operation 'Dump Partition'. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Dump Partition" task. Parameters: parameters (dict): Input parameters for the operation. Allowable input parameters are defined in section 'Request body contents' in section 'Dump Partition' in the :term:`HMC API` book. wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the
python
{ "resource": "" }
q15150
Partition.mount_iso_image
train
def mount_iso_image(self, image, image_name, ins_file_name): """ Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition. * Task permission to the "Partition Details" task. Parameters: image (:term:`byte string` or file-like object): The content of the ISO image. Images larger than 2GB cannot be specified as a Byte string; they must be specified as a file-like object. File-like objects must have opened the file in binary mode. image_name (:term:`string`): The displayable name of the image. This value must be a valid Linux file name without directories, must not contain blanks, and must end with '.iso' in lower case. This value will be shown in the 'boot-iso-image-name' property of this partition. ins_file_name (:term:`string`): The path name of the INS file within
python
{ "resource": "" }
q15151
Partition.open_os_message_channel
train
def open_os_message_channel(self, include_refresh_messages=True): """ Open a JMS message channel to this partition's operating system, returning the string "topic" representing the message channel. Parameters: include_refresh_messages (bool): Boolean controlling whether refresh operating systems messages should be sent, as follows: * If `True`, refresh messages will be recieved when the user connects to the topic. The default.
python
{ "resource": "" }
q15152
Partition.send_os_command
train
def send_os_command(self, os_command_text, is_priority=False): """ Send a command to the operating system running in this partition. Parameters: os_command_text (string): The text of the operating system command. is_priority (bool): Boolean controlling whether this is a priority operating system command, as follows: * If `True`, this message is treated as a priority operating system command. * If `False`, this message is not treated as a priority operating system command. The default.
python
{ "resource": "" }
q15153
Partition.wait_for_status
train
def wait_for_status(self, status, status_timeout=None): """ Wait until the status of this partition has a desired value. Parameters: status (:term:`string` or iterable of :term:`string`): Desired partition status or set of status values to reach; one or more of the values defined for the 'status' property in the data model for partitions in the :term:`HMC API` book. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the partition has reached one of the desired status values. The special value 0 means that no timeout is set. `None` means that the default status timeout will be used. If the timeout expires, a :exc:`~zhmcclient.StatusTimeout` is raised. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.StatusTimeout`: The status timeout expired while waiting for the desired partition status. """ if status_timeout is None: status_timeout = \ self.manager.session.retry_timeout_config.status_timeout if status_timeout > 0: end_time = time.time() + status_timeout
python
{ "resource": "" }
q15154
Partition.change_crypto_domain_config
train
def change_crypto_domain_config(self, crypto_domain_index, access_mode): """ Change the access mode for a crypto domain that is currently included in the crypto configuration of this partition. The access mode will be changed for the specified crypto domain on all crypto adapters currently included in the crypto configuration of this partition. For the general principle for maintaining crypto configurations of partitions, see :meth:`~zhmcclient.Partition.increase_crypto_config`. Authorization requirements: * Object-access permission to this Partition.
python
{ "resource": "" }
q15155
Partition.zeroize_crypto_domain
train
def zeroize_crypto_domain(self, crypto_adapter, crypto_domain_index): """ Zeroize a single crypto domain on a crypto adapter. Zeroizing a crypto domain clears the cryptographic keys and non-compliance mode settings in the crypto domain. The crypto domain must be attached to this partition in "control-usage" access mode. Supported CPC versions: z14 GA2 and above, and the corresponding LinuxOne systems. Authorization requirements: * Object-access permission to this Partition and to the Crypto Adapter. * Task permission to the "Zeroize Crypto Domain" task. Parameters: crypto_adapter (:class:`~zhmcclient.Adapter`): Crypto adapter with the crypto domain to be zeroized.
python
{ "resource": "" }
q15156
Partition.list_attached_storage_groups
train
def list_attached_storage_groups(self, full_properties=False): """ Return the storage groups that are attached to this partition. The CPC must have the "dpm-storage-management" feature enabled. Authorization requirements: * Object-access permission to this partition. * Task permission to the "Partition Details" task. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned storage group is being retrieved, vs. only the following short set:
python
{ "resource": "" }
q15157
PasswordRule.update_properties
train
def update_properties(self, properties): """ Update writeable properties of this PasswordRule. The Password Rule must be user-defined. System-defined Password Rules cannot be updated. Authorization requirements: * Task permission to the "Manage Password Rules" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model' in section 'Password Rule object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError`
python
{ "resource": "" }
q15158
Client.version_info
train
def version_info(self): """ Returns API version information for the HMC. This operation does not require authentication. Returns: :term:`HMC API version`: The HMC API version supported by the HMC.
python
{ "resource": "" }
q15159
Client.query_api_version
train
def query_api_version(self): """ The Query API Version operation returns information about the level of Web Services API supported by the HMC. This operation does not require authentication. Returns: :term:`json object`: A JSON object with members ``api-major-version``, ``api-minor-version``, ``hmc-version`` and ``hmc-name``. For details about these properties, see section 'Response body contents' in section 'Query API Version' in the :term:`HMC API` book. Raises:
python
{ "resource": "" }
q15160
Client.get_inventory
train
def get_inventory(self, resources): """ Returns a JSON object with the requested resources and their properties, that are managed by the HMC. This method performs the 'Get Inventory' HMC operation. Parameters: resources (:term:`iterable` of :term:`string`): Resource classes and/or resource classifiers specifying the types of resources that should be included in the result. For valid values, see the 'Get Inventory' operation in the :term:`HMC API` book. Element resources of the specified resource types are automatically
python
{ "resource": "" }
q15161
BaseResource.pull_full_properties
train
def pull_full_properties(self): """ Retrieve the full set of resource properties and cache them in this object. Authorization requirements: * Object-access permission to this resource. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError`
python
{ "resource": "" }
q15162
BaseResource.get_property
train
def get_property(self, name): """ Return the value of a resource property. If the resource property is not cached in this object yet, the full set of resource properties is retrieved and cached in this object, and the resource property is again attempted to be returned. Authorization requirements: * Object-access permission to this resource. Parameters: name (:term:`string`): Name of the resource property, using the names defined in the respective 'Data model' sections in the :term:`HMC API` book. Returns: The value of the resource property. Raises:
python
{ "resource": "" }
q15163
make_client
train
def make_client(zhmc, userid=None, password=None): """ Create a `Session` object for the specified HMC and log that on. Create a `Client` object using that `Session` object, and return it. If no userid and password are specified, and if no previous call to this method was made, userid and password are interactively inquired. Userid and password are saved in module-global variables for future calls to this method. """ global USERID, PASSWORD # pylint: disable=global-statement USERID = userid or USERID or \ six.input('Enter userid for HMC {}: '.format(zhmc)) PASSWORD = password or PASSWORD or \
python
{ "resource": "" }
q15164
repr_list
train
def repr_list(_list, indent): """Return a debug representation of a list or tuple.""" # pprint represents lists and tuples in one row if possible. We want one # per row, so we iterate ourselves. if _list is None: return 'None' if isinstance(_list, MutableSequence): bm = '[' em = ']' elif isinstance(_list, Iterable): bm = '(' em = ')' else: raise TypeError("Object must be an iterable, but is
python
{ "resource": "" }
q15165
repr_dict
train
def repr_dict(_dict, indent): """Return a debug representation of a dict or OrderedDict.""" # pprint represents OrderedDict objects using the tuple init syntax, # which is not very readable. Therefore, dictionaries are iterated over. if _dict is None: return 'None' if not isinstance(_dict, Mapping): raise TypeError("Object must be a mapping, but is a %s" % type(_dict)) if isinstance(_dict, OrderedDict): kind = 'ordered' ret = '%s {\n' % kind # non standard syntax for the kind indicator for key in six.iterkeys(_dict): value = _dict[key]
python
{ "resource": "" }
q15166
repr_timestamp
train
def repr_timestamp(timestamp): """Return a debug representation of an HMC timestamp number.""" if timestamp is None: return 'None' dt = datetime_from_timestamp(timestamp)
python
{ "resource": "" }
q15167
StorageGroupManager.create
train
def create(self, properties): """ Create and configure a storage group. The new storage group will be associated with the CPC identified by the `cpc-uri` input property. Authorization requirements: * Object-access permission to the CPC that will be associated with the new storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Storage Group' in the :term:`HMC API` book. The 'cpc-uri' property identifies the CPC to which the new storage group will be associated, and is required to be specified in this parameter. Returns: :class:`~zhmcclient.StorageGroup`: The resource object for the new storage group. The object will have its 'object-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError`
python
{ "resource": "" }
q15168
StorageGroup.list_attached_partitions
train
def list_attached_partitions(self, name=None, status=None): """ Return the partitions to which this storage group is currently attached, optionally filtered by partition name and status. Authorization requirements: * Object-access permission to this storage group. * Task permission to the "Configure Storage - System Programmer" task. Parameters: name (:term:`string`): Filter pattern (regular expression) to limit returned partitions to those that have a matching name. If `None`, no filtering for the partition name takes place. status (:term:`string`): Filter string to limit returned partitions to those that have a matching status. The value must be a valid partition status property value. If `None`, no filtering for the partition status takes place. Returns: List of :class:`~zhmcclient.Partition` objects representing the partitions to whivch this storage group is currently attached, with a minimal set of properties ('object-id', 'name', 'status'). Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """
python
{ "resource": "" }
q15169
StorageGroup.add_candidate_adapter_ports
train
def add_candidate_adapter_ports(self, ports): """ Add a list of storage adapter ports to this storage group's candidate adapter ports list. This operation only applies to storage groups of type "fcp". These adapter ports become candidates for use as backing adapters when creating virtual storage resources when the storage group is attached to a partition. The adapter ports should have connectivity to the storage area network (SAN). Candidate adapter ports may only be added before the CPC discovers a working communications path, indicated by a "verified" status on at least one of this storage group's WWPNs. After that point, all adapter ports in the storage group are automatically detected and manually adding them is no longer possible. Because the CPC discovers working communications paths automatically, candidate adapter ports do not need to be added by the user. Any ports that are added, are validated by the CPC during discovery, and may or may not actually be used. Authorization requirements: * Object-access permission to this storage group. * Object-access permission to the adapter of each specified port. * Task permission to the "Configure Storage - System Programmer" task.
python
{ "resource": "" }
q15170
StorageGroup.list_candidate_adapter_ports
train
def list_candidate_adapter_ports(self, full_properties=False): """ Return the current candidate storage adapter port list of this storage group. The result reflects the actual list of ports used by the CPC, including any changes that have been made during discovery. The source for this information is the 'candidate-adapter-port-uris' property of the storage group object. Parameters: full_properties (bool): Controls that the full set of resource properties for each returned candidate storage adapter port is being retrieved, vs. only the following short set: "element-uri", "element-id", "class", "parent". TODO: Verify short list of properties. Returns: List of :class:`~zhmcclient.Port` objects representing the current candidate storage adapter ports of this storage group. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """
python
{ "resource": "" }
q15171
AdapterManager.create_hipersocket
train
def create_hipersocket(self, properties): """ Create and configure a HiperSockets Adapter in this CPC. Authorization requirements: * Object-access permission to the scoping CPC. * Task permission to the "Create HiperSockets Adapter" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create Hipersocket' in the :term:`HMC API` book. Returns: :class:`~zhmcclient.Adapter`: The resource object for the new HiperSockets Adapter.
python
{ "resource": "" }
q15172
Adapter.change_crypto_type
train
def change_crypto_type(self, crypto_type, zeroize=None): """ Reconfigures a cryptographic adapter to a different crypto type. This operation is only supported for cryptographic adapters. The cryptographic adapter must be varied offline before its crypto type can be reconfigured. Authorization requirements: * Object-access permission to this Adapter. * Task permission to the "Adapter Details" task. Parameters: crypto_type (:term:`string`): - ``"accelerator"``: Crypto Express5S Accelerator - ``"cca-coprocessor"``: Crypto Express5S CCA Coprocessor - ``"ep11-coprocessor"``: Crypto Express5S EP11 Coprocessor zeroize (bool): Specifies whether the cryptographic adapter will be zeroized when
python
{ "resource": "" }
q15173
Lpar.stop
train
def stop(self, wait_for_completion=True, operation_timeout=None, status_timeout=None, allow_status_exceptions=False): """ Stop this LPAR, using the HMC operation "Stop Logical Partition". The stop operation stops the processors from processing instructions. This HMC operation has deferred status behavior: If the asynchronous job on the HMC is complete, it takes a few seconds until the LPAR status has reached the desired value. If `wait_for_completion=True`, this method repeatedly checks the status of the LPAR after the HMC operation has completed, and waits until the status is in the desired state "operating", or if `allow_status_exceptions` was set additionally in the state "exceptions". Authorization requirements: * Object-access permission to the CPC containing this LPAR. * Object-access permission to this LPAR. * Task permission for the "Stop" task. Parameters: wait_for_completion (bool): Boolean controlling whether this method should wait for completion of the requested asynchronous HMC operation, as follows: * If `True`, this method will wait for completion of the asynchronous job performing the operation, and for the status becoming "operating" (or in addition "exceptions", if `allow_status_exceptions` was set. * If `False`, this method will return immediately once the HMC has accepted the request to perform the operation. operation_timeout (:term:`number`): Timeout in seconds, for waiting for completion of the asynchronous job performing the operation. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.OperationTimeout` is raised. status_timeout (:term:`number`): Timeout in seconds, for waiting that the status of the LPAR has reached the desired status, after the HMC operation has completed. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires when `wait_for_completion=True`, a :exc:`~zhmcclient.StatusTimeout` is raised. allow_status_exceptions (bool):
python
{ "resource": "" }
q15174
_result_object
train
def _result_object(result): """ Return the JSON payload in the HTTP response as a Python dict. Parameters: result (requests.Response): HTTP response object. Raises: zhmcclient.ParseError: Error parsing the returned JSON. """ content_type = result.headers.get('content-type', None) if content_type is None or content_type.startswith('application/json'): # This function is only called when there is content expected. # Therefore, a response without content will result in a ParseError. try: return result.json(object_pairs_hook=OrderedDict) except ValueError as exc: raise ParseError( "JSON parse error in HTTP response: {}. " "HTTP request: {} {}. " "Response status {}. " "Response content-type: {!r}. " "Content (max.1000, decoded using {}): {}". format(exc.args[0], result.request.method, result.request.url, result.status_code, content_type, result.encoding, _text_repr(result.text, 1000))) elif content_type.startswith('text/html'): # We are in some error situation. The HMC returns HTML content # for some 5xx status codes. We try to deal with it somehow, # but we are not going as far as real HTML parsing. m = re.search(r'charset=([^;,]+)', content_type) if m: encoding = m.group(1) # e.g. RFC "ISO-8859-1" else: encoding = 'utf-8' try: html_uni = result.content.decode(encoding) except LookupError: html_uni = result.content.decode() # We convert to one line to be regexp-friendly. html_oneline = html_uni.replace('\r\n', '\\n').replace('\r', '\\n').\ replace('\n', '\\n') # Check for some well-known errors: if re.search(r'javax\.servlet\.ServletException: ' r'Web Services are not enabled\.', html_oneline): html_title = "Console Configuration Error" html_details = "Web Services API is not enabled on the HMC." html_reason = HTML_REASON_WEB_SERVICES_DISABLED else: m = re.search( r'<title>([^<]*)</title>.*' r'<h2>Details:</h2>(.*)(<hr size="1" noshade>)?</body>', html_oneline) if m: html_title = m.group(1)
python
{ "resource": "" }
q15175
RetryTimeoutConfig.override_with
train
def override_with(self, override_config): """ Return a new configuration object that represents the configuration from this configuration object acting as a default, and the specified configuration object overriding that default. Parameters: override_config (:class:`~zhmcclient.RetryTimeoutConfig`): The configuration object overriding the defaults defined in this configuration object. Returns: :class:`~zhmcclient.RetryTimeoutConfig`: A new configuration object representing this configuration object,
python
{ "resource": "" }
q15176
Session.is_logon
train
def is_logon(self, verify=False): """ Return a boolean indicating whether the session is currently logged on to the HMC. By default, this method checks whether there is a session-id set and considers that sufficient for determining that the session is logged on. The `verify` parameter can be used to verify the validity of a session-id that is already set, by issuing a dummy operation ("Get Console Properties") to the HMC. Parameters: verify (bool): If a session-id is already set, verify its validity.
python
{ "resource": "" }
q15177
Session._do_logon
train
def _do_logon(self): """ Log on, unconditionally. This can be used to re-logon. This requires credentials to be provided. Raises: :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ if self._userid is None: raise ClientAuthError("Userid is not provided.")
python
{ "resource": "" }
q15178
Session._new_session
train
def _new_session(retry_timeout_config): """ Return a new `requests.Session` object. """ retry = requests.packages.urllib3.Retry( total=None, connect=retry_timeout_config.connect_retries, read=retry_timeout_config.read_retries, method_whitelist=retry_timeout_config.method_whitelist, redirect=retry_timeout_config.max_redirects) session =
python
{ "resource": "" }
q15179
Session._do_logoff
train
def _do_logoff(self): """ Log off, unconditionally. Raises: :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.HTTPError` """ session_uri = '/api/sessions/this-session'
python
{ "resource": "" }
q15180
Session._log_http_request
train
def _log_http_request(method, url, headers=None, content=None): """ Log the HTTP request of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) headers (iterable): HTTP headers used for the request content (:term:`string`): HTTP body (aka content) used for the request """ if method == 'POST' and url.endswith('/api/sessions'): #
python
{ "resource": "" }
q15181
Session._log_http_response
train
def _log_http_response(method, url, status, headers=None, content=None): """ Log the HTTP response of an HMC REST API call, at the debug level. Parameters: method (:term:`string`): HTTP method name in upper case, e.g. 'GET' url (:term:`string`): HTTP URL (base URL and operation URI) status (integer): HTTP status code headers (iterable): HTTP headers returned in the response content (:term:`string`): HTTP body (aka content) returned in the response """ if method == 'POST' and url.endswith('/api/sessions'): # In Python 3 up to 3.5, json.loads() requires unicode strings. if sys.version_info[0] == 3 and sys.version_info[1] in (4, 5) and \ isinstance(content, six.binary_type): content = content.decode('utf-8') try: content_dict = json.loads(content) except ValueError as exc: content = '"Error: Cannot parse JSON payload of response: ' \
python
{ "resource": "" }
q15182
Session.delete
train
def delete(self, uri, logon_required=True): """ Perform the HTTP DELETE method against the resource identified by a URI. A set of standard HTTP headers is automatically part of the request. If the HMC session token is expired, this method re-logs on and retries the operation. Parameters: uri (:term:`string`): Relative URI path of the resource, e.g. "/api/session/{session-id}". This URI is relative to the base URL of the session (see the :attr:`~zhmcclient.Session.base_url` property). Must not be `None`. logon_required (bool): Boolean indicating whether the operation requires that the session is logged on to the HMC. For example, for the logoff operation, it does not make sense to first log on. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.ClientAuthError` :exc:`~zhmcclient.ServerAuthError` :exc:`~zhmcclient.ConnectionError` """ if logon_required:
python
{ "resource": "" }
q15183
Job.check_for_completion
train
def check_for_completion(self): """ Check once for completion of the job and return completion status and result if it has completed. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Returns: : A tuple (status, result) with: * status (:term:`string`): Completion status of the job, as returned in the ``status`` field of the response body of the "Query Job Status" HMC operation, as follows: * ``"complete"``: Job completed (successfully). * any other value: Job is not yet complete. * result (:term:`json object` or `None`): `None` for incomplete jobs. For completed jobs, the result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the "Query Job Status" HMC operation. That result is a :term:`json object` as described for the asynchronous operation, or `None` if the operation has no result. Raises: :exc:`~zhmcclient.HTTPError`: The job completed in
python
{ "resource": "" }
q15184
Job.wait_for_completion
train
def wait_for_completion(self, operation_timeout=None): """ Wait for completion of the job, then delete the job on the HMC and return the result of the original asynchronous HMC operation, if it completed successfully. If the job completed in error, an :exc:`~zhmcclient.HTTPError` exception is raised. Parameters: operation_timeout (:term:`number`): Timeout in seconds, when waiting for completion of the job. The special value 0 means that no timeout is set. `None` means that the default async operation timeout of the session is used. If the timeout expires, a :exc:`~zhmcclient.OperationTimeout` is raised. This method gives completion of the job priority over strictly achieving the timeout. This may cause a slightly longer duration of the method than prescribed by the timeout. Returns: :term:`json object` or `None`: The result of the original asynchronous operation that was performed by the job, from the ``job-results`` field of the response body of the
python
{ "resource": "" }
q15185
logged_api_call
train
def logged_api_call(func): """ Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): The original function being decorated. Returns: function object: The function wrappering the original function being decorated. Raises: TypeError: The @logged_api_call decorator must be used on a function or method (and not on top of the @property decorator). """ # Note that in this decorator function, we are in a module loading context, # where the decorated functions are being defined. When this decorator # function is called, its call stack represents the definition of the # decorated functions. Not all global definitions in the module have been # defined yet, and methods of classes that are decorated with this # decorator are still functions at this point (and not yet methods). module = inspect.getmodule(func) if not inspect.isfunction(func) or not hasattr(module, '__name__'): raise TypeError("The @logged_api_call decorator must be used on a " "function or method (and not on top of the @property " "decorator)") try: # We avoid the use of inspect.getouterframes() because it is slow, # and use the pointers up the stack frame, instead. this_frame = inspect.currentframe() # this decorator function here apifunc_frame = this_frame.f_back # the decorated API function apifunc_owner = inspect.getframeinfo(apifunc_frame)[2] finally: # Recommended way to deal with frame objects to avoid ref cycles del this_frame del apifunc_frame # TODO: For inner functions, show all outer levels instead of just one. if apifunc_owner == '<module>': # The decorated API function is defined globally (at module level) apifunc_str = '{func}()'.format(func=func.__name__) else: # The decorated API function is defined in a class or in a function
python
{ "resource": "" }
q15186
generic_div
train
def generic_div(a, b): """Simple function to divide two numbers"""
python
{ "resource": "" }
q15187
buggy_div
train
def buggy_div(request): """ A buggy endpoint to perform division between query parameters a and b. It will fail if b is equal to 0 or
python
{ "resource": "" }
q15188
ascii
train
def ascii(graph): """Format graph as an ASCII art.""" from .._ascii import DAG from .._echo
python
{ "resource": "" }
q15189
_jsonld
train
def _jsonld(graph, format, *args, **kwargs): """Return formatted graph in JSON-LD ``format`` function.""" import json from pyld import jsonld from renku.models._jsonld import asjsonld output = getattr(jsonld,
python
{ "resource": "" }
q15190
dot
train
def dot(graph, simple=True, debug=False, landscape=False): """Format graph as a dot file.""" import sys from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser from rdflib.tools.rdf2dot import rdf2dot register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') g = ConjunctiveGraph().parse( data=_jsonld(graph, 'expand'), format='json-ld', ) g.bind('prov', 'http://www.w3.org/ns/prov#') g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#') g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#')
python
{ "resource": "" }
q15191
_rdf2dot_simple
train
def _rdf2dot_simple(g, stream): """Create a simple graph of processes and artifacts.""" from itertools import chain import re path_re = re.compile( r'file:///(?P<type>[a-zA-Z]+)/' r'(?P<commit>\w+)' r'(?P<path>.+)?' ) inputs = g.query( """ SELECT ?input ?role ?activity ?comment WHERE { ?activity (prov:qualifiedUsage/prov:entity) ?input . ?activity prov:qualifiedUsage ?qual . ?qual prov:hadRole ?role . ?qual prov:entity ?input . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun . ?activity rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) outputs = g.query( """ SELECT ?activity ?role ?output ?comment WHERE { ?output (prov:qualifiedGeneration/prov:activity) ?activity . ?output prov:qualifiedGeneration ?qual . ?qual prov:hadRole ?role . ?qual prov:activity ?activity . ?qual rdf:type ?type . ?activity rdf:type wfprov:ProcessRun ; rdfs:comment ?comment . FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun} } """ ) activity_nodes = {} artifact_nodes = {} for source, role, target, comment, in chain(inputs, outputs): # extract the pieces of the process URI src_path = path_re.match(source).groupdict() tgt_path = path_re.match(target).groupdict() # write the edge stream.write( '\t"{src_commit}:{src_path}" -> ' '"{tgt_commit}:{tgt_path}" ' '[label={role}] \n'.format( src_commit=src_path['commit'][:5], src_path=src_path.get('path') or '', tgt_commit=tgt_path['commit'][:5], tgt_path=tgt_path.get('path') or '', role=role ) ) if src_path.get('type') == 'commit': activity_nodes.setdefault(source,
python
{ "resource": "" }
q15192
makefile
train
def makefile(graph): """Format graph as Makefile.""" from renku.models.provenance.activities import ProcessRun, WorkflowRun for activity in graph.activities.values(): if not isinstance(activity, ProcessRun): continue elif isinstance(activity, WorkflowRun): steps = activity.subprocesses.values() else: steps = [activity] for step in steps: click.echo(' '.join(step.outputs) + ': ' + ' '.join(step.inputs)) tool =
python
{ "resource": "" }
q15193
nt
train
def nt(graph): """Format graph as n-tuples.""" from rdflib import ConjunctiveGraph from rdflib.plugin import register, Parser register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser') click.echo( ConjunctiveGraph().parse(
python
{ "resource": "" }
q15194
install
train
def install(client, force): """Install Git hooks.""" import pkg_resources from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path = Path(get_hook_path(hook, client.repo.git_dir)) if hook_path.exists(): if not force: click.echo( 'Hook already exists. Skipping {0}'.format(str(hook_path)), err=True ) continue else:
python
{ "resource": "" }
q15195
uninstall
train
def uninstall(client): """Uninstall Git hooks.""" from git.index.fun import hook_path as get_hook_path for hook in HOOKS: hook_path
python
{ "resource": "" }
q15196
format_cell
train
def format_cell(cell, datetime_fmt=None): """Format a cell.""" if datetime_fmt and isinstance(cell, datetime):
python
{ "resource": "" }
q15197
tabulate
train
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs): """Pretty-print a collection.""" if isinstance(headers, dict): attrs = headers.keys() # if mapping is not specified keep original names = [ key if value is None else value for key, value in headers.items() ] else: attrs = names = headers table = [(
python
{ "resource": "" }
q15198
_convert_dataset_files
train
def _convert_dataset_files(value): """Convert dataset files.""" output = {} for k, v in value.items(): inst
python
{ "resource": "" }
q15199
remove
train
def remove(ctx, client, sources): """Remove files and check repository for potential problems.""" from renku.api._git import _expand_directories def fmt_path(path): """Format path as relative to the client path.""" return str(Path(path).absolute().relative_to(client.path)) files = { fmt_path(source): fmt_path(file_or_dir) for file_or_dir in sources for source in _expand_directories((file_or_dir, )) } # 1. Update dataset metadata files. with progressbar( client.datasets.values(), item_show_func=lambda item: str(item.short_id) if item else '', label='Updating dataset metadata', width=0, ) as bar: for dataset in bar: remove = [] for key, file_ in dataset.files.items(): filepath = fmt_path(file_.full_path) if filepath in files: remove.append(key) if remove: for key in remove:
python
{ "resource": "" }