Instruction:
Implement a Python 3 function for
returning the FirmwareImageExtractor object fine - tuned for the specified type of compact firmware file.

Response:
def get_fw_extractor(fw_file):
    """Gets the firmware extractor object fine-tuned for specified type

    :param fw_file: compact firmware file to be extracted from
    :raises: InvalidInputError, for unsupported file types
    :returns: FirmwareImageExtractor object
    """
    fw_img_extractor = FirmwareImageExtractor(fw_file)
    extension = fw_img_extractor.fw_file_ext.lower()

    if extension == '.scexe':
        # assign _do_extract attribute to refer to _extract_scexe_file
        fw_img_extractor._do_extract = types.MethodType(
            _extract_scexe_file, fw_img_extractor)
    elif extension == '.rpm':
        # assign _do_extract attribute to refer to _extract_rpm_file
        fw_img_extractor._do_extract = types.MethodType(
            _extract_rpm_file, fw_img_extractor)
    elif extension in RAW_FIRMWARE_EXTNS:
        # Note(deray): Assigning ``extract`` attribute to return
        #     1. the firmware file itself
        #     2. boolean (False) to indicate firmware file is not extracted
        def dummy_extract(self):
            """Dummy (no-op) extract method

            :returns: the same firmware file with the complete path
            :returns: boolean(False) to indicate that a new file is not
                      generated.
            """
            return fw_img_extractor.fw_file, False

        fw_img_extractor.extract = types.MethodType(
            dummy_extract, fw_img_extractor)
    else:
        raise exception.InvalidInputError(
            'Unexpected compact firmware file type: %s' % fw_file)

    return fw_img_extractor


Instruction:
Can you generate the documentation for the following Python 3 function
def _extract_scexe_file(self, target_file, extract_path):
    # Command to extract the smart component file.
    unpack_cmd = '--unpack=' + extract_path
    # os.path.isfile(target_file)
    cmd = [target_file, unpack_cmd]
    out, err = utils.trycmd(*cmd)

Response: Extracts the scexe file from the target file.


Instruction:
Make a summary of the following Python 3 code
def _extract_rpm_file(self, target_file, extract_path):
    if not os.path.exists(extract_path):
        os.makedirs(extract_path)
    os.chdir(extract_path)

    if find_executable('rpm2cpio') is None:
        raise exception.ImageExtractionFailed(
            image_ref=target_file, reason='Command `rpm2cpio` not found.')
    if find_executable('cpio') is None:
        raise exception.ImageExtractionFailed(
            image_ref=target_file, reason='Command `cpio` not found.')
    try:
        rpm2cpio = subprocess.Popen('rpm2cpio ' + target_file,
                                    shell=True,
                                    stdout=subprocess.PIPE)
        cpio = subprocess.Popen('cpio -idm', shell=True,
                                stdin=rpm2cpio.stdout)
        out, err = cpio.communicate()
    except (OSError, ValueError) as e:
        raise exception.ImageExtractionFailed(
            image_ref=target_file,
            reason='Unexpected error in extracting file. ' + str(e))

Response: Extracts the rpm file from the specified path.


Instruction:
Make a summary of the following Python 3 code
def _get_firmware_file(path):
    for dirpath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            file_name, file_ext = os.path.splitext(os.path.basename(filename))
            if file_ext in RAW_FIRMWARE_EXTNS:
                # return filename
                return os.path.join(dirpath, filename)

Response: Gets the raw firmware file from the extracted directory structure


Instruction:
Write a Python 3 function that can
get the raw firmware file from the extracted directory structure creates a hard link to that file and cleans up the lookup extract path.

Response:
def _get_firmware_file_in_new_path(searching_path):
    """Gets the raw firmware file in a new path

    Gets the raw firmware file from the extracted directory structure
    and creates a hard link to that in a file path and cleans up the
    lookup extract path.
    :param searching_path: the directory structure to search for
    :returns: the raw firmware file with the complete new path
    """
    firmware_file_path = _get_firmware_file(searching_path)
    if not firmware_file_path:
        return None

    # Note(deray): the path of the new firmware file will be of the form:
    #
    #    [TEMP_DIR]/xxx-xxx_actual_firmware_filename
    #
    # e.g. /tmp/77e8f689-f32c-4727-9fc3-a7dacefe67e4_ilo4_210.bin
    file_name, file_ext_with_dot = common.get_filename_and_extension_of(
        firmware_file_path)
    new_firmware_file_path = os.path.join(
        tempfile.gettempdir(), str(uuid.uuid4()) + '_' +
        file_name + file_ext_with_dot)

    # create a hard link to the raw firmware file
    os.link(firmware_file_path, new_firmware_file_path)
    return new_firmware_file_path


Instruction:
How would you explain what the following Python 3 function does
def upload_file_to(self, addressinfo, timeout):
        self.hostname, self.port = addressinfo
        self.timeout = timeout
        filename = self.fw_file

        firmware = open(filename, 'rb').read()
        # generate boundary
        boundary = b('------hpiLO3t' +
                     str(random.randint(100000, 1000000)) + 'z')

        while boundary in firmware:
            boundary = b('------hpiLO3t' +
                         str(random.randint(100000, 1000000)) + 'z')
        # generate body parts
        parts = [
            # body1
            b("--") + boundary +
            b("""\r\nContent-Disposition: form-data; """
              """name="fileType"\r\n\r\n"""),
            # body2
            b("\r\n--") + boundary +
            b('''\r\nContent-Disposition: form-data; name="fwimgfile"; '''
              '''filename="''') +
            b(filename) +
            b('''"\r\nContent-Type: application/octet-stream\r\n\r\n'''),
            # firmware image
            firmware,
            # body3
            b("\r\n--") + boundary + b("--\r\n"),
        ]
        total_bytes = sum([len(x) for x in parts])
        sock = self._get_socket()

        # send the firmware image
        sock.write(b(self.HTTP_UPLOAD_HEADER %
                     (total_bytes, boundary.decode('ascii'))))
        for part in parts:
            sock.write(part)

        data = ''
        try:
            while True:
                d = sock.read()
                data += d.decode('latin-1')
                if not d:
                    break
        except socket.sslerror:  # Connection closed
            e = sys.exc_info()[1]
            if not data:
                raise exception.IloConnectionError(
                    "Communication with %(hostname)s:%(port)d failed: "
                    "%(error)s" % {'hostname': self.hostname,
                                   'port': self.port, 'error': str(e)})

        # Received len(data) bytes
        cookie_match = re.search('Set-Cookie: *(.*)', data)
        if not cookie_match:
            raise exception.IloError("Uploading of file: %s failed due "
                                     "to unknown reason." % filename)
        # return the cookie
        return cookie_match.group(1)

Response: Uploads the raw firmware file to iLO and returns the cookie so sent back to iLO.


Instruction:
Make a summary of the following Python 3 code
def _get_socket(self, sslversion=ssl.PROTOCOL_TLSv1):
        err = None
        sock = None
        try:
            for res in socket.getaddrinfo(
                    self.hostname, self.port, 0, socket.SOCK_STREAM):
                af, socktype, proto, canonname, sa = res
                try:
                    sock = socket.socket(af, socktype, proto)
                    sock.settimeout(self.timeout)
                    # Connecting to {self.hostname} at port {self.port}
                    sock.connect(sa)
                except socket.timeout:
                    if sock is not None:
                        sock.close()
                    err = exception.IloConnectionError(
                        "Timeout connecting to %(hostname)s:%(port)d"
                        % {'hostname': self.hostname, 'port': self.port})
                except socket.error:
                    if sock is not None:
                        sock.close()
                    e = sys.exc_info()[1]
                    err = exception.IloConnectionError(
                        "Error connecting to %(hostname)s:%(port)d : %(error)s"
                        % {'hostname': self.hostname, 'port': self.port,
                           'error': str(e)})
        except Exception:
            raise exception.IloConnectionError(
                "Unable to resolve %s" % self.hostname)

        if err is not None:
            raise err

        # wrapping the socket over ssl session
        try:
            return ssl.wrap_socket(sock, ssl_version=sslversion)
        except socket.sslerror:
            e = sys.exc_info()[1]
            msg = (getattr(e, 'reason', None) or
                   getattr(e, 'message', None))
            # Some older iLO s don't support TLSv1, retry with SSLv3
            if ('wrong version number' in msg) and (
                    sslversion == ssl.PROTOCOL_TLSv1):

                return self._get_socket(ssl.PROTOCOL_SSLv3)

            raise exception.IloConnectionError(
                "Cannot establish ssl session with %(hostname)s:%(port)d : "
                "%(error)s" % {'hostname': self.hostname, 'port': self.port,
                               'error': str(e)})

Response: Returns a ssl wrapped socket object for the current connection and SSLv1 protocol version.


Instruction:
Create a Python 3 function to
extract the raw firmware file from its compact format and returns the full path to the raw firmware file.

Response:
def extract(self):
        """Extracts the raw firmware file from its compact format

        Extracts the raw firmware file from its compact file format (already
        set as attribute in FirmwareImageControllerBase constructor).
        :raises: InvalidInputError, if raw firmware file not found
        :raises: ImageExtractionFailed, for extraction related issues
        :returns: the raw firmware file with the complete path
        :returns: boolean(True) to indicate that a new file got generated
                  after successful extraction.
        """
        target_file = self.fw_file
        common.add_exec_permission_to(target_file)
        # create a temp directory where the extraction will occur
        temp_dir = tempfile.mkdtemp()
        extract_path = os.path.join(temp_dir, self.fw_filename)

        try:
            self._do_extract(target_file, extract_path)
        except exception.ImageExtractionFailed:
            # clean up the partial extracted content, if any,
            # along with temp dir and re-raise the exception
            shutil.rmtree(temp_dir, ignore_errors=True)
            raise

        # creating a new hard link to the core firmware file
        firmware_file_path = _get_firmware_file_in_new_path(extract_path)
        # delete the entire extracted content along with temp dir.
        shutil.rmtree(temp_dir, ignore_errors=True)

        if not firmware_file_path:
            raise exception.InvalidInputError(
                "Raw firmware file not found in: '%s'" % target_file)

        return firmware_file_path, True


