output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def live_migrate_move(self, userid, destination, parms): """ moves the specified virtual machine, while it continues to run, to the specified system within the SSI cluster. """ rd = ('migratevm %(uid)s move --destination %(dest)s ' % {'uid': userid, 'dest': destination}) ...
Can you create a Python 3 function that moves the specified virtual machine while it continues to run to run to the specified system within the SSI cluster.
As a Python code composer, you craft elegant and concise scripts.
def create_vm(self, userid, cpu, memory, disk_list, profile, max_cpu, max_mem, ipl_from, ipl_param, ipl_loadparam): """ Create VM and add disks if specified. """ rd = ('makevm %(uid)s directory LBYONLY %(mem)im %(pri)s ' '--cpus %(cpu)i --profile %(prof)s --maxCPU %(max_c...
Can you create a Python 3 function that creates VM and add disks if specified.
As a Python code analyst, you investigate and solve complex coding mysteries
def _add_mdisk(self, userid, disk, vdev): """Create one disk for userid NOTE: No read, write and multi password specified, and access mode default as 'MR'. """ size = disk['size'] fmt = disk.get('format', 'ext4') disk_pool = disk.get('disk_pool') or CONF.zvm.dis...
Write a Python 3 function that can add one mdisk to userid
As a Python code composer, you craft elegant and concise scripts.
Get the list of guests that are created by SDK return userid list
Can you generate the documentation for the following Python 3 function def get_vm_list(self): action = "list all guests in database" with zvmutils.log_and_reraise_sdkbase_error(action): guests_in_db = self._GuestDbOperator.get_guest_list() guests_migrated = self._GuestDbOperator....
You are a Python code architect, reviewing and designing scalable and efficient code
def guest_authorize_iucv_client(self, userid, client=None): """Punch a script that used to set the authorized client userid in vm If the guest is in log off status, the change will take effect when the guest start up at first time. If the guest is in active status, power off and power on...
Write a Python 3 function that can punch a script that used to set the authorized client userid in vm
As a Python code translator, you convert algorithms and pseudocode into Python.
Deploy image and punch config driver to target
Can you tell what is the following Python 3 function doing def guest_deploy(self, userid, image_name, transportfiles=None, remotehost=None, vdev=None): """ Deploy image and punch config driver to target """ # (TODO: add the support of multiple disks deploy) msg = ('Start to ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Grant user to vswitch.
Can you tell what is the following Python 3 function doing def grant_user_to_vswitch(self, vswitch_name, userid): smt_userid = zvmutils.get_smt_userid() requestData = ' '.join(( 'SMAPI %s API Virtual_Network_Vswitch_Set_Extended' % smt_userid, "--operands", "-k switch...
As a python code expert, you are capable of creating scripts from specifications.
def image_performance_query(self, uid_list): """Call Image_Performance_Query to get guest current status. :uid_list: A list of zvm userids to be queried """ if uid_list == []: return {} if not isinstance(uid_list, list): uid_list = [uid_list] sm...
Can you implement a function in Python 3 that calls Image_Performance_Query to get guest current status.
You are a Python code architect, reviewing and designing scalable and efficient code
def system_image_performance_query(self, namelist): """Call System_Image_Performance_Query to get guest current status. :namelist: A namelist that defined in smapi namelist file. """ smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API System_Image_Pe...
Write a Python 3 function that can call System_Image_Performance_Query to get guest current status.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_vswitch(self, switch_name, **kwargs): """Set vswitch""" smt_userid = zvmutils.get_smt_userid() rd = ' '.join(( "SMAPI %s API Virtual_Network_Vswitch_Set_Extended" % smt_userid, "--operands", "-k switch_name=%s" % switch_name)) for ...
Implement a Python 3 function for setting the attributes of a virtual switch.
As a python code expert, you are capable of creating scripts from specifications.
def _couple_nic(self, userid, vdev, vswitch_name, active=False): """Couple NIC to vswitch by adding vswitch into user direct.""" if active: self._is_active(userid) msg = ('Start to couple nic device %(vdev)s of guest %(vm)s ' 'with vswitch %(vsw)s'...
Write a Python 3 script for coupling NIC to vswitch by adding vswitch into user direct.
You are a Python code architect, reviewing and designing scalable and efficient code
Couple nic to vswitch.
Can you tell what is the following Python 3 function doing def couple_nic_to_vswitch(self, userid, nic_vdev, vswitch_name, active=False): """Couple nic to vswitch.""" if active: msg = ("both in the user direct of guest %s and on " "the active ...
You are a Python code architect, reviewing and designing scalable and efficient code
Uncouple NIC from vswitch.
Here you have a function in Python 3, explain what it does def _uncouple_nic(self, userid, vdev, active=False): if active: self._is_active(userid) msg = ('Start to uncouple nic device %(vdev)s of guest %(vm)s' % {'vdev': vdev, 'vm': userid}) LOG.info(msg) req...
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute a command on a virtual machine.
Explain what the following Python 3 code does def execute_cmd(self, userid, cmdStr): requestData = 'cmdVM ' + userid + ' CMD \'' + cmdStr + '\'' with zvmutils.log_and_reraise_smt_request_failed(action='execute ' 'command on vm via iucv channel'): results = self._request(requestData) ...
As a Python code composer, you craft elegant and concise scripts.
def execute_cmd_direct(self, userid, cmdStr): """"cmdVM.""" requestData = 'cmdVM ' + userid + ' CMD \'' + cmdStr + '\'' results = self._smt.request(requestData) return results
How would you implement a function in Python 3 that executes a direct command on the virtual machine.
You are a Python code analyst, evaluating scripts for potential improvements.
def image_import(self, image_name, url, image_meta, remote_host=None): """Import the image specified in url to SDK image repository, and create a record in image db, the imported images are located in image_repository/prov_method/os_version/image_name/, for example, /opt/sdk/images/netbo...
Can you write a function in Python 3 where it imports the image specified in url to SDK image repository and create a record in image db
You are a Python code generator, capable of creating scripts from specifications.
Export the specific image to remote host or local file system
Make a summary of the following Python 3 code def image_export(self, image_name, dest_url, remote_host=None): image_info = self._ImageDbOperator.image_query_record(image_name) if not image_info: msg = ("The image %s does not exist in image repository" % image_name) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_image_size(self, image_path): """Return disk size in bytes""" command = 'du -b %s' % image_path (rc, output) = zvmutils.execute(command) if rc: msg = ("Error happened when executing command du -b with" "reason: %s" % output) LOG.error(m...
Can you implement a function in Python 3 that returns disk size in bytes
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_md5sum(self, fpath): """Calculate the md5sum of the specific image file""" try: current_md5 = hashlib.md5() if isinstance(fpath, six.string_types) and os.path.exists(fpath): with open(fpath, "rb") as fh: for chunk in self._read_chunks(...
Can you write a function in Python 3 where it calculates the md5sum of the specific image file
As a python code expert, you are capable of creating scripts from specifications.
def image_get_root_disk_size(self, image_name): """Return the root disk units of the specified image image_name: the unique image name in db Return the disk units in format like 3339:CYL or 467200:BLK """ image_info = self.image_query(image_name) if not image_info: ...
Implement a Python 3 function for getting the root disk size of the specified image
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_guest_connection_status(self, userid): '''Get guest vm connection status.''' rd = ' '.join(('getvm', userid, 'isreachable')) results = self._request(rd) if results['rs'] == 1: return True else: return False
Create a Python 3 function to get guest vm connection status.
You are a Python code analyst, evaluating scripts for potential improvements.
def process_additional_minidisks(self, userid, disk_info): '''Generate and punch the scripts used to process additional disk into target vm's reader. ''' for idx, disk in enumerate(disk_info): vdev = disk.get('vdev') or self.generate_disk_vdev( ...
Implement a function in Python 3 to generate and punch the scripts used to process additional disk into target vm s reader.
You are a Python code generator, capable of creating scripts from specifications.
Send smt request log and ignore any errors.
Can you generate a brief explanation for the following Python 3 code def _request_with_error_ignored(self, rd): try: return self._request(rd) except Exception as err: # log as warning and ignore namelist operation failures LOG.warning(six.text_type(err))
As a python code expert, you are capable of creating scripts from specifications.
This method imports an image from remote host to local image repository using scp.
Can you tell what is the following Python 3 function doing def image_import(cls, image_name, url, target, **kwargs): source = urlparse.urlparse(url).path if kwargs['remote_host']: if '@' in kwargs['remote_host']: source_path = ':'.join([kwargs['remote_host'], source]) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def image_export(cls, source_path, dest_url, **kwargs): """Export the specific image to remote host or local file system """ dest_path = urlparse.urlparse(dest_url).path if kwargs['remote_host']: target_path = ':'.join([kwargs['remote_host'], dest_path]) command = ' '.joi...
Write a Python 3 function that can export the specific image to remote host or local file system
You are a Python code analyst, evaluating scripts for potential improvements.
Dedent the docstring of a function and substitute with params
Explain what the following Python 3 code does def dedent(func): if isinstance(func, types.MethodType) and not six.PY3: func = func.im_func func.__doc__ = func.__doc__ and dedents(func.__doc__) return func
You are a Python code generator, capable of creating scripts from specifications.
Return an iterator that appends the docstring of the given parent to the applied function
Can you generate the documentation for the following Python 3 function def append_original_doc(parent, num=0): def func(func): func.__doc__ = func.__doc__ and func.__doc__ + indent( parent.__doc__, num) return func return func
As a Python code analyst, you investigate and solve complex coding mysteries
def get_sections(self, s, base, sections=[ 'Parameters', 'Other Parameters', 'Possible types']): """ Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by defa...
Write a Python 3 script to extract the specified sections out of the given string s.
You are a Python code generator, capable of creating scripts from specifications.
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address...
Implement a Python 3 function for generating config drive for zVM guest vm.
As a python code expert, you are capable of creating scripts from specifications.
Returns a key derived using the scrypt key - derivarion function
Explain what the following Python 3 code does def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64): check_args(password, salt, N, r, p, olen) # Set the memory required based on parameter values m = 128 * r * (N + p + 2) try: return _scrypt( password=password, sal...
You are a Python code analyst, evaluating scripts for potential improvements.
Set or update cache content.
Given the following Python 3 function, write the documentation def set(self, ctype, key, data): with zvmutils.acquire_lock(self._lock): target_cache = self._get_ctype_cache(ctype) target_cache['data'][key] = data
You are a Python code generator, capable of creating scripts from specifications.
def GoodResponse(body, request, status_code=None, headers=None): """ Construct a Good HTTP response (defined in DEFAULT_GOOD_RESPONSE_CODE) :param body: The body of the response :type body: ``str`` :param request: The HTTP request :type request: :...
Implement a function in Python 3 to construct a Good HTTP response object.
As a Python code composer, you craft elegant and concise scripts.
Construct a Bad HTTP response object.
Can you generate a brief explanation for the following Python 3 code def BadResponse(body, request, status_code=None, headers=None): """ Construct a Bad HTTP response (defined in DEFAULT_BAD_RESPONSE_CODE) :param body: The body of the response :type body: ``str`` ...
As a Python code analyst, you investigate and solve complex coding mysteries
def disable_warnings(critical=False): """Function that disables all warnings and all critical warnings (if critical evaluates to True) related to the psyplot Module. Please note that you can also configure the warnings via the psyplot.warning logger (logging.getLogger(psyplot.warning)).""" warnings....
How would you code a function in Python 3 to function that disables all warnings related to the psyplot Module.
As a python code expert, you are capable of creating scripts from specifications.
def warn(message, category=PsyPlotWarning, logger=None): """wrapper around the warnings.warn function for non-critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, stacklevel=...
Can you implement a function in Python 3 that wraps around the warnings. warn function for critical warnings. warn
As a Python code translator, you convert algorithms and pseudocode into Python.
def critical(message, category=PsyPlotCritical, logger=None): """wrapper around the warnings.warn function for critical warnings. logger may be a logging.Logger instance""" if logger is not None: message = "[Critical warning by %s]\n%s" % (logger.name, message) warnings.warn(message, category, s...
Implement a Python 3 function for wrapping around the warnings. warn function for critical warnings. warn function for critical warnings. warn logger may be a logging. Logger instance
You are a Python code analyst, evaluating scripts for potential improvements.
def customwarn(message, category, filename, lineno, *args, **kwargs): """Use the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.""" if category is PsyPlotWarning: logger.warning(warnings.forma...
How would you implement a function in Python 3 that uses the psyplot.warning logger for categories being out of PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning function for all the others.
As a Python code translator, you convert algorithms and pseudocode into Python.
Find user s home directory if possible. Otherwise returns None.
Given the following Python 3 function, write the documentation def _get_home(): try: if six.PY2 and sys.platform == 'win32': path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding()) else: path = os.path.expanduser("~") except ImportError: # This happens...
As a Python code translator, you convert algorithms and pseudocode into Python.
Match the request against a file in the adapter directory
Make a summary of the following Python 3 code def match_url(self, request): parsed_url = urlparse(request.path_url) path_url = parsed_url.path query_params = parsed_url.query match = None for path in self.paths: for item in self.index: target_path = o...
As a Python code translator, you convert algorithms and pseudocode into Python.
Reindex the index of the paths in the database.
Make a summary of the following Python 3 code def _reindex(self): self.index = [] for path in self.paths: target_path = os.path.normpath(os.path.join(BASE_PATH, path)) for root, subdirs, files in os.walk(target_path): ...
You are a Python code generator, capable of creating scripts from specifications.
This function adds a 3390 disk to a virtual machine s directory entry.
Make a summary of the following Python 3 code def add3390(rh): rh.printSysLog("Enter changeVM.add3390") results, cyl = generalUtils.cvtToCyl(rh, rh.parms['diskSize']) if results['overallRC'] != 0: # message already sent. Only need to update the final results. rh.updateResults(results) ...
As a Python code composer, you craft elegant and concise scripts.
def add9336(rh): """ Adds a 9336 (FBA) disk to virtual machine's directory entry. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'ADD9336' userid - userid of the virtual machine parms['diskPool'] - Disk pool ...
Write a Python 3 function for adding a 9336 (FBA) disk to virtual machine's directory entry. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'ADD9336' userid - userid of the virtual machine parms['diskPool'] - Disk pool parms['diskSize'] - size of the disk in blocks or bytes. pa...
As a Python code analyst, you investigate and solve complex coding mysteries
Dedicate a virtual machine.
Can you tell what is the following Python 3 function doing def dedicate(rh): rh.printSysLog("Enter changeVM.dedicate") parms = [ "-T", rh.userid, "-v", rh.parms['vaddr'], "-r", rh.parms['raddr'], "-R", rh.parms['mode']] hideList = [] results = invokeSMCLI(rh, ...
As a python code expert, you are capable of creating scripts from specifications.
This function sends an Activation Modification Script to the virtual machine.
Explain what the following Python 3 code does def addAEMOD(rh): rh.printSysLog("Enter changeVM.addAEMOD") invokeScript = "invokeScript.sh" trunkFile = "aemod.doscript" fileClass = "X" tempDir = tempfile.mkdtemp() if os.path.isfile(rh.parms['aeScript']): # Get the short name of our activ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def addLOADDEV(rh): """ Sets the LOADDEV statement in the virtual machine's directory entry. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'ADDLOADDEV' userid - userid of the virtual machine parms['boot'] ...
Write a Python 3 script for setting the LOADDEV statement in the virtual machine's directory entry. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'ADDLOADDEV' userid - userid of the virtual machine parms['boot'] - Boot program number parms['addr'] - Logical block address of th...
As a Python code translator, you convert algorithms and pseudocode into Python.
Punch a file to a virtual reader of the specified virtual machine.
Can you tell what is the following Python 3 function doing def punchFile(rh): rh.printSysLog("Enter changeVM.punchFile") # Default spool class in "A" , if specified change to specified class spoolClass = "A" if 'class' in rh.parms: spoolClass = str(rh.parms['class']) punch2reader(rh, rh.u...
You are a Python code analyst, evaluating scripts for potential improvements.
Purges the reader belonging to the virtual machine and returns the virtual machine ID.
How would you explain what the following Python 3 function does def purgeRDR(rh): rh.printSysLog("Enter changeVM.purgeRDR") results = purgeReader(rh) rh.updateResults(results) rh.printSysLog("Exit changeVM.purgeRDR, rc: " + str(rh.results['overallRC'])) return rh.results['overallRC']
As a Python code composer, you craft elegant and concise scripts.
This function removes a disk from a virtual machine.
Can you generate a brief explanation for the following Python 3 code def removeDisk(rh): rh.printSysLog("Enter changeVM.removeDisk") results = {'overallRC': 0, 'rc': 0, 'rs': 0} # Is image logged on loggedOn = False results = isLoggedOn(rh, rh.userid) if results['overallRC'] == 0: if ...
You are a Python code analyst, evaluating scripts for potential improvements.
Prints out the help output related to the command synopsis
Explain what the following Python 3 code does def showInvLines(rh): if rh.subfunction != '': rh.printLn("N", "Usage:") rh.printLn("N", " python " + rh.cmdName + " ChangeVM <userid> add3390 <diskPool> <vAddr>") rh.printLn("N", " <diskSize3390> --mode " + ...
You are a Python code architect, reviewing and designing scalable and efficient code
Prints the output of the operands for the current virtual machine.
Can you generate a brief explanation for the following Python 3 code def showOperandLines(rh): if rh.function == 'HELP': rh.printLn("N", " For the ChangeVM function:") else: rh.printLn("N", "Sub-Functions(s):") rh.printLn("N", " add3390 - Add a 3390 (ECKD) disk " + ...
You are a Python code generator, capable of creating scripts from specifications.
def send_request(self, api_name, *api_args, **api_kwargs): """Refer to SDK API documentation. :param api_name: SDK API name :param *api_args: SDK API sequence parameters :param **api_kwargs: SDK API keyword parameters """ return self.conn.request(api_name, *...
Create a Python 3 function for sending a request to the SDK API.
You are a Python code architect, reviewing and designing scalable and efficient code
This function returns the list of disk pools known to the directory manager.
Can you tell what is the following Python 3 function doing def getDiskPoolNames(rh): rh.printSysLog("Enter getHost.getDiskPoolNames") parms = ["-q", "1", "-e", "3", "-T", "dummy"] results = invokeSMCLI(rh, "Image_Volume_Space_Query_DM", parms) if results['overallRC'] == 0: for line in results[...
You are a Python code analyst, evaluating scripts for potential improvements.
def getDiskPoolSpace(rh): """ Obtain disk pool space information for all or a specific disk pool. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'DISKPOOLSPACE' parms['poolName'] - Name of the disk pool. Opti...
Can you create a Python 3 function that obtains disk pool space information for all or a specific disk pool. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'DISKPOOLSPACE' parms['poolName'] - Name of the disk pool. Optional, if not present then information for all disk pools is ...
As a Python code analyst, you investigate and solve complex coding mysteries
def getFcpDevices(rh): """ Lists the FCP device channels that are active, free, or offline. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'FCPDEVICES' Output: Request Handle updated with the results. Return code - 0:...
Can you create a Python 3 function that lists the FCP device channels that are active, free, or offline. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'FCPDEVICES' Output: Request Handle updated with the results. Return code - 0: ok, non-zero: error
As a Python code analyst, you investigate and solve complex coding mysteries
This function returns general information about the host.
Can you tell what is the following Python 3 function doing def getGeneralInfo(rh): rh.printSysLog("Enter getHost.getGeneralInfo") # Get host using VMCP rh.results['overallRC'] = 0 cmd = ["sudo", "/sbin/vmcp", "query userid"] strCmd = ' '.join(cmd) rh.printSysLog("Invoking: " + strCmd) try:...
As a Python code composer, you craft elegant and concise scripts.
Parse the command line and return the result.
Here you have a function in Python 3, explain what it does def parseCmdline(rh): rh.printSysLog("Enter getHost.parseCmdline") rh.userid = '' if rh.totalParms >= 2: rh.subfunction = rh.request[1].upper() # Verify the subfunction is valid. if rh.subfunction not in subfuncHandler: #...
You are a Python code analyst, evaluating scripts for potential improvements.
def showInvLines(rh): """ Produce help output related to command synopsis Input: Request Handle """ if rh.subfunction != '': rh.printLn("N", "Usage:") rh.printLn("N", " python " + rh.cmdName + " GetHost " + "diskpoolnames") rh.printLn("N", " python " + rh.cmdName +...
How would you code a function in Python 3 to produce help output related to command synopsis
As a Python code composer, you craft elegant and concise scripts.
Prints the output related to operands.
How would you explain what the following Python 3 function does def showOperandLines(rh): if rh.function == 'HELP': rh.printLn("N", " For the GetHost function:") else: rh.printLn("N", "Sub-Functions(s):") rh.printLn("N", " diskpoolnames - " + "Returns the names of the director...
You are a Python code analyst, evaluating scripts for potential improvements.
def deleteMachine(rh): """ Delete a virtual machine from the user directory. Input: Request Handle with the following properties: function - 'DELETEVM' subfunction - 'DIRECTORY' userid - userid of the virtual machine to be deleted. Output: Request Ha...
How would you implement a function in Python 3 that deletes a virtual machine from the user directory. Input: Request Handle with the following properties: function - 'DELETEVM' subfunction - 'DIRECTORY' userid - userid of the virtual machine to be deleted. Output: Request Handle updated with the results. Return code -...
You are a Python code architect, reviewing and designing scalable and efficient code
Activate a virtual machine.
Explain what the following Python 3 code does def activate(rh): rh.printSysLog("Enter powerVM.activate, userid: " + rh.userid) parms = ["-T", rh.userid] smcliResults = invokeSMCLI(rh, "Image_Activate", parms) if smcliResults['overallRC'] == 0: pass elif (smcliResults['overallRC'] == 8 and ...
You are a Python code architect, reviewing and designing scalable and efficient code
def checkIsReachable(rh): """ Check if a virtual machine is reachable. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'ISREACHABLE' userid - userid of the virtual machine Output: Request Handle updated with th...
Can you write a function in Python 3 where it checks if a virtual machine is reachable. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'ISREACHABLE' userid - userid of the virtual machine Output: Request Handle updated with the results. overallRC - 0: determined the status, non-...
As a python code expert, you are capable of creating scripts from specifications.
def deactivate(rh): """ Deactivate a virtual machine. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'OFF' userid - userid of the virtual machine parms['maxQueries'] - Maximum number of queries to issue. ...
Write a Python 3 function for deactivating a virtual machine.
You are a Python code analyst, evaluating scripts for potential improvements.
def getStatus(rh): """ Get the power (logon/off) status of a virtual machine. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'STATUS' userid - userid of the virtual machine Output: Request Handle updated with ...
Implement a Python 3 function for returning the power status of a virtual machine.
You are a Python code architect, reviewing and designing scalable and efficient code
def parseCmdline(rh): """ Parse the request command input. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error """ rh.printSysLog("Enter powerVM.parseCmdline") if rh.totalParms >= 2: rh.userid = rh.requ...
Create a Python 3 function to parse the command line and return the handle of the current object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Pause a virtual machine.
Given the following Python 3 function, write the documentation def pause(rh): rh.printSysLog("Enter powerVM.pause, userid: " + rh.userid) parms = ["-T", rh.userid, "-k", "PAUSE=YES"] results = invokeSMCLI(rh, "Image_Pause", parms) if results['overallRC'] != 0: # SMAPI API failed. rh.pr...
As a Python code analyst, you investigate and solve complex coding mysteries
def reset(rh): """ Reset a virtual machine. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'RESET' userid - userid of the virtual machine parms['maxQueries'] - Maximum number of queries to issue. ...
Can you write a function in Python 3 where it resets a virtual machine. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'RESET' userid - userid of the virtual machine parms['maxQueries'] - Maximum number of queries to issue. Optional. parms['maxWait'] - Maximum time to wait in se...
As a Python code composer, you craft elegant and concise scripts.
def softDeactivate(rh): """ Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parm...
Write a Python 3 script for deactivating a virtual machine by first shutting down Linux and then log off the system.
You are a Python code analyst, evaluating scripts for potential improvements.
This function waits for the virtual machine to go into the specified state.
How would you explain what the following Python 3 function does def wait(rh): rh.printSysLog("Enter powerVM.wait, userid: " + rh.userid) if (rh.parms['desiredState'] == 'off' or rh.parms['desiredState'] == 'on'): results = waitForVMState( rh, rh.userid, rh.p...
You are a Python code analyst, evaluating scripts for potential improvements.
def call(self, func, *api_args, **api_kwargs): """Send API call to SDK server and return results""" if not isinstance(func, str) or (func == ''): msg = ('Invalid input for API name, should be a' 'string, type: %s specified.') % type(func) return self._construct...
Write a Python 3 function for sending API call to the SDK server and return results
As a python code expert, you are capable of creating scripts from specifications.
send results to a specific client
Explain what the following Python 3 code does def send_results(self, client, addr, results): json_results = json.dumps(results) json_results = json_results.encode() sent = 0 total_len = len(json_results) got_error = False while (sent < total_len): this_sent =...
You are a Python code analyst, evaluating scripts for potential improvements.
def serve_API(self, client, addr): """ Read client request and call target SDK API""" self.log_debug("(%s:%s) Handling new request from client." % (addr[0], addr[1])) results = None try: data = client.recv(4096) data = bytes.decode(data) ...
Implement a function in Python 3 to read client request and call target SDK API function and return result.
As a Python code translator, you convert algorithms and pseudocode into Python.
def dispatch(environ, start_response, mapper): """Find a matching route for the current request. :raises: 404(not found) if no match request 405(method not allowed) if route exist but method not provided. """ result = mapper.match(environ=environ) if result is None: ...
Can you implement a function in Python 3 that dispatches the request to the next handler.
You are a Python code generator, capable of creating scripts from specifications.
def handle_not_allowed(environ, start_response): """Return a 405 response when method is not allowed. If _methods are in routing_args, send an allow header listing the methods that are possible on the provided URL. """ _methods = util.wsgi_path_item(environ, '_methods') headers = {} if _met...
How would you code a function in Python 3 to return a 405 response when the method is not allowed.
You are a Python code analyst, evaluating scripts for potential improvements.
Process route declarations to create a Route Mapper.
Can you generate a brief explanation for the following Python 3 code def make_map(declarations): mapper = routes.Mapper() for route, methods in ROUTE_LIST: allowed_methods = [] for method, func in methods.items(): mapper.connect(route, action=func, conditio...
As a Python code composer, you craft elegant and concise scripts.
def _delete_zfcp_config_records(self, fcp, target_wwpn, target_lun): """rhel""" device = '0.0.%s' % fcp data = {'wwpn': target_wwpn, 'lun': target_lun, 'device': device, 'zfcpConf': '/etc/zfcp.conf'} delete_records_cmd = ('sed -i -e ' '\"/%(d...
Write a Python 3 script for deleting the records from the config file for the given fcp.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_source_device_path(self, fcp, target_wwpn, target_lun): """rhel""" device = '0.0.%s' % fcp data = {'device': device, 'wwpn': target_wwpn, 'lun': target_lun} var_source_device = ('SourceDevice="/dev/disk/by-path/ccw-%(device)s-' 'zfcp-%(wwpn)s:%(lun)s...
Create a Python 3 function to get the source device path for a given fcp and target WWPN and LUN.
As a Python code composer, you craft elegant and concise scripts.
rhel7 set WWPN and LUN in sysfs
Given the following Python 3 function, write the documentation def _set_sysfs(self, fcp, target_wwpn, target_lun): device = '0.0.%s' % fcp unit_add = "echo '%s' > " % target_lun unit_add += "/sys/bus/ccw/drivers/zfcp/%(device)s/%(wwpn)s/unit_add\n"\ % {'device': device, 'wwpn...
As a Python code analyst, you investigate and solve complex coding mysteries
construct udev rules info.
Explain what the following Python 3 code does def _get_udev_rules(self, channel_read, channel_write, channel_data): sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { 'read': channel_read, 'read': channel_read, ...
As a Python code composer, you craft elegant and concise scripts.
handle udev rules file.
Given the following Python 3 function, write the documentation def _delete_vdev_info(self, vdev): vdev = vdev.lower() rules_file_name = '/etc/udev/rules.d/51-qeth-0.0.%s.rules' % vdev cmd = 'rm -f %s\n' % rules_file_name address = '0.0.%s' % str(vdev).zfill(4) udev_file_name = '...
As a Python code analyst, you investigate and solve complex coding mysteries
sles set WWPN and LUN in configuration files
Here you have a function in Python 3, explain what it does def _set_zfcp_config_files(self, fcp, target_wwpn, target_lun): device = '0.0.%s' % fcp # host config host_config = '/sbin/zfcp_host_configure %s 1' % device # disk config disk_config = '/sbin/zfcp_disk_configure ' +\ ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _set_zfcp_multipath(self): """sles""" # modprobe DM multipath kernel module modprobe = 'modprobe dm_multipath' conf_file = '#blacklist {\n' conf_file += '#\tdevnode \\"*\\"\n' conf_file += '#}\n' conf_cmd = 'echo -e "%s" > /etc/multipath.conf' % conf_file ...
Can you create a Python 3 function that sets multipath kernel module
As a python code expert, you are capable of creating scripts from specifications.
Generate the configuration files for the guest VM.
Given the following Python 3 function, write the documentation def create_network_configuration_files(self, file_path, guest_networks, first, active=False): """Generate network configuration files for guest vm :param list guest_networks: a list of network info...
As a python code expert, you are capable of creating scripts from specifications.
handle vdev related info.
Given the following Python 3 function, write the documentation def _delete_vdev_info(self, vdev): vdev = vdev.lower() network_config_file_name = self._get_network_file() device = self._get_device_name(vdev) cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_dist(self, os_version): """Separate os and version from os_version. Possible return value are only: ('rhel', x.y) and ('sles', x.y) where x.y may not be digits """ supported = {'rhel': ['rhel', 'redhat', 'red hat'], 'sles': ['suse', 'sles'], ...
Can you write a function in Python 3 where it separates os and version from os_version.
You are a Python code generator, capable of creating scripts from specifications.
def getStatus(rh): """ Get status of a VMRelocate request. Input: Request Handle with the following properties: function - 'MIGRATEVM' subfunction - 'STATUS' userid - userid of the virtual machine parms['all'] - If present, set status_target to A...
Create a Python 3 function to get status of a VMRelocate request. Input: Request Handle with the following properties: function - 'MIGRATEVM' subfunction - 'STATUS' userid - userid of the virtual machine parms['all'] - If present, set status_target to ALL. parms['incoming'] - If present, set status_target to INCOMING. ...
As a Python code analyst, you investigate and solve complex coding mysteries
This function is called by the function handler to route to the appropriate subfunction.
How would you explain what the following Python 3 function does def driveFunction(self): if self.function == 'HELP': # General help for all functions. self.printLn("N", "") self.printLn("N", "Usage:") self.printLn("N", " python " + self.cmdName + " --help") ...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse the command string and return the parsed information.
Here you have a function in Python 3, explain what it does def parseCmdline(self, requestData): self.printSysLog("Enter ReqHandle.parseCmdline") # Save the request data based on the type of operand. if isinstance(requestData, list): self.requestString = ' '.join(requestData) # Req...
You are a Python code analyst, evaluating scripts for potential improvements.
def printLn(self, respType, respString): """ Add one or lines of output to the response list. Input: Response type: One or more characters indicate type of response. E - Error message N - Normal message S - Output should be logged ...
Implement a Python 3 function for printing a line of output to the log.
You are a Python code architect, reviewing and designing scalable and efficient code
Print a log string to the logEntries list.
Can you generate a brief explanation for the following Python 3 code def printSysLog(self, logString): if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG: # print log only when debug is enabled if self.daemon == '': self.logger.debug(self.requestId + ": " + logString) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def updateResults(self, newResults, **kwArgs): """ Update the results related to this request excluding the 'response' and 'logEntries' values. We specifically update (if present): overallRC, rc, rs, errno. Input: Dictionary containing the results to be upd...
How would you code a function in Python 3 to update the results related to this request with the provided dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
Adds a query filter to be applied to the next API list call for this resource.
Given the following Python 3 function, write the documentation def filter(self, field, operator, value): instance = copy(self) i = len(instance._filters) instance._filters.append({ 'filter[field][%d]' % i: str(field), 'filter[operator][%d]' % i: str(operator), ...
As a Python code composer, you craft elegant and concise scripts.
def resultsperpage(self, value): """ Set the number of results that will be retrieved by the request. :param value: 'resultsperpage' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object ...
Can you write a function in Python 3 where it sets the number of results that will be retrieved by the request.
As a Python code composer, you craft elegant and concise scripts.
def page(self, value): """ Set the page which will be returned. :param value: 'page' parameter value for the rest api call :type value: str Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object """ instance = copy(self) ins...
Write a Python 3 function for setting the page which will be returned.
You are a Python code generator, capable of creating scripts from specifications.
Returns a merged dictionary of filters.
Make a summary of the following Python 3 code def filters(self): params = {} for _filter in self._filters: params.update(_filter) return params
As a Python code analyst, you investigate and solve complex coding mysteries
A json_formatter for webob exceptions.
Given the following Python 3 function, write the documentation def json_error_formatter(body, status, title, environ): body = webob.exc.strip_tags(body) status_code = int(status.split(None, 1)[0]) error_dict = { 'status': status_code, 'title': title, 'detail': body } return {...
You are a Python code generator, capable of creating scripts from specifications.
Add json_error_formatter to any webob HTTPExceptions.
How would you explain what the following Python 3 function does def call_func(self, req, *args, **kwargs): try: return super(SdkWsgify, self).call_func(req, *args, **kwargs) except webob.exc.HTTPException as exc: msg = ('encounter %(error)s error') % {'error': exc} LO...
As a Python code composer, you craft elegant and concise scripts.
Calculate latitude and longitude variable calculated from the gdal. Open. GetGeoTransform method
Given the following Python 3 function, write the documentation def _load_GeoTransform(self): def load_lon(): return arange(ds.RasterXSize)*b[1]+b[0] def load_lat(): return arange(ds.RasterYSize)*b[5]+b[3] ds = self.ds b = self.ds.GetGeoTransform() # bbox, interv...
As a python code expert, you are capable of creating scripts from specifications.
Returns the path to the psyplot configuration file.
Can you generate the documentation for the following Python 3 function def psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml', if_exists=True): """ Get the location of the config file. The file location is determined in the following order - `$PWD/psyplotrc.yml` - environm...
You are a Python code architect, reviewing and designing scalable and efficient code
Validate that s is a path and return s else False
Can you generate a brief explanation for the following Python 3 code def validate_path_exists(s): if s is None: return None if os.path.exists(s): return s else: raise ValueError('"%s" should be a path but it does not exist' % s)
As a Python code analyst, you investigate and solve complex coding mysteries
Validate a dictionary of a node.
How would you explain what the following Python 3 function does def validate_dict(d): try: return dict(d) except TypeError: d = validate_path_exists(d) try: with open(d) as f: return dict(yaml.load(f)) except Exception: raise ValueError("Co...
As a Python code analyst, you investigate and solve complex coding mysteries