Instruction:
Can you implement a function in Python 3 that
converts redfish data of current raid config to generic format.

Response:
def _generic_format(self, raid_config, controller=None):
        """Convert redfish data of current raid config to generic format.

        :param raid_config: Raid configuration dictionary
        :param controller: Array controller model in post_create read else
                           None
        :returns: current raid config.
        """
        logical_drives = raid_config["LogicalDrives"]
        logical_disks = []
        controller = controller
        for ld in logical_drives:
            prop = {'size_gb': ld['CapacityGiB'],
                    'raid_level': ld['Raid'].strip('Raid'),
                    'root_device_hint': {
                        'wwn': '0x' + ld['VolumeUniqueIdentifier']},
                    'controller': controller,
                    'physical_disks': ld['DataDrives'],
                    'volume_name': ld['LogicalDriveName']}
            logical_disks.append(prop)
        return logical_disks


Instruction:
Implement a function in Python 3 to
check for smart storage message.

Response:
def _check_smart_storage_message(self):
        """Check for smart storage message.

        :returns: result, raid_message
        """
        ssc_mesg = self.smart_storage_config_message
        result = True
        raid_message = ""
        for element in ssc_mesg:
            if "Success" not in element['MessageId']:
                result = False
                raid_message = element['MessageId']
        return result, raid_message


Instruction:
Can you generate a brief explanation for the following Python 3 code
def read_raid(self, controller=None):
        if controller:
            if not self.logical_drives:
                msg = ('No logical drives found on the controller')
                LOG.debug(msg)
                raise exception.IloLogicalDriveNotFoundError(msg)
            raid_op = 'create_raid'
        else:
            raid_op = 'delete_raid'

        result, raid_message = self._check_smart_storage_message()

        if result:
            configured_raid_settings = self._conn.get(self.settings_uri)
            raid_data = {
                'logical_disks': self._generic_format(
                    configured_raid_settings.json(), controller=controller)}
            return raid_data
        else:
            if self.physical_drives is None or not raid_message:
                # This controller is not configured or controller
                # not used in raid operation
                return
            else:
                msg = ('Failed to perform the %(opr)s operation '
                       'successfully. Error - %(error)s'
                       % {'opr': raid_op, 'error': str(raid_message)})
                raise exception.IloError(msg)

Response: Get the current RAID configuration from the system.


Instruction:
Here you have a function in Python 3, explain what it does
def delete_raid(self):
        if not self.logical_drives:
            msg = ('No logical drives found on the controller '
                   '%(controller)s' % {'controller': str(self.controller_id)})
            LOG.debug(msg)
            raise exception.IloLogicalDriveNotFoundError(msg)

        lds = [{
               'Actions': [{"Action": "LogicalDriveDelete"}],
               'VolumeUniqueIdentifier':
               logical_drive.volume_unique_identifier}
               for logical_drive in self.logical_drives]

        data = {'LogicalDrives': lds, 'DataGuard': 'Permissive'}
        self._conn.put(self.settings_uri, data=data)

Response: Clears the RAID configuration from the system.


Instruction:
Can you create a Python 3 function that
creates the raid configuration on the hardware.

Response:
def create_raid(self, raid_config):
        """Create the raid configuration on the hardware.

        :param raid_config: A dictionary containing target raid configuration
                            data. This data stucture should be as follows:
                            raid_config = {'logical_disks': [{'raid_level': 1,
                            'size_gb': 100, 'physical_disks': ['6I:1:5'],
                            'controller': 'HPE Smart Array P408i-a SR Gen10'},
                            <info-for-logical-disk-2>]}
        """
        manager.validate(raid_config)
        logical_drives = raid_config['logical_disks']
        redfish_logical_disk = []
        for ld in logical_drives:
            ld_attr = {"Raid": "Raid" + ld["raid_level"]}
            ld_attr[
                "CapacityGiB"] = -1 if ld[
                    "size_gb"] == "MAX" else int(ld["size_gb"])
            if 'physical_disks' in ld:
                ld_attr["DataDrives"] = ld["physical_disks"]
            else:
                datadrives = {}
                if 'number_of_physical_disks' in ld:
                    datadrives["DataDriveCount"] = (
                        ld["number_of_physical_disks"])
                else:
                    datadrives["DataDriveCount"] = (constants.
                                                    RAID_LEVEL_MIN_DISKS
                                                    [ld["raid_level"]])
                if 'disk_type' in ld:
                    datadrives["DataDriveMediaType"] = ld["disk_type"]
                if 'interface_type' in ld:
                    datadrives["DataDriveInterfaceType"] = ld["interface_type"]
                ld_attr["DataDrives"] = datadrives
            if 'volume_name' in ld:
                ld_attr["LogicalDriveName"] = ld["volume_name"]
            redfish_logical_disk.append(ld_attr)

        data = {
            "DataGuard": "Disabled",
            "LogicalDrives": redfish_logical_disk
        }
        self._conn.put(self.settings_uri, data=data)


Instruction:
Can you tell what is the following Python 3 function doing
def _readFile(self, fname, sldir):
        '''
        Private method that reads in the data file and organizes it
        within this object.

        '''
        if sldir.endswith('/'):
            fname = str(sldir)+str(fname)
        else:
            fname = str(sldir)+'/'+str(fname)
        f=open(fname,'r')

        # read header line
        line=f.readline()
        cols  = []
        ispec = 0
        for i in range(1,len(line.split('|'))):
            col = line.split('|')[i].strip()
            if '-' in col:
                ispec += 1
                col   = col.split('-')[1]
            cols.append(col)
            col_num={}
        col_tot = len(cols)

        print('number of species: ', str(ispec))
        print('number of cols: ', str(col_tot))

        col_num={}
        for a,b in zip(cols,list(range(col_tot))):
            col_num[a]=b

        # read remainder of the file
        lines=f.readlines()
        data=[]
        for i in range(len(lines)):
            v=lines[i].split()
            vv=array(v,dtype='float')
            data.append(vv)
        ilines=i
        print("There are "+str(ilines)+" time steps found.")
        return data,col_num,cols,col_tot,ilines

Response: Private method that reads in the data file and organizes it into a list of tuples.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(self, col_str):
        '''
        get one data column with the data

        Parameters
        ----------
        col_str : string
            One of the column strings in self.cols.

        '''
        data_column=zeros(self.ilines)
        for i in range(self.ilines):
            data_column[i]=self.data[i][self.col_num[col_str]]
        return data_column

Response: get one data column with the data


Instruction:
Given the following Python 3 function, write the documentation
def plot_xtime(self, y, x='time', label='default', labelx=None,
                   labely=None ,title=None, shape='.', logx=False,
                   logy=True, base=10):
        '''
        make a simple plot of two columns against each other.

        An example would be instance.plot_xtime('PB206', label='PB206 vs t_y'
        Recomend using the plot function DataPlot.plot() it has more
        functionality.

        Parameters
        ----------
        Y : string
            Column on Y-axis.
        X : string, optional
            Column on X-axis.  The default is "time".
        label : string, optional
            Legend label.  The default is "default".
        labelX : string, optional
            The label on the X axis.  The default is None.
        labelY : string, optional
            The label on the Y axis.  The default is None.
        title : string, optional
            The Title of the Graph.  The default is None.
        shape : string, optional
            What shape and colour the user would like their plot in.
            The default is '.'.
        logX : boolean, optional
            A boolean of weather the user wants the x axis
            logarithmically.  The default is False.
        logY : boolean, optional
            A boolean of weather the user wants the Y axis
            logarithmically.  The default is True.
        base : integer, optional
            The base of the logarithm.  The default is 10.

        Notes
        -----
        For all possable choices visit,
        <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot>

        '''
        if label is 'default':
            lab_str=y
        else:
            lab_str=label

        try:
            self.get(x)
        except KeyError:
            x='age'

        DataPlot.plot(self,x,y,legend=lab_str,labelx=labelx, labely=labely,
                      title=title, shape=shape,logx=logx, logy=logy, base=base)
        '''
        print X,Y
        xdat=self.get(X)
        ydat=self.get(Y)
        self.xdat = xdat
        self.ydat = ydat

        plot(xdat,log10(ydat),label=lab_str)
        legend()
        '''

Response: This function will plot two columns against each other.


Instruction:
How would you explain what the following Python 3 function does
def getColData(self, attri, fname, numtype='cycNum'):
        fname=self.findFile(fname,numtype)
        f=open(fname,'r')
        for i in range(self.index+1):
            f.readline()
        lines=f.readlines()
        for i in range(len(lines)):
            lines[i]=lines[i].strip()
            lines[i]=lines[i].split()
        index=0
        data=[]

        while index < len (self.dcols):
            if attri== self.dcols[index]:
                break
            index+=1

        for i in range(len(lines)):

            if index==5 and len(lines[i])==7:
                data.append(str(lines[i][index].capitalize())+'-'\
                +str(lines[i][index+1]))
            elif index==5 and len(lines[i])!=7:
                tmp=str(lines[i][index])
                if tmp[len(tmp)-1].isdigit():
                    tmp1=tmp[0]+tmp[1]
                    tmp1=tmp1.capitalize()
                    tmp2=''
                    for j in range(len(tmp)):
                        if j == 0 or j == 1:
                            continue
                        tmp2+=tmp[j]
                    data.append(tmp1+'-'+tmp2)
                elif tmp=='PROT':
                    data.append('H-1')
                elif tmp==('NEUT'or'NEUTR'or'nn'or'N   1'or'N-1'):
                    data.append('N-1')
                else:
                    data.append(tmp)
            elif index==0:
                data.append(int(lines[i][index]))
            else:
                data.append(float(lines[i][index]))

        return array(data)

Response: This method returns the column of data for the associated column.


Instruction:
Explain what the following Python 3 code does
def getElement(self, attri, fname, numtype='cycNum'):
        '''
        In this method instead of getting a particular column of data,
        the program gets a particular row of data for a particular
        element name.

        attri : string
            The name of the attribute we are looking for. A complete
            list of them can be obtained by calling

            >>> get('element_name')
        fname : string
            The name of the file we are getting the data from or the
            cycle number found in the filename.
        numtype : string, optional
            Determines whether fname is the name of a file or, the
            cycle number.  If it is 'file' it will then  interpret it as
            a file, if it is 'cycNum' it will then  interpret it as a
            cycle number.  The default is "cycNum".

        Returns
        -------
        array
            A numpy array of the four element attributes, number, Z, A
            and abundance, in that order.

        Notes
        -----
        Warning
        '''
        element=[] #Variable for holding the list of element names
        number=[]  #Variable for holding the array of numbers
        z=[]       #Variable for holding the array of z
        a=[]       #Variable for holding the array of a
        abd=[]     #Variable for holding the array of Abundance
        data=[]    #variable for the final list of data

        fname=self.findFile(fname,numtype)
        f=open(fname,'r')
        for i in range(self.index+1):
            f.readline()
        lines=f.readlines()
        for i in range(len(lines)):
            lines[i]=lines[i].strip()
            lines[i]=lines[i].split()
        index=0
        data=[]

        while index < len (self.dcols):
            if attri== self.dcols[index]:
                break
            index+=1

        element=self.get(self.dcols[5],fname,numtype)
        number=[]
        z=[]
        a=[]
        isom=[]
        abd=[]
        for i in range(len(lines)):
            number.append(int(lines[i][0]))
            z.append(float(lines[i][1]))
            isom.append(float(lines[i][2]))
            abd.append(float(lines[i][1]))
        index=0 #Variable for determing the index in the data columns

        while index < len(element):
            if attri == element[index]:
                break

            index+=1

        data.append(number[index])
        data.append(z[index])
        data.append(a[index])
        data.append(isom[index])
        data.append(abd[index])

        return array(data)

Response: This method gets the element name of a particular attribute from a file. This method will return a list of the four element attributes number Z and Arac.


Instruction:
Here you have a function in Python 3, explain what it does
def _getcycle(self, cycle, decayed=False):
        ''' Private method for getting a cycle, called from get.'''
        yps=self.get('ABUNDANCE_MF', cycle)
        z=self.get('Z', cycle) #charge
        a=self.get('A', cycle) #mass
        isomers=self.get('ISOM', cycle)

        a_iso_to_plot,z_iso_to_plot,abunds,isotope_to_plot,el_iso_to_plot,isom=\
            self._process_abundance_vector(a,z,isomers,yps)
        self.a_iso_to_plot=a_iso_to_plot
        self.isotope_to_plot=isotope_to_plot
        self.z_iso_to_plot=z_iso_to_plot
        self.el_iso_to_plot=el_iso_to_plot
        self.abunds=array(abunds)
        self.isom=isom

        if decayed:
            try:
                self.decay_idp
            except AttributeError:
                print("WARNING: decayed in _getcycle ignores isomers " \
                    "and will decay alpha-unstable p-rich nuclei as if they were beta+ stable.")
                print("Initialising decay index pointers ....")
                self.decay_indexpointer() # provides self.decay_idp and
            ind_tmp=self.idp_to_stables_in_isostoplot

            isotope_decay=array(isotope_to_plot)[ind_tmp]
            z_iso_decay=array(z_iso_to_plot)[ind_tmp]
            a_iso_decay=array(a_iso_to_plot)[ind_tmp]
            el_iso_decay=array(el_iso_to_plot)[ind_tmp]
            abunds_decay=zeros(len(ind_tmp), dtype='float64')
            for i in range(len(isotope_to_plot)):
                idp=where(isotope_decay==isotope_to_plot[self.decay_idp[i]])[0] # points from
                # i on isotope_to_plot scale to decay target_on_decayed array scale
                abunds_decay[idp] += abunds[i]

            if self.debug:
                print("Decayed array:")
                for i in range(len(ind_tmp)):
                    print(isotope_decay[i], z_iso_decay[i], a_iso_decay[i], el_iso_decay[i], abunds_decay[i])

            self.a_iso_to_plot=a_iso_decay
            self.isotope_to_plot=isotope_decay
            self.z_iso_to_plot=z_iso_decay
            self.el_iso_to_plot=el_iso_decay
            self.abunds=abunds_decay

Response: Private method for getting a cycle.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _readFile(self, fname, sldir):
        '''
        private method that reads in and organizes the .DAT file
        Loads the data of the .DAT File into the variables cattrs and cols.
        In both these cases they are dictionaries, but in the case of cols,
        it is a dictionary of numpy array exect for the element ,
        element_name where it is just a list

        '''
        cattrs=[]
        if sldir.endswith(os.sep):
            #Making sure fname will be formatted correctly
            fname = str(sldir)+str(fname)
        else:
            fname = str(sldir)+os.sep+str(fname)
            self.sldir+=os.sep
        f=open(fname,'r')
        lines=f.readlines()
        for i in range(len(lines)):
            lines[i]=lines[i].strip()

        cols=lines[0].strip('H')
        cols=cols.strip()
        cols=cols.split()
        for i in range(len(lines)):
            if lines[i].startswith('#'):
                # if it is a cycle attribute line
                lines[i]=lines[i].strip('#')
                tmp=lines[i].split()
                tmp1=[]
                for j in range(len(tmp)):
                    if tmp[j] != '=' or '':
                        tmp1.append(tmp[j])
                tmp=tmp1

                j=0
                while j <len(tmp):
                    cattrs.append(tmp[j])
                    j+=2

            elif not lines[i].startswith('H'):
                index = i-1
                break

        return cattrs,cols, index

Response: Private method that reads in and organizes the. DAT file fname and returns a list of dictionaries where the keys are column names and the values are column names and the index is the index of the column.


Instruction:
Can you generate the documentation for the following Python 3 function
def findFile(self, fname, numtype):
        numType=numtype.upper()
        if numType == 'FILE':
                #do nothing
            return fname
        elif numType == 'CYCNUM':
            try:
                fname = int(fname)
            except ValueError:
                print('Improper choice:'+ str(fname))
                print('Reselecting as 0')
                fname = 0
                print('Using '+self.files[fname])
        try:
            return self.files[self.indexp_cyc2filels[fname]]
        except IndexError:
            mods = array(self.get('mod'), dtype=int)
            if fname not in mods:
                print('You seem to try to plot a cycle that is not present: '+str(fname))
                fname = mods[-1]
                print('I will assume you want to plot the last cycle in the run: '+str(fname))
                print('[I am not 100% sure this escape is debugged. You better do this again with')
                print('the correct input.]')
                return self.files[fname]

Response: Function that finds the associated file for fname when Fname is not in the table.


Instruction:
Write a Python 3 script for
attempting to retry the given data in the given context.

Response:
def _retry(self, context, backoff):
        '''
        A function which determines whether and how to retry.

        :param ~azure.storage.models.RetryContext context:
            The retry context. This contains the request, response, and other data
            which can be used to determine whether or not to retry.
        :param function() backoff:
            A function which returns the backoff time if a retry is to be performed.
        :return:
            An integer indicating how long to wait before retrying the request,
            or None to indicate no retry should be performed.
        :rtype: int or None
        '''
        # If the context does not contain a count parameter, this request has not
        # been retried yet. Add the count parameter to track the number of retries.
        if not hasattr(context, 'count'):
            context.count = 0

        # Determine whether to retry, and if so increment the count, modify the
        # request as desired, and return the backoff.
        if self._should_retry(context):
            context.count += 1

            # If retry to secondary is enabled, attempt to change the host if the
            # request allows it
            if self.retry_to_secondary:
                self._set_next_host_location(context)

            return backoff(context)

        return None


Instruction:
Write a Python 3 function for
converting the response body of a storage service to a ServiceStats object.

Response:
def _convert_xml_to_service_stats(response):
    '''
    <?xml version="1.0" encoding="utf-8"?>
    <StorageServiceStats>
      <GeoReplication>
          <Status>live|bootstrap|unavailable</Status>
          <LastSyncTime>sync-time|<empty></LastSyncTime>
      </GeoReplication>
    </StorageServiceStats>
    '''
    if response is None or response.body is None:
        return None

    service_stats_element = ETree.fromstring(response.body)

    geo_replication_element = service_stats_element.find('GeoReplication')

    geo_replication = GeoReplication()
    geo_replication.status = geo_replication_element.find('Status').text
    geo_replication.last_sync_time = parser.parse(geo_replication_element.find('LastSyncTime').text)

    service_stats = ServiceStats()
    service_stats.geo_replication = geo_replication
    return service_stats


Instruction:
Implement a Python 3 function for
getting the url for firmware update

Response:
def _get_firmware_update_element(self):
        """Get the url for firmware update

        :returns: firmware update url
        :raises: Missing resource error on missing url
        """
        fw_update_action = self._actions.update_firmware
        if not fw_update_action:
            raise (sushy.exceptions.
                   MissingActionError(action='#UpdateService.SimpleUpdate',
                                      resource=self._path))
        return fw_update_action


Instruction:
Can you write a function in Python 3 where it
performs firmware flashing on a redfish system.

Response:
def flash_firmware(self, redfish_inst,  file_url):
        """Perform firmware flashing on a redfish system

        :param file_url: url to firmware bits.
        :param redfish_inst: redfish instance
        :raises: IloError, on an error from iLO.
        """
        action_data = {
            'ImageURI': file_url,
        }
        target_uri = self._get_firmware_update_element().target_uri
        try:
            self._conn.post(target_uri, data=action_data)
        except sushy.exceptions.SushyError as e:
            msg = (('The Redfish controller failed to update firmware '
                    'with file %(file)s Error %(error)s') %
                   {'file': file_url, 'error': str(e)})
            LOG.debug(msg)  # noqa
            raise exception.IloError(msg)

        self.wait_for_redfish_firmware_update_to_complete(redfish_inst)
        try:
            state, percent = self.get_firmware_update_progress()
        except sushy.exceptions.SushyError as e:
            msg = ('Failed to get firmware progress update '
                   'Error %(error)s' % {'error': str(e)})
            LOG.debug(msg)
            raise exception.IloError(msg)

        if state == "Error":
            msg = 'Unable to update firmware'
            LOG.debug(msg)  # noqa
            raise exception.IloError(msg)
        elif state == "Unknown":
            msg = 'Status of firmware update not known'
            LOG.debug(msg)  # noqa
        else:  # "Complete" | "Idle"
            LOG.info('Flashing firmware file: %s ... done', file_url)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def wait_for_redfish_firmware_update_to_complete(self, redfish_object):
        p_state = ['Idle']
        c_state = ['Idle']

        def has_firmware_flash_completed():
            """Checks for completion status of firmware update operation

            The below table shows the conditions for which the firmware update
            will be considered as DONE (be it success or error)::

            +-----------------------------------+-----------------------------+
            |    Previous state                 |   Current state             |
            +===================================+=============================+
            |    Idle                           |   Error, Complete           |
            +-----------------------------------+-----------------------------+
            |    Updating, Verifying,           |   Complete, Error,          |
            |    Uploading, Writing             |   Unknown, Idle             |
            +-----------------------------------+-----------------------------+

            :returns: True upon firmware update completion otherwise False
            """
            curr_state, curr_percent = self.get_firmware_update_progress()
            p_state[0] = c_state[0]
            c_state[0] = curr_state
            if (((p_state[0] in ['Updating', 'Verifying',
                                 'Uploading', 'Writing'])
                    and (c_state[0] in ['Complete', 'Error',
                                        'Unknown', 'Idle']))
                    or (p_state[0] == 'Idle' and (c_state[0] in
                                                  ['Complete', 'Error']))):
                return True
            return False

        common.wait_for_operation_to_complete(
            has_firmware_flash_completed,
            delay_bw_retries=30,
            failover_msg='iLO firmware update has failed.'
        )
        common.wait_for_ilo_after_reset(redfish_object)

Response: This function polls for iLO firmware update to complete.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_firmware_update_progress(self):
        # perform refresh
        try:
            self.refresh()
        except sushy.exceptions.SushyError as e:
            msg = (('Progress of firmware update not known. '
                    'Error %(error)s') %
                   {'error': str(e)})
            LOG.debug(msg)
            return "Unknown", "Unknown"

        # NOTE: Percentage is returned None after firmware flash is completed.
        return (self.firmware_state, self.firmware_percentage)

Response: Get the progress of the firmware update.


Instruction:
Here you have a function in Python 3, explain what it does
def boot_settings(self):
        return BIOSBootSettings(
            self._conn, utils.get_subresource_path_by(
                self, ["Oem", "Hpe", "Links", "Boot"]),
            redfish_version=self.redfish_version)

Response: Property to provide reference to bios boot instance


Instruction:
How would you explain what the following Python 3 function does
def iscsi_resource(self):
        return iscsi.ISCSIResource(
            self._conn, utils.get_subresource_path_by(
                self, ["Oem", "Hpe", "Links", "iScsi"]),
            redfish_version=self.redfish_version)

Response: Property to provide reference to bios iscsi resource instance


Instruction:
Here you have a function in Python 3, explain what it does
def bios_mappings(self):
        return BIOSMappings(
            self._conn, utils.get_subresource_path_by(
                self, ["Oem", "Hpe", "Links", "Mappings"]),
            redfish_version=self.redfish_version)

Response: Property to provide reference to bios mappings instance


Instruction:
Can you tell what is the following Python 3 function doing
def _get_base_configs(self):
        return BIOSBaseConfigs(
            self._conn, utils.get_subresource_path_by(
                self, ["Oem", "Hpe", "Links", "BaseConfigs"]),
            redfish_version=self.redfish_version)

Response: Method that returns object of bios base configs.


Instruction:
Given the following Python 3 function, write the documentation
def set_pending_boot_mode(self, boot_mode):
        bios_properties = {
            'BootMode': mappings.GET_BIOS_BOOT_MODE_MAP_REV.get(boot_mode)
        }

        if boot_mode == sys_cons.BIOS_BOOT_MODE_UEFI:
            bios_properties['UefiOptimizedBoot'] = 'Enabled'

        self.update_bios_data_by_patch(bios_properties)

Response: Sets the boot mode of the system for next boot.


Instruction:
Can you create a Python 3 function that
updates bios data by post

Response:
def update_bios_data_by_post(self, data):
        """Update bios data by post

        :param data: default bios config data
        """
        bios_settings_data = {
            'Attributes': data
        }
        self._conn.post(self.path, data=bios_settings_data)


Instruction:
Can you implement a function in Python 3 that
updates bios data by patch

Response:
def update_bios_data_by_patch(self, data):
        """Update bios data by patch

        :param data: default bios config data
        """
        bios_settings_data = {
            'Attributes': data
        }
        self._conn.patch(self.path, data=bios_settings_data)


Instruction:
Create a Python 3 function to
get the persistent boot device for the host.

Response:
def get_persistent_boot_device(self):
        """Get current persistent boot device set for the host

        :returns: persistent boot device for the system
        :raises: IloError, on an error from iLO.
        """
        boot_string = None
        if not self.persistent_boot_config_order or not self.boot_sources:
            msg = ('Boot sources or persistent boot config order not found')
            LOG.debug(msg)
            raise exception.IloError(msg)

        preferred_boot_device = self.persistent_boot_config_order[0]
        for boot_source in self.boot_sources:
            if ((boot_source.get("StructuredBootString") is not None) and (
                    preferred_boot_device ==
                    boot_source.get("StructuredBootString"))):
                boot_string = boot_source["BootString"]
                break
        else:
            msg = (('Persistent boot device failed, as no matched boot '
                    'sources found for device: %(persistent_boot_device)s')
                   % {'persistent_boot_device': preferred_boot_device})
            LOG.debug(msg)
            raise exception.IloError(msg)

        for key, value in BOOT_SOURCE_TARGET_TO_PARTIAL_STRING_MAP.items():
            for val in value:
                if val in boot_string:
                    return key
        return sushy.BOOT_SOURCE_TARGET_NONE


Instruction:
Make a summary of the following Python 3 code
def get_uefi_boot_string(self, mac):
        boot_sources = self.boot_sources
        if not boot_sources:
            msg = ('Boot sources are not found')
            LOG.debug(msg)
            raise exception.IloError(msg)

        for boot_source in boot_sources:
            if (mac.upper() in boot_source['UEFIDevicePath'] and
                    'iSCSI' in boot_source['UEFIDevicePath']):
                return boot_source['StructuredBootString']
        else:
            msg = ('MAC provided "%s" is Invalid' % mac)
            raise exception.IloInvalidInputError(msg)

Response: Get uefi boot string for the host and system.


Instruction:
Write a Python 3 function that can
return the viscosity of a single Molecular plasma.

Response:
def visc_mol_sol(T,rho,X):
    '''
    Molecular plasma viscosity (Spitzer 1962)

    Parameters
    ----------
    X : float
       H mass fraction
    T : float
       temperature in K
    rho : float
       density in cgs

    Returns
    -------
    nu : float
       molecular diffusivity in [cm**2/s]

    Notes
    -----
    According to Eq 22 in Schatzman (1977). Assume log Lambda = 15.
    (see Table 5.1), a H/He mix (for different mix use Eq. 5.54 in
    Spitzer text book)

    Examples
    --------
    see astronomy.visc_rad_kap_sc

    '''
    visc_mol = 1.84e-17*(1.+7.*X)*(old_div(T**2.5,rho))
    return visc_mol


Instruction:
Explain what the following Python 3 code does
def visc_rad_kap_sc(T,rho,X):
    '''
    Radiative viscosity (Thomas, 1930) for e- scattering opacity

    Parameters
    ----------
    X : float
       H mass fraction
    T : float
       temperature in K
    rho : float
       density in cgs

    Returns
    -------
    nu : float
       radiative diffusivity in [cm**2/s]

    Examples
    --------
    >>> In [1]: import astronomy as ast
    >>> In [2]: l = 100*1.e5 # 100km
    >>> In [3]: v = 1.e5     # typical velocity
    >>> In [4]: T   = 90.e6  # temperature
    >>> In [5]: X   = 0.001  # H mass fraction
    >>> In [6]: rho = 100.   # density
    >>> In [7]: nu = ast.visc_rad_kap_sc(T,rho,X)
    >>> In [8]: Re=v*l/nu
    >>> In [9]: print "Re_rad = "+str('%g'%Re)
    >>> Re_rad = 4.43512e+08

    Notes
    -----
    Eqn. 14' in Schatzman, 1977, assume electron scattering opacity
    kappa_sc = 0.2*(1+X), Kippenhahn (2nd edn, Eqn 17.2)

    '''
    kappa = 0.2*(1.+X)
    nu_rad = 6.88e-26*(old_div(T**4,(kappa*rho**2)))
    return nu_rad

Response: Radiative viscosity for electron scattering opacity in Schatzman 1930


Instruction:
Can you tell what is the following Python 3 function doing
def Gamma1_gasrad(beta):
    '''
    Gamma1 for a mix of ideal gas and radiation

    Hansen & Kawaler, page 177, Eqn. 3.110

    Parameters
    ----------
    beta : float
        Gas pressure fraction Pgas/(Pgas+Prad)

    '''
    Gamma3minus1 = (old_div(2.,3.))*(4.-3.*beta)/(8.-7.*beta)
    Gamma1 = beta + (4.-3.*beta) * Gamma3minus1
    return Gamma1

Response: Returns the Gamma1 for a mix of ideal gas and radiation.


Instruction:
Can you write a function in Python 3 where it
returns the Pas of a base - class resource with the given mean molecular weight rho T and mu.

Response:
def Pgas(rho,T,mu):
    '''
    P = R/mu * rho * T

    Parameters
    ----------
    mu : float
        Mean molecular weight
    rho : float
        Density [cgs]
    T : float
        Temperature [K]

    '''
    R = old_div(boltzmann_constant, atomic_mass_unit)
    return (old_div(R,mu)) * rho * T


Instruction:
Make a summary of the following Python 3 code
def mimf_ferrario(mi):
    ''' Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131.'''

    mf=-0.00012336*mi**6+0.003160*mi**5-0.02960*mi**4+\
      0.12350*mi**3-0.21550*mi**2+0.19022*mi+0.46575
    return mf

Response: Curvature MiMf from Ferrario etal. 2005MNRAS. 361. 1131.


Instruction:
Can you generate the documentation for the following Python 3 function
def imf(m):
    '''
    Returns
    -------
    N(M)dM
        for given mass according to Kroupa IMF, vectorization
        available via vimf()

    '''

    m1 = 0.08; m2 = 0.50
    a1 = 0.30; a2 = 1.30; a3 = 2.3
    const2 = m1**-a1 -m1**-a2
    const3 = m2**-a2 -m2**-a3

    if m < 0.08:
        alpha = 0.3
        const = -const2 -const3
    elif m < 0.50:
        alpha = 1.3
        const = -const3
    else:
        alpha = 2.3
        const = 0.0
    # print m,alpha, const, m**-alpha + const
    return m**-alpha + const

Response: Returns N M according to Kroupa IMF


Instruction:
Here you have a function in Python 3, explain what it does
def int_imf_dm(m1,m2,m,imf,bywhat='bymass',integral='normal'):
    '''
    Integrate IMF between m1 and m2.

    Parameters
    ----------
    m1 : float
        Min mass
    m2 : float
        Max mass
    m : float
        Mass array
    imf : float
        IMF array
    bywhat : string, optional
        'bymass' integrates the mass that goes into stars of
        that mass interval; or 'bynumber' which integrates the number
        of stars in that mass interval.  The default is 'bymass'.
    integrate : string, optional
        'normal' uses sc.integrate.trapz; 'cum' returns cumulative
        trapezoidal integral.  The default is 'normal'.

    '''

    ind_m = (m >= min(m1,m2)) & (m <= max(m1,m2))
    if integral is 'normal':
        int_func = sc.integrate.trapz
    elif integral is 'cum':
        int_func = sc.integrate.cumtrapz
    else:
        print("Error in int_imf_dm: don't know how to integrate")
        return 0

    if bywhat is 'bymass':
        return int_func(m[ind_m]*imf[ind_m],m[ind_m])
    elif bywhat is 'bynumber':
        return int_func(imf[ind_m],m[ind_m])
    else:
        print("Error in int_imf_dm: don't know by what to integrate")
        return 0

Response: Integrate IMF between m1 and m2.


Instruction:
Implement a function in Python 3 to
calculate the orbital angular momentum for two sets of species A and A and e. g Ge etal2010

Response:
def am_orb(m1,m2,a,e):
    '''
    orbital angular momentum.

    e.g Ge etal2010

    Parameters
    ----------
    m1, m2 : float
        Masses of both stars in Msun.
    A : float
        Separation in Rsun.
    e : float
        Eccentricity

    '''

    a_cm  = a * rsun_cm
    m1_g = m1 * msun_g
    m2_g = m2 * msun_g

    J_orb=np.sqrt(grav_const*a_cm*(old_div((m1_g**2*m2_g**2),(m1_g+m2_g))))*(1-e**2)
    return J_orb


Instruction:
How would you explain what the following Python 3 function does
def mass_loss_loon05(L,Teff):
    '''
    mass loss rate van Loon etal (2005).

    Parameters
    ----------
    L : float
        L in L_sun.
    Teff : float
        Teff in K.

    Returns
    -------
    Mdot
        Mdot in Msun/yr

    Notes
    -----
    ref: van Loon etal 2005, A&A 438, 273

    '''

    Mdot = -5.65 + np.log10(old_div(L,10.**4)) -6.3*np.log10(old_div(Teff,3500.))
    return Mdot

Response: Returns the mass loss rate in Msun for a given log L and temperature.


Instruction:
How would you explain what the following Python 3 function does
def energ_orb(m1,m2,r):
    '''
    Parameters
    ----------
    m1, m2 : float
        M in Msun.
    r : float
        Distance in Rsun.

    Returns
    -------
    Epot
        Epot in erg.

    '''
    epo = -grav_const * m1 * m2 * msun_g**2 / (r * rsun_cm)
    return epo

Response: Calculates the Energ orbit of a set of species in the system.


Instruction:
Can you create a Python 3 function that
calculates the binary period from a separation A M1 and M2.

Response:
def period(A,M1,M2):
    """
    calculate binary period from separation.

    Parameters
    ----------
    A : float
        separation A Rsun.
    M1, M2 : float
        M in Msun.

    Returns
    -------
    p
        period in days.

    """

    A *= rsun_cm
    print(A)
    velocity = np.sqrt(grav_const*msun_g*(M1+M2)/A)
    print(old_div(velocity,1.e5))

    p = 2.*np.pi * A / velocity

    p  /= (60*60*24.)
    return p


Instruction:
Can you implement a function in Python 3 that
returns the escape velocity of a single object in the solar masses and solar radiu.

Response:
def escape_velocity(M,R):
    """
    escape velocity.

    Parameters
    ----------
    M : float
        Mass in solar masses.
    R : float
        Radius in solar radiu.

    Returns
    -------
    v_escape
        in km/s.

    """

    ve = np.sqrt(2.*grav_const*M*msun_g/(R*rsun_cm))
    ve = ve*1.e-5
    return ve


Instruction:
Can you create a Python 3 function that
returns the total number of masses in a single node

Response:
def Nasv(macs,T):
    '''
    Returns
    -------
    Na*<sigma v>
        for MACS [mb] at T [K].

    '''

    Na = avogadro_constant
    k  = boltzmann_constant
    vtherm=(2.*k*T/mass_H_atom)**0.5

    s  = macs*1.e-27
    Nasv = s*vtherm*Na
    return Nasv


Instruction:
Can you implement a function in Python 3 that
returns the MACS of a single site at a given mass at a given time.

Response:
def macs(nasv,T):
    '''
    Returns
    -------
    MACS
        [mb] at T [K] from Na*<sigma v>.

    '''

    Na = avogadro_constant
    k  = boltzmann_constant
    vtherm=(2.*k*T/mass_H_atom)**0.5

    s      = old_div(nasv,(vtherm*Na))
    macs   = s*1.e27
    return macs


Instruction:
Write a Python 3 function for
returning the mean molecular weight per free electron assuming full ionisation and mu_i approximating mu_i / Z_i ~ 2 for all elements heavier then Helium.

Response:
def mu_e(X):
    '''
    mean molecular weight per free electron, assuming full ionisation, and
    approximating mu_i/Z_i ~ 2 for all elements heavier then Helium.

    (Kippenhahn & Weigert, Ch 13.1, Eq. 13.8)

    Parameters
    ----------
    X : float
        Mass fraction of H.

    '''

    try:
        mu_e = old_div(2.,(1.+X))
    except TypeError:
        X=np.array([X])
        mu_e = old_div(2.,(1.+X))

    return mu_e


Instruction:
Can you generate the documentation for the following Python 3 function
def mu(X,Z,A):
    '''
    mean molecular weight assuming full ionisation.

    (Kippenhahn & Weigert, Ch 13.1, Eq. 13.6)

    Parameters
    ----------
    X : float
        Mass fraction vector.
    Z : float
        Charge number vector.
    A : float
        Mass number vector.

    '''

    if not isinstance(Z,np.ndarray):
        Z = np.array(Z)
    if not isinstance(A,np.ndarray):
        A = np.array(A)
    if not isinstance(X,np.ndarray):
        X = np.array(X)

    try:
        mu = old_div(1.,sum(X*(1.+Z)/A))
    except TypeError:
        X=np.array([X])
        A=np.array([A])
        Z=np.array([Z])
        mu = old_div(1.,sum(X*(1.+Z)/A))

    return mu

Response: returns the mean molecular weight assuming full ionisation.


Instruction:
Can you tell what is the following Python 3 function doing
def Trho_iddeg(rho,mu,mu_e):
    '''
    T(rho) that separates ideal gas and degenerate pressure dominated regions.

    Kippenhahn & Weigert, Eq. 16.6

    Parameters
    ----------
    rho : float
        Density array [cgs].
    mu : float
        Mean molecular weight.
    mu_e : float
        Mean molecular weight per free electron.

    '''

    T = 1.207E5 * rho**(old_div(2.,3.)) * mu / mu_e**(old_div(5.,3.))
    return T

Response: Returns T that separates ideal gas and degenerate pressure dominated regions.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_criteria_matching_disks(logical_disk, physical_drives):
    matching_physical_drives = []
    criteria_to_consider = [x for x in FILTER_CRITERIA
                            if x in logical_disk]

    for physical_drive_object in physical_drives:
        for criteria in criteria_to_consider:
            logical_drive_value = logical_disk.get(criteria)
            physical_drive_value = getattr(physical_drive_object, criteria)
            if logical_drive_value != physical_drive_value:
                break
        else:
            matching_physical_drives.append(physical_drive_object)

    return matching_physical_drives

Response: This method finds the physical drives matching the criteria of the logical disk.


Instruction:
Can you generate the documentation for the following Python 3 function
def allocate_disks(logical_disk, server, raid_config):
    size_gb = logical_disk['size_gb']
    raid_level = logical_disk['raid_level']
    number_of_physical_disks = logical_disk.get(
        'number_of_physical_disks', constants.RAID_LEVEL_MIN_DISKS[raid_level])
    share_physical_disks = logical_disk.get('share_physical_disks', False)

    # Try to create a new independent array for this request.
    for controller in server.controllers:
        physical_drives = controller.unassigned_physical_drives
        physical_drives = _get_criteria_matching_disks(logical_disk,
                                                       physical_drives)

        if size_gb != "MAX":
            # If we want to allocate for a logical disk for which size_gb is
            # mentioned, we take the smallest physical drives which is required
            # to match the criteria.
            reverse_sort = False
            physical_drives = [x for x in physical_drives
                               if x.size_gb >= size_gb]
        else:
            # If we want to allocate for a logical disk for which size_gb is
            # MAX, we take the largest physical drives available.
            reverse_sort = True

        if len(physical_drives) >= number_of_physical_disks:
            selected_drives = sorted(physical_drives, key=lambda x: x.size_gb,
                                     reverse=reverse_sort)
            selected_drive_ids = [x.id for x in selected_drives]
            logical_disk['controller'] = controller.id
            physical_disks = selected_drive_ids[:number_of_physical_disks]
            logical_disk['physical_disks'] = physical_disks
            return

    # We didn't find physical disks to create an independent array.
    # Check if we can get some shared arrays.
    if share_physical_disks:
        sharable_disk_wwns = []
        for sharable_logical_disk in raid_config['logical_disks']:
            if (sharable_logical_disk.get('share_physical_disks', False) and
                    'root_device_hint' in sharable_logical_disk):
                wwn = sharable_logical_disk['root_device_hint']['wwn']
                sharable_disk_wwns.append(wwn)

        for controller in server.controllers:
            sharable_arrays = [x for x in controller.raid_arrays if
                               x.logical_drives[0].wwn in sharable_disk_wwns]

            for array in sharable_arrays:

                # Check if criterias for the logical disk match the ones with
                # physical disks in the raid array.
                criteria_matched_disks = _get_criteria_matching_disks(
                    logical_disk, array.physical_drives)

                # Check if all disks in the array don't match the criteria
                if len(criteria_matched_disks) != len(array.physical_drives):
                    continue

                # Check if raid array can accomodate the logical disk.
                if array.can_accomodate(logical_disk):
                    logical_disk['controller'] = controller.id
                    logical_disk['array'] = array.id
                    return

    # We check both options and couldn't get any physical disks.
    raise exception.PhysicalDisksNotFoundError(size_gb=size_gb,
                                               raid_level=raid_level)

Response: Allocate physical disks to a logical disk.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01):
    '''
    setup trajectories for constant radiation entropy.

    S_gamma/R where the radiation constant R = N_A*k
    (Dave Arnett, Supernova book, p. 212)
    This relates rho and T but the time scale for this
    is independent.

    Parameters
    ----------
    Sg : float
        S_gamma/R, values between 0.1 and 10. reflect conditions in
        massive stars.  The default is 0.1.
    delta_logt_dex : float
        Sets interval between time steps in dex of logtimerev.  The
        default is -0.01.

    '''

    # reverse logarithmic time
    logtimerev=np.arange(5.,-6.,delta_logt_dex)
    logrho=np.linspace(0,8.5,len(logtimerev))
    logT = (old_div(1.,3.))*(logrho + 21.9161 + np.log10(Sg))

    #rho_6=10**logrho/(0.1213*1.e6)
    #T9=rho_6**(1./3.)
    #logT_T3=np.log10(T9*1.e9)

    pl.close(3);pl.figure(3);pl.plot(logrho,logT,label='$S/\mathrm{N_Ak}='+str(Sg)+'$')
    pl.legend(loc=2);pl.xlabel('$\log \\rho$'); pl.ylabel('$\log T$')
    pl.close(5);pl.figure(5);pl.plot(logtimerev, logrho)
    pl.xlabel('$\log (t_\mathrm{final}-t)$'); pl.ylabel('$\log \\rho$')
    pl.xlim(8,-6)

    pl.close(6);pl.figure(6);pl.plot(logtimerev)
    pl.ylabel('$\log (t_\mathrm{final}-t)$'); pl.xlabel('cycle')

    # [t] logtimerev yrs
    # [rho] cgs
    # [T]   K

    T9=old_div(10**logT,1.e9)
    data=[logtimerev,T9,logrho]
    att.writeTraj(filename='trajectory.input', data=data, ageunit=2, tunit=1, rhounit=1, idNum=1)

Response: setup trajectories for constant radiation entropy.


Instruction:
Can you write a function in Python 3 where it
returns a list of lists of elements to plot.

Response:
def species_list(what_list):
    '''
    provide default lists of elements to plot.

    what_list : string
        String name of species lists provided.

        If what_list is "CNONe", then C, N, O and some other light
        elements.

        If what_list is "s-process", then s-process indicators.

    '''
    if what_list is "CNONe":
        list_to_print = ['H-1','He-4','C-12','N-14','O-16','Ne-20']
    elif what_list is "sprocess":
        list_to_print = ['Fe-56','Ge-70','Zn-70','Se-76','Kr-80','Kr-82','Kr-86','Sr-88','Ba-138','Pb-208']
    elif what_list is "burn_stages":
        list_to_print = ['H-1','He-4','C-12','O-16','Ne-20','Si-28']
    elif what_list is "list_marco_1":
        list_to_print = ['C-12','O-16','Ne-20','Ne-22','Na-23','Fe-54','Fe-56','Zn-70','Ge-70','Se-76','Kr-80','Kr-82','Sr-88','Y-89','Zr-96','Te-124','Xe-130','Xe-134','Ba-138']

    return list_to_print


Instruction:
Make a summary of the following Python 3 code
def linestyle(i,a=5,b=3):
    '''
    provide one out of 25 unique combinations of style, color and mark

    use in combination with markevery=a+mod(i,b) to add spaced points,
    here a would be the base spacing that would depend on the data
    density, modulated with the number of lines to be plotted (b)

    Parameters
    ----------
    i : integer
        Number of linestyle combination - there are many....
    a : integer
        Spacing of marks.  The default is 5.
    b : integer
        Modulation in case of plotting many nearby lines.  The default
        is 3.

    Examples
    --------

    >>> plot(x,sin(x),linestyle(7)[0], markevery=linestyle(7)[1])

    (c) 2014 FH
    '''

    lines=['-','--','-.',':']
    points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o']
    colors=['b','g','r','c','m','k']
    ls_string = colors[sc.mod(i,6)]+lines[sc.mod(i,4)]+points[sc.mod(i,18)]
    mark_i    = a+sc.mod(i,b)
    return ls_string,int(mark_i)

Response: This function returns a string and the number of lines that are plotted in a specific style.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def colourblind(i):
    '''
        colour pallete from http://tableaufriction.blogspot.ro/
        allegedly suitable for colour-blind folk

        SJ
    '''

    rawRGBs = [(162,200,236),
               (255,128,14),
               (171,171,171),
               (95,158,209),
               (89,89,89),
               (0,107,164),
               (255,188,121),
               (207,207,207),
               (200,82,0),
               (137,137,137)]

    scaledRGBs = []
    for r in rawRGBs:
        scaledRGBs.append((old_div(r[0],255.),old_div(r[1],255.),old_div(r[2],255.)))

    idx = sc.mod(i,len(scaledRGBs))
    return scaledRGBs[idx]

Response: colour blinding for a single item in the base image


Instruction:
Can you write a function in Python 3 where it
gets another colour pallete from http://www. sron. nl/~pault / allegedly suitable for colour - blend folk SJ

Response:
def colourblind2(i):
    '''
        another colour pallete from http://www.sron.nl/~pault/
        allegedly suitable for colour-blind folk

        SJ
    '''

    hexcols = ['#332288', '#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77',
               '#CC6677', '#882255', '#AA4499']
    idx = sc.mod(i,len(hexcols))
    return hexcols[idx]


Instruction:
Make a summary of the following Python 3 code
def linestylecb(i,a=5,b=3):
    '''
        version of linestyle function with colourblind colour scheme

        returns linetyle, marker, color (see example)

        Parameters
        ----------
        i : integer
        Number of linestyle combination - there are many....
        a : integer
        Spacing of marks.  The default is 5.
        b : integer
        Modulation in case of plotting many nearby lines.  The default
        is 3.

        Examples
        --------

        >>> plot(x,sin(x),ls=linestyle(7)[0], marker=linestyle(7)[1], \
                 color=linestyle(7)[2],markevery=linestyle(7)[3])

        (c) 2014 FH
        '''

    lines=['-','--','-.',':']
    points=['v','^','<','>','1','2','3','4','s','p','*','h','H','+','x','D','d','o']
    colors=['b','g','r','c','m','k']
    col=colourblind(i)
    style=lines[sc.mod(i,4)]
    point=points[sc.mod(i,18)]
    mark_i    = a+sc.mod(i,b)
    return style,point,col,mark_i

Response: version of linestyle function with colourblind colour scheme


Instruction:
Can you create a Python 3 function that
returns a list of all possible symbol lists for the current language

Response:
def symbol_list(what_list):
    '''
    provide default symbol lists

    Parameters
    ----------
    what_list : string
        String name of symbol lists provided; "list1", "list2",
        "lines1" or "lines2".

    '''
    if what_list is "list1":
        symbol=['ro','bo','ko','go','mo'\
                ,'r-','b-','k-','g-','m-','r--','b--','k--'\
                ,'g--','r1']
        #symbol=['r+','ro','r-']
    elif what_list is "list2":
        symbol=['r-','b--','g-.','k:','md','.','o','v','^','<','>','1','2',\
                '3','4','s','p','*','h','H','+']
    elif what_list is "lines1":
        symbol=['b--','k--','r--','c--','m--','g--','b-','k-','r-','c-','m-','g-','b.','b-.','k-.','r-.','c-.','m-.','g-.','b:','k:','r:','c:','m:','g:']
    elif what_list is "lines2":
        symbol=['g:','r-.','k-','b--','k-.','b+','r:','b-','c--','m--','g--','r-','c-','m-','g-','k-.','c-.','m-.','g-.','k:','r:','c:','m:','b-.','b:']
    return symbol


Instruction:
Can you tell what is the following Python 3 function doing
def make_list(default_symbol_list, len_list_to_print):
    '''
    provide the list of symbols to use according for the list of
    species/arrays to plot.

    Parameters
    ----------
    default_symbol_list : list
        Symbols that the user choose to use.
    len_list_to_print : integer
        len of list of species/arrays to print.

    '''

    symbol_used = []
    for i in range(len_list_to_print):
        symbol_used.append(default_symbol_list[sc.mod(i,len(default_symbol_list))])

    return symbol_used

Response: This function creates a list of symbols that the user choose to use according for the list of species and arrays to plot.


Instruction:
Can you tell what is the following Python 3 function doing
def strictly_monotonic(bb):
    '''
    bb is an index array which may have numerous double or triple
    occurrences of indices, such as for example the decay_index_pointer.
    This method removes all entries <= -, then all dublicates and
    finally returns a sorted list of indices.

    '''
    cc=bb[np.where(bb>=0)]
    cc.sort()
    dc=cc[1:]-cc[:-1] # subsequent equal entries have 0 in db
    dc=np.insert(dc,0,1) # the first element is always unique (the second occurence is the dublicate)
    dc_mask=np.ma.masked_equal(dc,0)
    return np.ma.array(cc,mask=dc_mask.mask).compressed()

Response: This method returns a sorted list of indices that are strictly monotonic.


Instruction:
How would you explain what the following Python 3 function does
def solar(filename_solar, solar_factor):
    '''
    read solar abundances from filename_solar.

    Parameters
    ----------
    filename_solar : string
        The file name.
    solar_factor : float
        The correction factor to apply, in case filename_solar is not
        solar, but some file used to get initial abundances at
        metallicity lower than solar. However, notice that this is
        really rude, since alpha-enahncements and things like that are
        not properly considered.  Only H and He4 are not multiplied. So,
        for publications PLEASE use proper filename_solar at...solar,
        and use solar_factor = 1. Marco

    '''

    f0=open(filename_solar)
    sol=f0.readlines()
    f0.close
    sol[0].split("         ")

    # Now read in the whole file and create a hashed array:
    global names_sol
    names_sol=[]
    global z_sol
    z_sol=[]
    yps=np.zeros(len(sol))
    mass_number=np.zeros(len(sol))
    for i in range(len(sol)):
        z_sol.append(int(sol[i][1:3]))
        names_sol.extend([sol[i].split("         ")[0][4:]])
        yps[i]=float(sol[i].split("         ")[1]) * solar_factor
        try:
            mass_number[i]=int(names_sol[i][2:5])
        except ValueError:
            print("WARNING:")
            print("This initial abundance file uses an element name that does")
            print("not contain the mass number in the 3rd to 5th position.")
            print("It is assumed that this is the proton and we will change")
            print("the name to 'h   1' to be consistent with the notation used in")
            print("iniab.dat files")
            names_sol[i]='h   1'
            mass_number[i]=int(names_sol[i][2:5])
        if mass_number[i] == 1 or mass_number[i] == 4:
            yps[i] = old_div(yps[i],solar_factor)
    #  convert 'h   1' in prot, not needed any more??
    #names_sol[0] = 'prot '

    # now zip them together:
    global solar_abundance
    solar_abundance={}
    for a,b in zip(names_sol,yps):
        solar_abundance[a] = b

    z_bismuth = 83
    global solar_elem_abund
    solar_elem_abund = np.zeros(z_bismuth)

    for i in range(z_bismuth):
        dummy = 0.
        for j in range(len(solar_abundance)):
            if z_sol[j] == i+1:
                dummy = dummy + float(solar_abundance[names_sol[j]])
        solar_elem_abund[i] = dummy

Response: Reads the solar abundances from filename_solar and creates a hashed array of solar abundances.


Instruction:
Can you generate the documentation for the following Python 3 function
def convert_specie_naming_from_h5_to_ppn(isotope_names):
    '''
    read isotopes names from h5 files, and convert them
    according to standard scheme used inside ppn and mppnp.  Also
    Z and A are recalculated, for these species. Isomers are
    excluded for now, since there were recent changes in isomers
    name. As soon as the isomers names are settled, than Z and A
    provided here will be obsolete, and can be changed by usual Z
    and A.

    '''

    spe_rude1 = []
    spe_rude2 = []
    spe_rude3 = []
    for i in range(len(isotope_names)):
        spe_rude1.append(isotope_names[i].split('-')[0])
        spe_rude2.append(isotope_names[i].split('-')[1])
    # spe_rude1 is elem name and spe_rude2 is mass number.
    #print spe_rude1,spe_rude2
    k = 0
    for i in range(len(spe_rude1)):
        try:
            if int(spe_rude2[i]) < 10:
                spe_rude3.append(str(spe_rude1[i][0:2])+str('  ')+str(spe_rude2[i][0:3]))
            elif int(spe_rude2[i]) >= 10 and int(spe_rude2[i]) < 100 :
                spe_rude3.append(str(spe_rude1[i][0:2])+str(' ')+str(spe_rude2[i][0:3]))
            elif int(spe_rude2[i]) >= 100 :
                spe_rude3.append(str(spe_rude1[i][0:2])+str(spe_rude2[i][0:3]))
        except ValueError:
            k = k+1
            None

    global spe
    spe = []
    global n_array
    n_array = []
    for i in range(len(spe_rude3)):
        if len(str(spe_rude1[i])) == 1:
            spe.append(str(spe_rude3[i][0:1])+str(' ')+str(spe_rude3[i][1:4]))
        else:
            spe.append(spe_rude3[i])
        n_array.append(i)
    if spe[0]=='Ne  1':
        spe[0] = 'N   1'

    # spe_rude is the isotope name, in agreement with what we use in ppn, etc.
    # need to do this to can use other functions without changing them drastically.

    # here I skip isomers...
    global amass_int
    amass_int=np.zeros(len(spe_rude2))
    for i in range(len(spe_rude2)-k):
        amass_int[i]=int(spe_rude2[i])
        #print amass_int

    # here I have to create an array for the atomic numbers.
    # I need to this when I calculate and plot element abundances

    global znum_int
    znum_int=np.zeros(len(spe))

    for i in range(len(spe)):
        znum_int[i] = Utils.elements_names.index(str(spe[i][0:2]).strip())
        # changed by alex
        # if str(spe[i][0:2]) == 'H ':
        #     znum_int[i] = 1
        # elif str(spe[i][0:2]) == 'He':
        #     znum_int[i] = 2
        # elif str(spe[i][0:2]) == 'Li':
        #     znum_int[i] = 3
        # elif str(spe[i][0:2]) == 'Be':
        #     znum_int[i] = 4
        # elif str(spe[i][0:2]) == 'B ':
        #     znum_int[i] = 5
        # elif str(spe[i][0:2]) == 'C ':
        #     znum_int[i] = 6
        # elif str(spe[i][0:2]) == 'N ':
        #     znum_int[i] = 7
        # elif str(spe[i][0:2]) == 'O ':
        #     znum_int[i] = 8
        # elif str(spe[i][0:2]) == 'F ':
        #     znum_int[i] = 9
        # elif str(spe[i][0:2]) == 'Ne':
        #     znum_int[i] = 10
        # elif str(spe[i][0:2]) == 'Na':
        #     znum_int[i] = 11
        # elif str(spe[i][0:2]) == 'Mg':
        #     znum_int[i] = 12
        # elif str(spe[i][0:2]) == 'Al':
        #     znum_int[i] = 13
        # elif str(spe[i][0:2]) == 'Si':
        #     znum_int[i] = 14
        # elif str(spe[i][0:2]) == 'P ':
        #     znum_int[i] = 15
        # elif str(spe[i][0:2]) == 'S ':
        #     znum_int[i] = 16
        # elif str(spe[i][0:2]) == 'Cl':
        #     znum_int[i] = 17
        # elif str(spe[i][0:2]) == 'Ar':
        #     znum_int[i] = 18
        # elif str(spe[i][0:2]) == 'K ':
        #     znum_int[i] = 19
        # elif str(spe[i][0:2]) == 'Ca':
        #     znum_int[i] = 20
        # elif str(spe[i][0:2]) == 'Sc':
        #     znum_int[i] = 21
        # elif str(spe[i][0:2]) == 'Ti':
        #     znum_int[i] = 22
        # elif str(spe[i][0:2]) == 'V ':
        #     znum_int[i] = 23
        # elif str(spe[i][0:2]) == 'Cr':
        #     znum_int[i] = 24
        # elif str(spe[i][0:2]) == 'Mn':
        #     znum_int[i] = 25
        # elif str(spe[i][0:2]) == 'Fe':
        #     znum_int[i] = 26
        # elif str(spe[i][0:2]) == 'Co':
        #     znum_int[i] = 27
        # elif str(spe[i][0:2]) == 'Ni':
        #     znum_int[i] = 28
        # elif str(spe[i][0:2]) == 'Cu':
        #     znum_int[i] = 29
        # elif str(spe[i][0:2]) == 'Zn':
        #     znum_int[i] = 30
        # elif str(spe[i][0:2]) == 'Ga':
        #     znum_int[i] = 31
        # elif str(spe[i][0:2]) == 'Ge':
        #     znum_int[i] = 32
        # elif str(spe[i][0:2]) == 'As':
        #     znum_int[i] = 33
        # elif str(spe[i][0:2]) == 'Se':
        #     znum_int[i] = 34
        # elif str(spe[i][0:2]) == 'Br':
        #     znum_int[i] = 35
        # elif str(spe[i][0:2]) == 'Kr':
        #     znum_int[i] = 36
        # elif str(spe[i][0:2]) == 'Rb':
        #     znum_int[i] = 37
        # elif str(spe[i][0:2]) == 'Sr':
        #     znum_int[i] = 38
        # elif str(spe[i][0:2]) == 'Y ':
        #     znum_int[i] = 39
        # elif str(spe[i][0:2]) == 'Zr':
        #     znum_int[i] = 40
        # elif str(spe[i][0:2]) == 'Nb':
        #     znum_int[i] = 41
        # elif str(spe[i][0:2]) == 'Mo':
        #     znum_int[i] = 42
        # elif str(spe[i][0:2]) == 'Tc':
        #     znum_int[i] = 43
        # elif str(spe[i][0:2]) == 'Ru':
        #     znum_int[i] = 44
        # elif str(spe[i][0:2]) == 'Rh':
        #     znum_int[i] = 45
        # elif str(spe[i][0:2]) == 'Pd':
        #     znum_int[i] = 46
        # elif str(spe[i][0:2]) == 'Ag':
        #     znum_int[i] = 47
        # elif str(spe[i][0:2]) == 'Cd':
        #     znum_int[i] = 48
        # elif str(spe[i][0:2]) == 'In':
        #     znum_int[i] = 49
        # elif str(spe[i][0:2]) == 'Sn':
        #     znum_int[i] = 50
        # elif str(spe[i][0:2]) == 'Sb':
        #     znum_int[i] = 51
        # elif str(spe[i][0:2]) == 'Te':
        #     znum_int[i] = 52
        # elif str(spe[i][0:2]) == 'I ':
        #     znum_int[i] = 53
        # elif str(spe[i][0:2]) == 'Xe':
        #     znum_int[i] = 54
        # elif str(spe[i][0:2]) == 'Cs':
        #     znum_int[i] = 55
        # elif str(spe[i][0:2]) == 'Ba':
        #     znum_int[i] = 56
        # elif str(spe[i][0:2]) == 'La':
        #     znum_int[i] = 57
        # elif str(spe[i][0:2]) == 'Ce':
        #     znum_int[i] = 58
        # elif str(spe[i][0:2]) == 'Pr':
        #     znum_int[i] = 59
        # elif str(spe[i][0:2]) == 'Nd':
        #     znum_int[i] = 60
        # elif str(spe[i][0:2]) == 'Pm':
        #     znum_int[i] = 61
        # elif str(spe[i][0:2]) == 'Sm':
        #     znum_int[i] = 62
        # elif str(spe[i][0:2]) == 'Eu':
        #     znum_int[i] = 63
        # elif str(spe[i][0:2]) == 'Gd':
        #     znum_int[i] = 64
        # elif str(spe[i][0:2]) == 'Tb':
        #     znum_int[i] = 65
        # elif str(spe[i][0:2]) == 'Dy':
        #     znum_int[i] = 66
        # elif str(spe[i][0:2]) == 'Ho':
        #     znum_int[i] = 67
        # elif str(spe[i][0:2]) == 'Er':
        #     znum_int[i] = 68
        # elif str(spe[i][0:2]) == 'Tm':
        #     znum_int[i] = 69
        # elif str(spe[i][0:2]) == 'Yb':
        #     znum_int[i] = 70
        # elif str(spe[i][0:2]) == 'Lu':
        #     znum_int[i] = 71
        # elif str(spe[i][0:2]) == 'Hf':
        #     znum_int[i] = 72
        # elif str(spe[i][0:2]) == 'Ta':
        #     znum_int[i] = 73
        # elif str(spe[i][0:2]) == 'W ':
        #     znum_int[i] = 74
        # elif str(spe[i][0:2]) == 'Re':
        #     znum_int[i] = 75
        # elif str(spe[i][0:2]) == 'Os':
        #     znum_int[i] = 76
        # elif str(spe[i][0:2]) == 'Ir':
        #     znum_int[i] = 77
        # elif str(spe[i][0:2]) == 'Pt':
        #     znum_int[i] = 78
        # elif str(spe[i][0:2]) == 'Au':
        #     znum_int[i] = 79
        # elif str(spe[i][0:2]) == 'Hg':
        #     znum_int[i] = 80
        # elif str(spe[i][0:2]) == 'Tl':
        #     znum_int[i] = 81
        # elif str(spe[i][0:2]) == 'Pb':
        #     znum_int[i] = 82
        # elif str(spe[i][0:2]) == 'Bi':
        #     znum_int[i] = 83
        # elif str(spe[i][0:2]) == 'Po':
        #     znum_int[i] = 84
        # elif str(spe[i][0:2]) == 'At':
        #     znum_int[i] = 85
        # elif str(spe[i][0:2]) == 'Rn':
        #     znum_int[i] = 86
        # elif str(spe[i][0:2]) == 'Fr':
        #     znum_int[i] = 87
        # elif str(spe[i][0:2]) == 'Ra':
        #     znum_int[i] = 88
        # elif str(spe[i][0:2]) == 'Ac':
        #     znum_int[i] = 89
        # elif str(spe[i][0:2]) == 'Th':
        #     znum_int[i] = 90
        # elif str(spe[i][0:2]) == 'Pa':
        #     znum_int[i] = 91
        # elif str(spe[i][0:2]) == 'U ':
        #     znum_int[i] = 92
        # elif str(spe[i][0:2]) == 'Np':
        #     znum_int[i] = 93
        # elif str(spe[i][0:2]) == 'Pu':
        #     znum_int[i] = 94
        # elif str(spe[i][0:2]) == 'Am':
        #     znum_int[i] = 95
        # elif str(spe[i][0:2]) == 'Cm':
        #     znum_int[i] = 96
        # elif str(spe[i][0:2]) == 'Bk':
        #     znum_int[i] = 97
        # elif str(spe[i][0:2]) == 'Cf':
        #     znum_int[i] = 98

    if spe[0] == 'N   1':
        znum_int[0] = 0

    # here the index to connect name and atomic numbers.
    global index_atomic_number
    index_atomic_number = {}
    for a,b in zip(spe,znum_int):
        index_atomic_number[a]=b

Response: Convert the specie names from h5 files to ppn.


Instruction:
Write a Python 3 function for
giving an array of isotopic abundances not decayed and a similar array of isotopic abundances not decayed, here elements abundances, and production factors for elements are calculated

Response:
def element_abund_marco(i_decay, stable_isotope_list,
                        stable_isotope_identifier,
                        mass_fractions_array_not_decayed,
                        mass_fractions_array_decayed):
    '''
    Given an array of isotopic abundances not decayed and a similar
    array of isotopic abundances not decayed, here elements abundances,
    and production factors for elements are calculated

    '''

    # this way is done in a really simple way. May be done better for sure, in a couple of loops.
    # I keep this, since I have only to copy over old script. Falk will probably redo it.

    #import numpy as np
    #from NuGridPy import utils as u

    global elem_abund
    elem_abund = np.zeros(z_bismuth)
    global elem_abund_decayed
    elem_abund_decayed = np.zeros(z_bismuth)
    global elem_prod_fac
    elem_prod_fac = np.zeros(z_bismuth)
    global elem_prod_fac_decayed
    elem_prod_fac_decayed = np.zeros(z_bismuth)

    # notice that elem_abund include all contribution, both from stables and unstables in
    # that moment.
    for i in range(z_bismuth):
        dummy = 0.
        for j in range(len(spe)):
            if znum_int[j] == i+1 and stable_isotope_identifier[j] > 0.5:
                dummy = dummy + float(mass_fractions_array_not_decayed[j])
        elem_abund[i] = dummy

    for i in range(z_bismuth):
        if index_stable[i] == 1:
            elem_prod_fac[i] = float(old_div(elem_abund[i],solar_elem_abund[i]))
        elif index_stable[i] == 0:
            elem_prod_fac[i] = 0.

    if i_decay == 2:
        for i in range(z_bismuth):
            dummy = 0.
            for j in range(len(mass_fractions_array_decayed)):
                if znum_int[cl[stable_isotope_list[j].capitalize()]] == i+1:
                #print znum_int[cl[stable[j].capitalize()]],cl[stable[j].capitalize()],stable[j]
                    dummy = dummy + float(mass_fractions_array_decayed[j])
            elem_abund_decayed[i] = dummy

        for i in range(z_bismuth):
            if index_stable[i] == 1:
                elem_prod_fac_decayed[i] = float(old_div(elem_abund_decayed[i],solar_elem_abund[i]))
            elif index_stable[i] == 0:
                elem_prod_fac_decayed[i] = 0.