Instruction:
Make a summary of the following Python 3 code
def cores(self, incycle, **keyw):

        def infomod(core_opt, *inp):
            """
            This calls the correct infomod function depending on the
            value of core_opt.

            """
            if core_opt == 0:
                return infomod1(inp[0], inp[1], inp[2])
            elif core_opt == 1:
                return infomod2(inp[0], inp[1], inp[2], inp[3], inp[4])

        def infomod1(shell, yps, isoindex):
            """
            Function for defining data to print into a string.  This is
            used for the case of core_opt = 0.

            """

            xh = yps[shell][isoindex[0]]
            xhe = yps[shell][isoindex[1]]
            xc = yps[shell][isoindex[2]]
            xo = yps[shell][isoindex[3]]
            xsi = yps[shell][isoindex[4]]
            xs = yps[shell][isoindex[5]]
            xa = yps[shell][isoindex[6]]
            xca = yps[shell][isoindex[7]]
            xti = yps[shell][isoindex[8]]
            xcr = yps[shell][isoindex[9]]
            xfe = yps[shell][isoindex[10]]
            xni = yps[shell][isoindex[11]]

            xsicore = xsi + xs + xa + xca + xti
            xfecore = xcr + xfe + xni

            return ' h=' + "%12.4e"%(xh) + ' he=' + "%12.4e"%(xhe) + \
            ' c=' + "%12.4e"%(xc) + ' o=' + "%12.4e"%(xo) + \
            ' si=' + "%12.4e"%(xsicore) + ' fe=' + "%12.4e"%(xfecore)

        def infomod2(shell, yps, isoindex, xsicore, xfecore):
            """
            Function for defining data to print into a string.  This is
            used for the case of core_opt = 1.

            """
            xsicore = 0.
            xsicoren = 0.
            xfecore = 0.
            xfecoren = 0.

            xh = yps[shell][isoindex[0]]
            xhe = yps[shell][isoindex[1]]
            xc = yps[shell][isoindex[2]]
            xo = yps[shell][isoindex[3]]

            for j in iso_si:
                xsicore += yps[i][j]
                xsicoren += yps[i+iter][j]
            for j in iso_fe:
                xfecore += yps[i][j]
                xfecoren += yps[i+iter][j]

            return 'shellnb = ' + str(shell) + ' h=' + "%12.4e"%(xh) + \
            ' he=' + "%12.4e"%(xhe) + ' c=' + "%12.4e"%(xc) + \
            ' o=' + "%12.4e"%(xo) + ' si=' + "%12.4e"%(xsicore) + \
            ' fe=' + "%12.4e"%(xfecore)

        if ("isoa" in keyw) == False:
            keyw["isoa"] = "A"
        if ("isoz" in keyw) == False:
            keyw["isoz"] = "Z"
        if ("mass" in keyw) == False:
            keyw["mass"] = "mass"
        if ("abund" in keyw) == False:
            keyw["abund"] = "iso_massf"
        if ("coreopt" in keyw) == False:
            core_opt = 1
        else:
            core_opt = keyw["coreopt"]

        cores = [0,0,0,0,0,0]
        core_type = ["","","","","",""]
        core_info = []
        iso_si = []
        iso_fe = []
        first = True

        xm_list     = self.se.get(incycle, keyw["mass"])
        abund_list  = self.se.get(incycle, keyw["abund"])
        tables = self.se.Tables
        isoa_list   = tables[0]
        isoz_list   = tables[1]

        # Check the order of the input data
        xmass = xm_list
        yps = abund_list
        centre = 0
        surface = len(xmass)-1
        iter = -1
        if isinstance(xmass, list) == True:
            if xmass[0] > xmass[1]:
                # mass is descending with shell number and the centre of the star
                # is the last shell
                centre = len(xmass)-1
                surface = 0
                iter = 1

        mco01 = 0.
        na    = 0
        nco   = 0

        h1index = -1
        he4index = -1
        c12index = -1
        o16index = -1
        si28index = -1
        s32index = -1
        a36index = -1
        ca40index = -1
        ti44index = -1
        cr48index = -1
        fe52index = -1
        ni56index = -1

        # Determine yps indices for certain abundances
        for i in range(len(isoa_list)):
            try:
                A = int(isoa_list[i])
                Z = int(isoz_list[i])
            except TypeError:
                A = int(isoa_list[i][0])
                Z = int(isoz_list[i][0])

            if A == 1 and Z == 1:
                h1index = i
            elif A == 4 and Z == 2:
                he4index = i
            elif A == 12 and Z == 6:
                c12index = i
            elif A == 16 and Z == 8:
                o16index = i

            if core_opt == 0:
                if A == 28 and Z == 14:
                    si28index = i
                elif A == 32 and Z == 16:
                    s32index = i
                elif A == 36 and Z == 18:
                    a36index = i
                elif A == 40 and Z == 20:
                    ca40index = i
                elif A == 44 and Z == 22:
                    ti44index = i
                elif A == 48 and Z == 24:
                    cr48index = i
                elif A == 52 and Z == 26:
                    fe52index = i
                elif A == 56 and Z == 38:
                    ni56index = i

        if h1index == -1 or he4index == -1 or c12index == -1 or o16index == -1:
            print("A key isotope(s) is not found in network!  Please check for the \
            presence of H1, He4, C12 and O16.")
            os.sys.exit()

        # Si_core = Si28+S32+Ar36+Ca40+Ti44
        # Fe_core = Cr48+Fe52+Ni56
        if core_opt == 0:
            if si28index == -1 or s32index == -1 or a36index == -1 or ca40index == -1 \
            or ti44index == -1 or cr48index == -1 or fe52index == -1 or ni56index == -1:
                print("Key isotopes for measuring the core mass with core_opt = 0 \
                are missing.  Setting core_opt = 1.")
                core_opt = 1

        # Si_core = Sum of all isotopes with 14 <= Z <= 22
        # Fe_core = Sum of all isotopes with 23 <= Z <= 28
        if core_opt == 1:
            for i in range(len(isoa_list)):
                try:
                    A = int(isoa_list[i])
                    Z = int(isoz_list[i])
                except TypeError:
                    A = int(isoa_list[i][0])
                    Z = int(isoz_list[i][0])
                if Z >= 14 and Z <= 22:
                    iso_si.append(i)
                if Z >= 23 and Z <= 28:
                    iso_fe.append(i)

        isoindex = [h1index, he4index, c12index, o16index]
        if core_opt == 0:
            isoindex.extend([si28index, s32index, a36index, ca40index,
            ti44index, cr48index, fe52index, ni56index])

        if first == True:
            first = False
            cores[0] = xmass[surface]
            core_type[0] = "Final"
            core_info.append(infomod(core_opt, surface, yps, isoindex, iso_si, iso_fe))

        # Iterate over shells to determine the core masses
        for i in np.arange(surface, centre, iter):

            xsicore = 0.
            xfecore = 0.
            xsicoren = 0.
            xfecoren = 0.

            # Abundances of key isotopes at this shell (and the next one)
            xh = yps[i][h1index]
            xhe = yps[i][he4index]
            xc = yps[i][c12index]
            xo = yps[i][o16index]

            xhn = yps[i+iter][h1index]
            xhen = yps[i+iter][he4index]
            xcn = yps[i+iter][c12index]
            xon = yps[i+iter][o16index]

            xcocore = xc + xo
            xcocoren = xcn + xon

            if core_opt == 0:
                xsi = yps[i][si28index]
                xs = yps[i][s32index]
                xa = yps[i][a36index]
                xca = yps[i][ca40index]
                xti = yps[i][ti44index]
                xcr = yps[i][cr48index]
                xfe = yps[i][fe52index]
                xni = yps[i][ni56index]

                xsin = yps[i+iter][si28index]
                xsn = yps[i+iter][s32index]
                xan = yps[i+iter][a36index]
                xcan = yps[i+iter][ca40index]
                xtin = yps[i+iter][ti44index]
                xcrn = yps[i+iter][cr48index]
                xfen = yps[i+iter][fe52index]
                xnin = yps[i+iter][ni56index]

                xsicore = xsi + xs + xa + xca + xti
                xfecore = xcr + xfe + xni

                xsicoren = xsin + xsn + xan + xcan + xtin
                xfecoren = xcrn + xfen + xnin

            elif core_opt == 1:
                for j in iso_si:
                    xsicore += yps[i][j]
                    xsicoren += yps[i+iter][j]
                for j in iso_fe:
                    xfecore += yps[i][j]
                    xfecoren += yps[i+iter][j]

            # M_alpha:
            if xh >= 1.e-9:
                if xhen > 0.75 and xhe <= 0.75:
                    if cores[1] == 0:
                        cores[1] = xmass[i]
                        core_type[1] = 'Malpha 75%'
                        core_info.append('Malpha 75% '+str(xmass[i-iter])+ \
                        infomod(core_opt, i-iter, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Malpha 75% '+str(xmass[i])+ \
                        infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Malpha 75% '+str(xmass[i+iter])+ \
                        infomod(core_opt, i+iter, yps, isoindex, iso_si, iso_fe))
                if xhen > 0.5 and xhe <= 0.5:
                    core_info.append('Malpha 50% '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xhn < 1.e-2 and xh >= 1.e-2:
                    na=i
                    core_info.append('Malpha 1.e-2 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xhn < 1.e-4 and xh >= 1.e-4:
                    core_info.append('Malpha 1.e-4 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xhn < 1.e-5 and xh >= 1.e-5:
                    core_info.append('Malpha 1.e-5 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))

            # M_CO:
            if xhe >= 1.e-9 and xh < 1.e-9:
                if xcocoren > 0.5 and xcocore <= 0.5:
                    core_info.append('Mco 50% '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xcocoren > 0.75 and xcocore <= 0.75:
                    core_info.append('Mco 75% '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xhen < 1.e-2 and xhe >= 1.e-2:
                    if cores[2] == 0:
                        mco01=xmass[i]
                        nco=i
                        cores[2] = xmass[i]
                        core_type[2] = 'Mco'
                        core_info.append('Mco 1.e-2 '+str(xmass[i-iter])+ \
                        infomod(core_opt, i-iter, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Mco 1.e-2 '+str(xmass[i])+ \
                        infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Mco 1.e-2 '+str(xmass[i+iter])+ \
                        infomod(core_opt, i+iter, yps, isoindex, iso_si, iso_fe))
                if xhen < 1.e-4 and xhe >= 1.e-4:
                    core_info.append('Mco 1.e-4 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xhen < 1.e-5 and xhe >= 1.e-5:
                    core_info.append('Mco 1.e-5 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))

            # M_Si:
            if xcocore >= 1.e-7:
                if xsicoren > 0.5 and xsicore <= 0.5:
                    if cores[3] == 0:
                        core_info.append('Msi 50% '+str(xmass[i-iter])+ \
                        infomod(core_opt, i-iter, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Msi 50% '+str(xmass[i])+ \
                        infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                        core_info.append('Msi 50% '+str(xmass[i+iter])+ \
                        infomod(core_opt, i+iter, yps, isoindex, iso_si, iso_fe))
                        cores[3] = xmass[i]
                        core_type[3] = 'Msi 50%'
                if xsicoren > 0.75 and xsicore <= 0.75:
                    core_info.append('Msi 75% '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                if xcocoren > 1.e-2 and xcocore <= 1.e-2:
                    core_info.append('Msi 1.e-2 '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))

            # M_fe:
            if xfecoren > 0.5 and xfecore <= 0.5:
                if cores[4] == 0:
                    core_info.append('Mfe 50% '+str(xmass[i-iter])+ \
                    infomod(core_opt, i-iter, yps, isoindex, iso_si, iso_fe))
                    core_info.append('Mfe 50% '+str(xmass[i])+ \
                    infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
                    core_info.append('Mfe 50% '+str(xmass[i+iter])+ \
                    infomod(core_opt, i+iter, yps, isoindex, iso_si, iso_fe))
                    cores[4] = xmass[i]
                    core_type[4] = 'Mfe 50%'
            if xfecoren > 0.75 and xfecore <= 0.75:
                core_info.append('Mfe 75% '+str(xmass[i])+ \
                infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))
            if xsicoren > 1.e-2 and xsicore <= 1.e-2:
                core_info.append('Mfe 1.e-2 '+str(xmass[i])+ \
                infomod(core_opt, i, yps, isoindex, iso_si, iso_fe))

        mcof=mco01
        i=na
        while i < nco:
            i+=1
            xco = yps[i][c12index] + yps[i][o16index]
            xcop = yps[i-iter][c12index] + yps[i-iter][o16index]
            mcof+=(xco+xcop)/2.*(xmass[i-iter]-xmass[i])
        cores[2] = mcof
        core_type[2] = 'Mco int'

        # M_rem vs M_CO relationship
        xmco = np.array([0.72,1.01,1.38,2.10,2.97,4.94,7.20,13.88,24.75,38.12,58.73])
        xmre = np.array([0.72,1.01,1.23,1.42,1.65,2.15,2.72,4.3,7.6,11.4,17.1])

        if 'Mco' in core_type:
            for i in np.arange(len(xmco)):
                if cores[2] < xmco[i]:
                    xco = yps[i][c12index] + yps[i][o16index]
                    xcop = yps[i-iter][c12index] + yps[i-iter][o16index]
                    cores[5] = xmre[i-1]+(xmre[i]-xmre[i-1])*(cores[j]-xmco[i-1])/(xmco[i]-xmco[i-1])
                    core_type[5] = 'Mrem'
                    break

        return [cores, core_type, core_info]

Response: This function returns the list of core masses for the given incycle and key word arguments.


Instruction:
Explain what the following Python 3 code does
def presnyields(self, *cycles, **keyw):
        abund_list  = []
        xm_list  = []

        if ("xm" in keyw) == False:
            keyw["xm"] = "mass"
        if ("abund" in keyw) == False:
            keyw["abund"] = "iso_massf"
        if ("mrem" in keyw) == False:
            mrem = 0.
        else:
            mrem = keyw["mrem"]

        # Only two cycles are required in this program.
        # Any more will be ignored
        cylen = len(cycles)
        if cylen > 2:
            cylen = 2
        for i in range(cylen):
            cycle = cycles[i]
            abund_list.append(self.se.get(cycle, keyw['abund']))
            xm_list.append(self.se.get(cycle, keyw['xm']))

        isoX = abund_list[0]
        xm = xm_list[0]
        if cylen == 2:
            isoXini = abund_list[1] # initial abundances

        niso = len(isoX[0,:])
        nshells = len(xm)

        X_i = np.zeros([niso], float)
        ybound = np.zeros([niso], float)
        xarray = np.zeros([nshells+1], float)
        yarray = np.zeros([nshells+1], float)

        # This part determines the index of the mass coordinate array which
        # is closest to the specified remnant mass.  This is used in the next
        # part, which is used to interpolate the abundances at the remnant mass
        for k in range(nshells):
            k1 = k
            if mrem<=xm[k]:
                break

        # This part is the interpolation of the isotopes found at the remnant
        # mass.
        for i in range(niso):
            if k1>=1:
                if isoX[k1-1,i]!=0.0:
                    m=old_div((isoX[k1,i]-isoX[k1-1,i]),(xm[k1]-xm[k1-1]))
                    ybound[i] = isoX[k1-1,i] +m*(mrem-xm[k1-1])
                else:
                    ybound[i]=1.e-99
            if k1==0:
                if isoX[k1,i]!=0.0:
                    ybound[i]=isoX[k1,i]
                else:
                    ybound[i]=1.e-99

        # This part merges the interpolated data and the existing arrays into
        # the arrays xarray and yarray.  Once this is done, the summation is
        # made.
        xarray[0] = mrem
        xarray[1:nshells-k1+1] = xm[k1:nshells]
        for i in range(niso):
            yarray[0] = ybound[i]
            for j in range(nshells-k1):
                if isoX[k1+j,i] != 0.0:
                    yarray[j+1] = isoX[k1+j,i]
                else:
                    yarray[j+1] = 1.e-99

            if cylen == 1:
                # Calculate the ejected masses
                for j in range(nshells-k1):
                    X_i[i] = X_i[i] + ((0.5*(yarray[j+1] + yarray[j])) * \
                    (xarray[j+1] - xarray[j]))
            elif cylen == 2:
                # Calculate the SN yield.
                for j in range(nshells-k1):
                    X_i[i] = X_i[i] + ((0.5*(yarray[j+1] + yarray[j]) - isoXini[-1,i]) * \
                    (xarray[j+1] - xarray[j]))

        return X_i

Response: This function calculates the presupernova yields of a full structure profile from a remnant mass and mrem.


Instruction:
How would you explain what the following Python 3 function does
def windyields(self, ini, end, delta, **keyw):

        if ("tmass" in keyw) == False:
            keyw["tmass"] = "mass"
        if ("abund" in keyw) == False:
            keyw["abund"] = "iso_massf"
        if ("cycle" in keyw) == False:
            keyw["cycle"] = "cycle"

        print("Windyields() initialised.  Reading files...")

        ypsinit = []
        niso = 0
        X_i = []
        E_i = []
        totalmass = []
        ypssurf  = []
        cycles = []
        first = True

        # The following statements copy global functions into local memory,
        # which is called faster, speeding up the code slightly
        wc = self._windcalc
        cycleret = self.se.cycles
        retrieve = self.se.get
        capp = cycles.extend
        tapp = totalmass.extend
        yapp = ypssurf.extend

        # Retrieve the data from the files
        for i in range(ini,end+1,delta):
            step = int(i)
            capp([int(cycleret[i-ini])])
            tapp([retrieve(step,keyw["tmass"])])
            yapp([retrieve(step,keyw["abund"])])

        print("Reading complete.  Calculating yields and ejected masses...")

        nsteps = len(cycles)-1
        niso = len(ypssurf[0])
        X_i = np.zeros([niso], float)
        E_i = np.zeros([niso], float)
        # Call the windyields calculator
        X_i, E_i = wc(first, totalmass, nsteps, niso, ypssurf, \
        ypsinit, X_i, E_i, cycles)
        return X_i, E_i

Response: This function initializes the entry point for the wind yields and ejected masses.


Instruction:
Can you tell what is the following Python 3 function doing
def average_iso_abund_marco(self,mass_range,cycle,stable,i_decay):

        import nuutils as u

        if not stable and i_decay == 2:
            print('ERROR: choose i_decay = 1')
            return

        #data=mp.se(directory,name_h5_file)
        self._read_iso_abund_marco(mass_range,cycle)
        #print spe
        if i_decay == 2:
            u.stable_specie()
            self.decay(self.mass_frac)

        # here I am calculating average mass fraction for all isotopes in given mass range, and then
        # if needed calculating average over decayed.
        # warning: mass_range is bigger than used_masses range, by definition. Should I use it?
        print('average over used_masses range, not over original mass_range')
        print(used_masses[0],used_masses[len(used_masses)-1],'instead of',mass_range[0],mass_range[1])

        global average_mass_frac
        average_mass_frac = []

        if len(used_masses) >= 2:
            dm_tot = abs(used_masses[len(used_masses)-1]-used_masses[0])
            for j in range(len(u.spe)-1):
                temp = 0.
                for i in range(len(used_masses)-1):
                    dm_i = abs(used_masses[i+1]-used_masses[i])
                    temp = float(self.mass_frac[i][j]*dm_i/dm_tot) + temp
                average_mass_frac.append(temp)
            #print average_mass_frac
        elif  len(used_masses) == 1:
            print('case with 1 mass zone only, not implemented yet')

        somma = 0.
        somma = sum(average_mass_frac)
        print('departure from 1 of sum of average_mass_frac=',abs(1. - somma))

        # not let's do it over decayed also, if i_decay = 2
        if i_decay == 2:
            global average_mass_frac_decay
            average_mass_frac_decay = []
            dm_tot = abs(used_masses[len(used_masses)-1]-used_masses[0])
            #
            #print len(decayed_multi_d[0]),decayed_multi_d[0]
            for j in range(len(u.back_ind)):
                temp = 0.
                for i in range(len(used_masses)-1):
                    dm_i = abs(used_masses[i+1]-used_masses[i])
                    temp = float(decayed_multi_d[i][j]*dm_i/dm_tot) + temp
                average_mass_frac_decay.append(temp)

            somma = 0.
            somma = sum(average_mass_frac_decay)
            print('departure from 1 of sum of average_mass_frac_decay=',abs(1. - somma))

Response: Function to plot the average mass fraction of all isotopes in a given mass range.


Instruction:
Write a Python 3 function that can
return for one cycle an element name dictionary.

Response:
def _get_elem_names(self):
        """ returns for one cycle an element name dictionary."""

        import nuutils as u

        # provide library for Z versus element names, and Z for elements
        #element_name = self.se.elements
        element_name = self.elements_names
        u.give_zip_element_z_and_names(element_name)
        self.z_of_element_name = u.index_z_for_elements


Instruction:
Can you write a function in Python 3 where it
returns the decayed stable isotopes. Parameters ---------- cycle : integer The cycle.

Response:
def get_abundance_iso_decay(self,cycle):
        """
        returns the decayed stable isotopes.

        Parameters
        ----------
        cycle : integer
            The cycle.

        """

        import nuutils as u

        masses_for_this_cycle = self.se.get(cycle,'mass')
        self._read_iso_abund_marco([min(masses_for_this_cycle),max(masses_for_this_cycle)],cycle)

        u.stable_specie()
        self.decay(self.mass_frac)

        self.index_for_all_species = u.cl
        self.index_for_stable_species = u.back_ind

        self.decayed_stable_isotopes_per_cycle = decayed_multi_d

        # from here read solar abundances
        solar_factor = 2.
        u.solar('iniab1.0E-02.ppn_GN93',solar_factor)

        self.stable_isotope_identifier=u.jjdum
        self.stable_isotope_list=u.stable

        self.isotopic_production_factors=[]
        for i in range(len(masses_for_this_cycle)):
            pf_dum=[]
            jj=0
            for j in range(len(self.stable_isotope_identifier)):
                if self.stable_isotope_identifier[j] == 1:
                    pf_dum.append(float(old_div(self.mass_frac[i][self.index_for_all_species[self.stable_isotope_list
[jj].capitalize()]],u.solar_abundance[self.stable_isotope_list[jj].lower()])))
                    jj=jj+1
                #elif self.stable_isotope_identifier[j] == 0:
                #       pf_dum.append(float(0.))
            self.isotopic_production_factors.append(pf_dum)

        self.isotopic_production_factors_decayed=[]
        for i in range(len(masses_for_this_cycle)):
            pf_dum_d=[]
            jj=0
            for j in range(len(self.stable_isotope_identifier)):
                if self.stable_isotope_identifier[j] == 1:
                    pf_dum_d.append(float(old_div(self.decayed_stable_isotopes_per_cycle[i][self.index_for_stable_species[self.stable_isotope_list
[jj].upper()]],u.solar_abundance[self.stable_isotope_list[jj].lower()])))
                    jj=jj+1
            self.isotopic_production_factors_decayed.append(pf_dum_d)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_abundance_elem(self,cycle):

        import nuutils as u

        masses_for_this_cycle = self.se.get(cycle,'mass')
        self._read_iso_abund_marco([min(masses_for_this_cycle),max(masses_for_this_cycle)],cycle)

        u.stable_specie()
        self.decay(self.mass_frac)

        # provide library for Z versus element names, and Z for elements
        element_name = self.se.elements
        u.give_zip_element_z_and_names(element_name)
        # from here read solar abundances
        solar_factor = 2.
        u.solar('iniab1.0E-02.ppn_GN93',solar_factor)

        self.stable_isotope_identifier=u.jjdum
        self.stable_isotope_list=u.stable

        self.element_abundance_not_decayed=[]
        self.element_abundance_decayed =[]
        self.element_production_factors=[]
        self.element_production_factors_decayed=[]
        for i in range(len(masses_for_this_cycle)):
            mass_fractions_array_decayed = decayed_multi_d[i]
            mass_fractions_array_not_decayed = self.mass_frac[i]
            u.element_abund_marco(2,self.stable_isotope_list,self.stable_isotope_identifier,mass_fractions_array_not_decayed,mass_fractions_array_decayed)
            self.element_abundance_not_decayed.append(u.elem_abund)
            self.element_abundance_decayed.append(u.elem_abund_decayed)
            self.element_production_factors.append(u.elem_prod_fac)
            self.element_production_factors_decayed.append(u.elem_prod_fac_decayed)

Response: returns the undecayed element profile for the given cycle


Instruction:
Can you generate the documentation for the following Python 3 function
def maximum_size_bytes(self):
        return utils.max_safe(
            [device.get('CapacityBytes') for device in self.devices
             if device.get('CapacityBytes') is not None])

Response:
Gets the biggest disk drive

       .


Instruction:
Can you implement a function in Python 3 that
generates a shared access signature for the account service.

Response:
def generate_account_shared_access_signature(self, resource_types, permission,
                                        expiry, start=None, ip=None, protocol=None):
        '''
        Generates a shared access signature for the table service.
        Use the returned signature with the sas_token parameter of TableService.

        :param ResourceTypes resource_types:
            Specifies the resource types that are accessible with the account SAS.
        :param AccountPermissions permission:
            The permissions associated with the shared access signature. The
            user is restricted to operations allowed by the permissions.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has been
            specified in an associated stored access policy.
        :param expiry:
            The time at which the shared access signature becomes invalid.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has
            been specified in an associated stored access policy. Azure will always
            convert values to UTC. If a date is passed in without timezone info, it
            is assumed to be UTC.
        :type expiry: date or str
        :param start:
            The time at which the shared access signature becomes valid. If
            omitted, start time for this call is assumed to be the time when the
            storage service receives the request. Azure will always convert values
            to UTC. If a date is passed in without timezone info, it is assumed to
            be UTC.
        :type start: date or str
        :param str ip:
            Specifies an IP address or a range of IP addresses from which to accept requests.
            If the IP address from which the request originates does not match the IP address
            or address range specified on the SAS token, the request is not authenticated.
            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS
            restricts the request to those IP addresses.
        :param str protocol:
            Specifies the protocol permitted for a request made. The default value
            is https,http. See :class:`~azure.storage.models.Protocol` for possible values.
        :return: A Shared Access Signature (sas) token.
        :rtype: str
        '''
        _validate_not_none('self.account_name', self.account_name)
        _validate_not_none('self.account_key', self.account_key)

        sas = SharedAccessSignature(self.account_name, self.account_key)
        return sas.generate_account(Services.TABLE, resource_types, permission,
                                    expiry, start=start, ip=ip, protocol=protocol)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def push_power_button(self, target_value):
        if target_value not in mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV:
            msg = ('The parameter "%(parameter)s" value "%(target_value)s" is '
                   'invalid. Valid values are: %(valid_power_values)s' %
                   {'parameter': 'target_value', 'target_value': target_value,
                    'valid_power_values': (
                        mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV.keys())})
            raise exception.InvalidInputError(msg)

        value = mappings.PUSH_POWER_BUTTON_VALUE_MAP_REV[target_value]
        target_uri = (
            self._get_hpe_push_power_button_action_element().target_uri)

        self._conn.post(target_uri, data={'PushType': value})

Response: Reset the system in hpe exclusive manner.


Instruction:
Given the following Python 3 function, write the documentation
def update_persistent_boot(self, devices=[], persistent=False):
        device = PERSISTENT_BOOT_DEVICE_MAP.get(devices[0].upper())
        if device == sushy.BOOT_SOURCE_TARGET_UEFI_TARGET:
            try:
                uefi_devices = self.uefi_target_override_devices
                iscsi_device = None
                for uefi_device in uefi_devices:
                    if uefi_device is not None and 'iSCSI' in uefi_device:
                        iscsi_device = uefi_device
                        break

                if iscsi_device is None:
                    msg = 'No UEFI iSCSI bootable device found on system.'
                    raise exception.IloError(msg)

            except sushy.exceptions.SushyError as e:
                msg = ('Unable to get uefi target override devices. '
                       'Error %s') % (str(e))
                raise exception.IloError(msg)

            uefi_boot_settings = {
                'Boot': {'UefiTargetBootSourceOverride': iscsi_device}
            }
            self._conn.patch(self.path, data=uefi_boot_settings)
        elif device is None:
            device = sushy.BOOT_SOURCE_TARGET_NONE

        tenure = (sushy.BOOT_SOURCE_ENABLED_CONTINUOUS
                  if persistent else sushy.BOOT_SOURCE_ENABLED_ONCE)
        self.set_system_boot_source(device, enabled=tenure)

Response: Updates the persistent boot mode for the given list of boot devices.


Instruction:
Make a summary of the following Python 3 code
def secure_boot(self):
        return secure_boot.SecureBoot(
            self._conn, utils.get_subresource_path_by(self, 'SecureBoot'),
            redfish_version=self.redfish_version)

Response: Property to provide reference to SecureBoot instance


Instruction:
Write a Python 3 script for
returning a reference to the ethernet interfaces collection instance

Response:
def ethernet_interfaces(self):
        """Provide reference to EthernetInterfacesCollection instance"""
        return ethernet_interface.EthernetInterfaceCollection(
            self._conn,
            self._get_hpe_sub_resource_collection_path('EthernetInterfaces'),
            redfish_version=self.redfish_version)


Instruction:
Can you tell what is the following Python 3 function doing
def smart_storage(self):
        return hpe_smart_storage.HPESmartStorage(
            self._conn, utils.get_subresource_path_by(
                self, ['Oem', 'Hpe', 'Links', 'SmartStorage']),
            redfish_version=self.redfish_version)

Response: This property gets the object for smart storage. It returns an instance of HPESmartStorage


Instruction:
Explain what the following Python 3 code does
def get_smart_storage_config(self, smart_storage_config_url):
        return (smart_storage_config.
                HPESmartStorageConfig(self._conn, smart_storage_config_url,
                                      redfish_version=self.redfish_version))

Response: Returns a SmartStorageConfig Instance for each controller.


Instruction:
Explain what the following Python 3 code does
def _get_smart_storage_config_by_controller_model(self, controller_model):
        ac = self.smart_storage.array_controllers.array_controller_by_model(
            controller_model)
        if ac:
            for ssc_id in self.smart_storage_config_identities:
                ssc_obj = self.get_smart_storage_config(ssc_id)
                if ac.location == ssc_obj.location:
                    return ssc_obj

Response: Returns a SmartStorageConfig Instance for the given controller model.


Instruction:
How would you code a function in Python 3 to
check SmartStorageConfig controllers are there in hardware.

Response:
def check_smart_storage_config_ids(self):
        """Check SmartStorageConfig controllers is there in hardware.

        :raises: IloError, on an error from iLO.
        """
        if self.smart_storage_config_identities is None:
            msg = ('The Redfish controller failed to get the '
                   'SmartStorageConfig controller configurations.')
            LOG.debug(msg)
            raise exception.IloError(msg)


Instruction:
How would you explain what the following Python 3 function does
def delete_raid(self):
        self.check_smart_storage_config_ids()
        any_exceptions = []
        ld_exc_count = 0
        for config_id in self.smart_storage_config_identities:
            try:
                ssc_obj = self.get_smart_storage_config(config_id)
                ssc_obj.delete_raid()
            except exception.IloLogicalDriveNotFoundError as e:
                ld_exc_count += 1
            except sushy.exceptions.SushyError as e:
                any_exceptions.append((config_id, str(e)))

        if any_exceptions:
            msg = ('The Redfish controller failed to delete the '
                   'raid configuration in one or more controllers with '
                   'Error: %(error)s' % {'error': str(any_exceptions)})
            raise exception.IloError(msg)

        if ld_exc_count == len(self.smart_storage_config_identities):
            msg = ('No logical drives are found in any controllers. Nothing '
                   'to delete.')
            raise exception.IloLogicalDriveNotFoundError(msg)

Response: Delete the raid configuration on the hardware.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _parse_raid_config_data(self, raid_config):
        default = (
            self.smart_storage.array_controllers.get_default_controller.model)
        controllers = {default: []}
        for ld in raid_config['logical_disks']:
            if 'controller' not in ld.keys():
                controllers[default].append(ld)
            else:
                ctrl = ld['controller']
                if ctrl not in controllers:
                    controllers[ctrl] = []
                controllers[ctrl].append(ld)
        return controllers

Response: This function will parse the raid config data based on the raid controllers and logical drives.


Instruction:
Implement a Python 3 function for
creating 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>]}
        :raises: IloError, on an error from iLO.
        """
        self.check_smart_storage_config_ids()
        any_exceptions = []
        controllers = self._parse_raid_config_data(raid_config)
        # Creating raid on rest of the controllers
        for controller in controllers:
            try:
                config = {'logical_disks': controllers[controller]}
                ssc_obj = (
                    self._get_smart_storage_config_by_controller_model(
                        controller))
                if ssc_obj:
                    ssc_obj.create_raid(config)
                else:
                    members = (
                        self.smart_storage.array_controllers.get_members())
                    models = [member.model for member in members]
                    msg = ('Controller not found. Available controllers are: '
                           '%(models)s' % {'models': models})
                    any_exceptions.append((controller, msg))
            except sushy.exceptions.SushyError as e:
                any_exceptions.append((controller, str(e)))

        if any_exceptions:
            msg = ('The Redfish controller failed to create the '
                   'raid configuration for one or more controllers with '
                   'Error: %(error)s' % {'error': str(any_exceptions)})
            raise exception.IloError(msg)


Instruction:
Can you create a Python 3 function that
reads the logical drives from the system after a create raid.

Response:
def _post_create_read_raid(self, raid_config):
        """Read the logical drives from the system after post-create raid

        :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>]}
        :raises: IloLogicalDriveNotFoundError, if no controllers are configured
        :raises: IloError, if any error form iLO
        :returns: A dictionary containing list of logical disks
        """
        controllers = self._parse_raid_config_data(raid_config)
        ld_exc_count = 0
        any_exceptions = []
        config = {'logical_disks': []}
        for controller in controllers:
            try:
                ssc_obj = (
                    self._get_smart_storage_config_by_controller_model(
                        controller))
                if ssc_obj:
                    result = ssc_obj.read_raid(controller=controller)
                    config['logical_disks'].extend(result['logical_disks'])
            except exception.IloLogicalDriveNotFoundError as e:
                ld_exc_count += 1
            except sushy.exceptions.SushyError as e:
                any_exceptions.append((controller, str(e)))

        if ld_exc_count == len(controllers):
            msg = 'No logical drives are found in any controllers.'
            raise exception.IloLogicalDriveNotFoundError(msg)
        if any_exceptions:
            msg = ('The Redfish controller failed to read the '
                   'raid configuration in one or more controllers with '
                   'Error: %(error)s' % {'error': str(any_exceptions)})
            raise exception.IloError(msg)
        return config


Instruction:
Can you write a function in Python 3 where it
reads the logical drives from the system after the delete.

Response:
def _post_delete_read_raid(self):
        """Read the logical drives from the system after post-delete raid

        :raises: IloError, if any error form iLO
        :returns: Empty dictionary with format: {'logical_disks': []}
        """
        any_exceptions = []
        ssc_ids = self.smart_storage_config_identities
        config = {'logical_disks': []}
        for ssc_id in ssc_ids:
            try:
                ssc_obj = self.get_smart_storage_config(ssc_id)
                ac_obj = (
                    self.smart_storage.array_controllers.
                    array_controller_by_location(ssc_obj.location))
                if ac_obj:
                    model = ac_obj.model
                    result = ssc_obj.read_raid()
                    if result:
                        config['logical_disks'].extend(result['logical_disks'])
            except sushy.exceptions.SushyError as e:
                any_exceptions.append((model, str(e)))

        if any_exceptions:
            msg = ('The Redfish controller failed to read the '
                   'raid configuration in one or more controllers with '
                   'Error: %(error)s' % {'error': str(any_exceptions)})
            raise exception.IloError(msg)
        return config


Instruction:
Write a Python 3 function for
reading the logical drives from the system.

Response:
def read_raid(self, raid_config=None):
        """Read the logical drives from the system

        :param raid_config: None or 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>]}
        :returns: A dictionary containing list of logical disks
        """
        self.check_smart_storage_config_ids()
        if raid_config:
            # When read called after create raid, user can pass raid config
            # as a input
            result = self._post_create_read_raid(raid_config=raid_config)
        else:
            # When read called after delete raid, there will be no input
            # passed by user then
            result = self._post_delete_read_raid()
        return result


Instruction:
Write a Python 3 script to
perform the request and return response. Catches HTTPError and hands itto error handler.

Response:
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None):
        '''
        Sends the request and return response. Catches HTTPError and hands it
        to error handler
        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()

        # Apply the appropriate host based on the location mode
        self._apply_host(request, operation_context, retry_context)

        # Apply common settings to the request
        _update_request(request)

        while(True):
            try:
                try:
                    # Execute the request callback
                    if self.request_callback:
                        self.request_callback(request)

                    # Add date and auth after the callback so date doesn't get too old and
                    # authentication is still correct if signed headers are added in the request
                    # callback. This also ensures retry policies with long back offs
                    # will work as it resets the time sensitive headers.
                    _add_date_header(request)
                    self.authentication.sign_request(request)

                    # Set the request context
                    retry_context.request = request

                    # Perform the request
                    response = self._httpclient.perform_request(request)

                    # Execute the response callback
                    if self.response_callback:
                        self.response_callback(response)

                    # Set the response context
                    retry_context.response = response

                    # Parse and wrap HTTP errors in AzureHttpError which inherits from AzureException
                    if response.status >= 300:
                        # This exception will be caught by the general error handler
                        # and raised as an azure http exception
                        _http_error_handler(HTTPError(response.status, response.message, response.headers, response.body))

                    # Parse the response
                    if parser:
                        if parser_args:
                            args = [response]
                            args.extend(parser_args)
                            return parser(*args)
                        else:
                            return parser(response)
                    else:
                        return
                except AzureException as ex:
                    raise ex
                except Exception as ex:
                    if sys.version_info >= (3,):
                        # Automatic chaining in Python 3 means we keep the trace
                        raise AzureException(ex.args[0])
                    else:
                        # There isn't a good solution in 2 for keeping the stack trace
                        # in general, or that will not result in an error in 3
                        # However, we can keep the previous error type and message
                        # TODO: In the future we will log the trace
                        msg = ""
                        if len(ex.args) > 0:
                            msg = ex.args[0]
                        raise AzureException('{}: {}'.format(ex.__class__.__name__, msg))

            except AzureException as ex:
                # Decryption failures (invalid objects, invalid algorithms, data unencrypted in strict mode, etc)
                # will not be resolved with retries.
                if str(ex) == _ERROR_DECRYPTION_FAILURE:
                    raise ex
                # Determine whether a retry should be performed and if so, how
                # long to wait before performing retry.
                retry_interval = self.retry(retry_context)
                if retry_interval is not None:
                    # Execute the callback
                    if self.retry_callback:
                        self.retry_callback(retry_context)

                    # Sleep for the desired retry interval
                    sleep(retry_interval)
                else:
                    raise ex
            finally:
                # If this is a location locked operation and the location is not set,
                # this is the first request of that operation. Set the location to
                # be used for subsequent requests in the operation.
                if operation_context.location_lock and not operation_context.host_location:
                    operation_context.host_location = {retry_context.location_mode: request.host}


Instruction:
Can you tell what is the following Python 3 function doing
def _convert_json_to_entity(entry_element, property_resolver):
    ''' Convert json response to entity.

    The entity format is:
    {
       "Address":"Mountain View",
       "Age":23,
       "AmountDue":200.23,
       "CustomerCode@odata.type":"Edm.Guid",
       "CustomerCode":"c9da6455-213d-42c9-9a79-3e9149a57833",
       "CustomerSince@odata.type":"Edm.DateTime",
       "CustomerSince":"2008-07-10T00:00:00",
       "IsActive":true,
       "NumberOfOrders@odata.type":"Edm.Int64",
       "NumberOfOrders":"255",
       "PartitionKey":"mypartitionkey",
       "RowKey":"myrowkey"
    }
    '''
    entity = Entity()

    properties = {}
    edmtypes = {}
    odata = {}

    for name, value in entry_element.items():
        if name.startswith('odata.'):
            odata[name[6:]] = value
        elif name.endswith('@odata.type'):
            edmtypes[name[:-11]] = value
        else:
            properties[name] = value

    # Partition key is a known property
    partition_key = properties.pop('PartitionKey', None)
    if partition_key:
        entity['PartitionKey'] = partition_key

    # Row key is a known property
    row_key = properties.pop('RowKey', None)
    if row_key:
        entity['RowKey'] = row_key

    # Timestamp is a known property
    timestamp = properties.pop('Timestamp', None)
    if timestamp:
        entity['Timestamp'] = _from_entity_datetime(timestamp)

    for name, value in properties.items():
        mtype = edmtypes.get(name);

        # use the property resolver if present
        if property_resolver:
            mtype = property_resolver(partition_key, row_key,
                                      name, value, mtype)

            # throw if the type returned is not a valid edm type
            if mtype and mtype not in _EDM_TYPES:
                raise AzureException(_ERROR_TYPE_NOT_SUPPORTED.format(mtype))

        # Add type for Int32
        if type(value) is int:
            mtype = EdmType.INT32

        # no type info, property should parse automatically
        if not mtype:
            entity[name] = value
        else:  # need an object to hold the property
            conv = _ENTITY_TO_PYTHON_CONVERSIONS.get(mtype)
            if conv is not None:
                try:
                    property = conv(value)
                except Exception as e:
                    # throw if the type returned by the property resolver
                    # cannot be used in the conversion
                    if property_resolver:
                        raise AzureException(
                            _ERROR_INVALID_PROPERTY_RESOLVER.format(name, value, mtype))
                    else:
                        raise e
            else:
                property = EntityProperty(mtype, value)
            entity[name] = property

    # extract etag from entry
    etag = odata.get('etag')
    if timestamp:
         etag = 'W/"datetime\'' + url_quote(timestamp) + '\'"'
    entity['etag'] = etag

    return entity

Response: Convert json response to entity.


Instruction:
Create a Python 3 function to
convert the response from a JSON response to a list of tables class.

Response:
def _convert_json_response_to_tables(response):
    ''' Converts the response to tables class.
    '''
    if response is None:
        return response

    tables = _list()

    continuation = _get_continuation_from_response_headers(response)
    tables.next_marker = continuation.get('NextTableName')

    root = loads(response.body.decode('utf-8'))

    if 'TableName' in root:
        table = Table()
        table.name = root['TableName']
        tables.append(table)
    else:
        for element in root['value']:
            table = Table()
            table.name = element['TableName']
            tables.append(table)

    return tables


Instruction:
Given the following Python 3 function, write the documentation
def _convert_json_response_to_entities(response, property_resolver):
    ''' Converts the response to tables class.
    '''
    if response is None:
        return response

    entities = _list()

    entities.next_marker = _get_continuation_from_response_headers(response)

    root = loads(response.body.decode('utf-8'))

    if 'value' in root:
        for entity in root['value']:
            entities.append(_convert_json_to_entity(entity,
                                                 property_resolver))
    else:
        entities.append(_convert_json_to_entity(entity,
                                             property_resolver))

    return entities

Response: Converts the response to tables class.


Instruction:
Write a Python 3 function that can
extract the etag from the response headers.

Response:
def _extract_etag(response):
    ''' Extracts the etag from the response headers. '''
    if response and response.headers:
        for name, value in response.headers:
            if name.lower() == 'etag':
                return value

    return None


Instruction:
Make a summary of the following Python 3 code
def generate_table(self, table_name, permission=None,
                        expiry=None, start=None, id=None,
                        ip=None, protocol=None,
                        start_pk=None, start_rk=None,
                        end_pk=None, end_rk=None):
        '''
        Generates a shared access signature for the table.
        Use the returned signature with the sas_token parameter of TableService.

        :param str table_name:
            Name of table.
        :param TablePermissions permission:
            The permissions associated with the shared access signature. The
            user is restricted to operations allowed by the permissions.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has been
            specified in an associated stored access policy.
        :param expiry:
            The time at which the shared access signature becomes invalid.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has
            been specified in an associated stored access policy. Azure will always
            convert values to UTC. If a date is passed in without timezone info, it
            is assumed to be UTC.
        :type expiry: date or str
        :param start:
            The time at which the shared access signature becomes valid. If
            omitted, start time for this call is assumed to be the time when the
            storage service receives the request. Azure will always convert values
            to UTC. If a date is passed in without timezone info, it is assumed to
            be UTC.
        :type start: date or str
        :param str id:
            A unique value up to 64 characters in length that correlates to a
            stored access policy. To create a stored access policy, use
            set_blob_service_properties.
        :param str ip:
            Specifies an IP address or a range of IP addresses from which to accept requests.
            If the IP address from which the request originates does not match the IP address
            or address range specified on the SAS token, the request is not authenticated.
            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS
            restricts the request to those IP addresses.
        :param str protocol:
            Specifies the protocol permitted for a request made. The default value
            is https,http. See :class:`~azure.storage.models.Protocol` for possible values.
        :param str start_pk:
            The minimum partition key accessible with this shared access
            signature. startpk must accompany startrk. Key values are inclusive.
            If omitted, there is no lower bound on the table entities that can
            be accessed.
        :param str start_rk:
            The minimum row key accessible with this shared access signature.
            startpk must accompany startrk. Key values are inclusive. If
            omitted, there is no lower bound on the table entities that can be
            accessed.
        :param str end_pk:
            The maximum partition key accessible with this shared access
            signature. endpk must accompany endrk. Key values are inclusive. If
            omitted, there is no upper bound on the table entities that can be
            accessed.
        :param str end_rk:
            The maximum row key accessible with this shared access signature.
            endpk must accompany endrk. Key values are inclusive. If omitted,
            there is no upper bound on the table entities that can be accessed.
        '''
        sas = _SharedAccessHelper()
        sas.add_base(permission, expiry, start, ip, protocol)
        sas.add_id(id)
        sas.add_table_access_ranges(table_name, start_pk, start_rk, end_pk, end_rk)
        sas.add_resource_signature(self.account_name, self.account_key, 'table', table_name)

        return sas.get_token()

Response: Generates a shared access signature for a table.


Instruction:
Write a Python 3 function that can
generate a shared access signature for a blob.

Response:
def generate_blob(self, container_name, blob_name, permission=None,
                        expiry=None, start=None, id=None, ip=None, protocol=None,
                        cache_control=None, content_disposition=None,
                        content_encoding=None, content_language=None,
                        content_type=None):
        '''
        Generates a shared access signature for the blob.
        Use the returned signature with the sas_token parameter of any BlobService.

        :param str container_name:
            Name of container.
        :param str blob_name:
            Name of blob.
        :param BlobPermissions permission:
            The permissions associated with the shared access signature. The
            user is restricted to operations allowed by the permissions.
            Permissions must be ordered read, write, delete, list.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has been
            specified in an associated stored access policy.
        :param expiry:
            The time at which the shared access signature becomes invalid.
            Required unless an id is given referencing a stored access policy
            which contains this field. This field must be omitted if it has
            been specified in an associated stored access policy. Azure will always
            convert values to UTC. If a date is passed in without timezone info, it
            is assumed to be UTC.
        :type expiry: date or str
        :param start:
            The time at which the shared access signature becomes valid. If
            omitted, start time for this call is assumed to be the time when the
            storage service receives the request. Azure will always convert values
            to UTC. If a date is passed in without timezone info, it is assumed to
            be UTC.
        :type start: date or str
        :param str id:
            A unique value up to 64 characters in length that correlates to a
            stored access policy. To create a stored access policy, use
            set_blob_service_properties.
        :param str ip:
            Specifies an IP address or a range of IP addresses from which to accept requests.
            If the IP address from which the request originates does not match the IP address
            or address range specified on the SAS token, the request is not authenticated.
            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS
            restricts the request to those IP addresses.
        :param str protocol:
            Specifies the protocol permitted for a request made. The default value
            is https,http. See :class:`~azure.storage.models.Protocol` for possible values.
        :param str cache_control:
            Response header value for Cache-Control when resource is accessed
            using this shared access signature.
        :param str content_disposition:
            Response header value for Content-Disposition when resource is accessed
            using this shared access signature.
        :param str content_encoding:
            Response header value for Content-Encoding when resource is accessed
            using this shared access signature.
        :param str content_language:
            Response header value for Content-Language when resource is accessed
            using this shared access signature.
        :param str content_type:
            Response header value for Content-Type when resource is accessed
            using this shared access signature.
        '''
        resource_path = container_name + '/' + blob_name

        sas = _SharedAccessHelper()
        sas.add_base(permission, expiry, start, ip, protocol)
        sas.add_id(id)
        sas.add_resource('b')
        sas.add_override_response_headers(cache_control, content_disposition,
                                          content_encoding, content_language,
                                          content_type)
        sas.add_resource_signature(self.account_name, self.account_key, 'blob', resource_path)

        return sas.get_token()


Instruction:
Write a Python 3 script for
returning a generator to list the tables in the account.

Response:
def list_tables(self, num_results=None, marker=None, timeout=None):
        '''
        Returns a generator to list the tables. The generator will lazily follow
        the continuation tokens returned by the service and stop when all tables
        have been returned or num_results is reached.

        If num_results is specified and the account has more than that number of
        tables, the generator will have a populated next_marker field once it
        finishes. This marker can be used to create a new generator if more
        results are desired.

        :param int num_results:
            The maximum number of tables to return.
        :param marker:
            An opaque continuation object. This value can be retrieved from the
            next_marker field of a previous generator object if num_results was
            specified and that generator has finished enumerating results. If
            specified, this generator will begin returning results from the point
            where the previous generator stopped.
        :type marker: obj
        :param int timeout:
            The server timeout, expressed in seconds. This function may make multiple
            calls to the service in which case the timeout value specified will be
            applied to each individual call.
        :return: A generator which produces :class:`~azure.storage.models.table.Table` objects.
        :rtype: :class:`~azure.storage.models.ListGenerator`:
        '''
        kwargs = {'max_results': num_results, 'marker': marker, 'timeout': timeout}
        resp = self._list_tables(**kwargs)

        return ListGenerator(resp, self._list_tables, (), kwargs)


Instruction:
How would you explain what the following Python 3 function does
def _list_tables(self, max_results=None, marker=None, timeout=None):
        '''
        Returns a list of tables under the specified account. Makes a single list
        request to the service. Used internally by the list_tables method.

        :param int max_results:
            The maximum number of tables to return. A single list request may
            return up to 1000 tables and potentially a continuation token which
            should be followed to get additional resutls.
        :param marker:
            A dictionary which identifies the portion of the query to be
            returned with the next query operation. The operation returns a
            next_marker element within the response body if the list returned
            was not complete. This value may then be used as a query parameter
            in a subsequent call to request the next portion of the list of
            queues. The marker value is opaque to the client.
        :type marker: obj
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A list of tables, potentially with a next_marker property.
        :rtype: list of :class:`~azure.storage.models.table.Table`:
        '''
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/Tables'
        request.headers = [('Accept', TablePayloadFormat.JSON_NO_METADATA)]
        request.query = [
            ('$top', _int_to_str(max_results)),
            ('NextTableName', _to_str(marker)),
            ('timeout', _int_to_str(timeout)),
        ]

        response = self._perform_request(request)
        return _convert_json_response_to_tables(response)

Response: Returns a list of tables under the specified account.


Instruction:
How would you explain what the following Python 3 function does
def create_table(self, table_name, fail_on_exist=False, timeout=None):
        '''
        Creates a new table in the storage account.

        :param str table_name:
            The name of the table to create. The table name may contain only
            alphanumeric characters and cannot begin with a numeric character.
            It is case-insensitive and must be from 3 to 63 characters long.
        :param bool fail_on_exist:
            Specifies whether to throw an exception if the table already exists.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return:
            A boolean indicating whether the table was created. If fail_on_exist
            was set to True, this will throw instead of returning false.
        :rtype: bool
        '''
        _validate_not_none('table', table_name)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/Tables'
        request.query = [('timeout', _int_to_str(timeout))]
        request.headers = [_DEFAULT_CONTENT_TYPE_HEADER,
                           _DEFAULT_PREFER_HEADER,
                           _DEFAULT_ACCEPT_HEADER]
        request.body = _get_request_body(_convert_table_to_json(table_name))

        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

Response: Creates a new table in the storage account.


Instruction:
Explain what the following Python 3 code does
def exists(self, table_name, timeout=None):
        '''
        Returns a boolean indicating whether the table exists.

        :param str table_name:
            The name of table to check for existence.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A boolean indicating whether the table exists.
        :rtype: bool
        '''
        _validate_not_none('table_name', table_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/Tables' + "('" + table_name + "')"
        request.headers = [('Accept', TablePayloadFormat.JSON_NO_METADATA)]
        request.query = [('timeout', _int_to_str(timeout))]

        try:
            self._perform_request(request)
            return True
        except AzureHttpError as ex:
            _dont_fail_not_exist(ex)
            return False

Response: Returns a boolean indicating whether the table exists.


Instruction:
Create a Python 3 function to
return details about any stored access policies associated with a table.

Response:
def get_table_acl(self, table_name, timeout=None):
        '''
        Returns details about any stored access policies specified on the
        table that may be used with Shared Access Signatures.

        :param str table_name:
            The name of an existing table.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A dictionary of access policies associated with the table.
        :rtype: dict of str to :class:`~azure.storage.models.AccessPolicy`:
        '''
        _validate_not_none('table_name', table_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _to_str(table_name)
        request.query = [
            ('comp', 'acl'),
            ('timeout', _int_to_str(timeout)),
        ]

        response = self._perform_request(request)
        return _convert_xml_to_signed_identifiers(response.body)


Instruction:
Make a summary of the following Python 3 code
def set_table_acl(self, table_name, signed_identifiers=None, timeout=None):
        '''
        Sets stored access policies for the table that may be used with Shared
        Access Signatures.

        When you set permissions for a table, the existing permissions are replaced.
        To update the table’s permissions, call :func:`~get_table_acl` to fetch
        all access policies associated with the table, modify the access policy
        that you wish to change, and then call this function with the complete
        set of data to perform the update.

        When you establish a stored access policy on a table, it may take up to
        30 seconds to take effect. During this interval, a shared access signature
        that is associated with the stored access policy will throw an
        :class:`AzureHttpError` until the access policy becomes active.

        :param str table_name:
            The name of an existing table.
        :param signed_identifiers:
            A dictionary of access policies to associate with the table. The
            dictionary may contain up to 5 elements. An empty dictionary
            will clear the access policies set on the service.
        :type signed_identifiers: dict of str to :class:`~azure.storage.models.AccessPolicy`
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('table_name', table_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _to_str(table_name)
        request.query = [
            ('comp', 'acl'),
            ('timeout', _int_to_str(timeout)),
        ]
        request.body = _get_request_body(
            _convert_signed_identifiers_to_xml(signed_identifiers))

        self._perform_request(request)

Response: Sets the permissions for a table.


Instruction:
Make a summary of the following Python 3 code
def query_entities(self, table_name, filter=None, select=None, num_results=None,
                       marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
                       property_resolver=None, timeout=None):
        '''
        Returns a generator to list the entities in the table specified. The
        generator will lazily follow the continuation tokens returned by the
        service and stop when all entities have been returned or max_results is
        reached.

        If max_results is specified and the account has more than that number of
        entities, the generator will have a populated next_marker field once it
        finishes. This marker can be used to create a new generator if more
        results are desired.

        :param str table_name:
            The name of the table to query.
        :param str filter:
            Returns only entities that satisfy the specified filter. Note that
            no more than 15 discrete comparisons are permitted within a $filter
            string. See http://msdn.microsoft.com/en-us/library/windowsazure/dd894031.aspx
            for more information on constructing filters.
        :param str select:
            Returns only the desired properties of an entity from the set.
        :param int num_results:
            The maximum number of entities to return.
        :param marker:
            An opaque continuation object. This value can be retrieved from the
            next_marker field of a previous generator object if max_results was
            specified and that generator has finished enumerating results. If
            specified, this generator will begin returning results from the point
            where the previous generator stopped.
        :type marker: obj
        :param str accept:
            Specifies the accepted content type of the response payload. See
            :class:`~azure.storage.table.models.TablePayloadFormat` for possible
            values.
        :param property_resolver:
            A function which given the partition key, row key, property name,
            property value, and the property EdmType if returned by the service,
            returns the EdmType of the property. Generally used if accept is set
            to JSON_NO_METADATA.
        :type property_resolver: callback function in format of func(pk, rk, prop_name, prop_value, service_edm_type)
        :param int timeout:
            The server timeout, expressed in seconds. This function may make multiple
            calls to the service in which case the timeout value specified will be
            applied to each individual call.
        :return: A generator which produces :class:`~azure.storage.table.models.Entity` objects.
        :rtype: :class:`~azure.storage.models.ListGenerator`
        '''
        args = (table_name,)
        kwargs = {'filter': filter, 'select': select, 'max_results': num_results, 'marker': marker,
                  'accept': accept, 'property_resolver': property_resolver, 'timeout': timeout}
        resp = self._query_entities(*args, **kwargs)

        return ListGenerator(resp, self._query_entities, args, kwargs)

Response: Returns a generator to list the entities in the specified table.


Instruction:
Here you have a function in Python 3, explain what it does
def _query_entities(self, table_name, filter=None, select=None, max_results=None,
                       marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
                       property_resolver=None, timeout=None):
        '''
        Returns a list of entities under the specified table. Makes a single list
        request to the service. Used internally by the query_entities method.

        :param str table_name:
            The name of the table to query.
        :param str filter:
            Returns only entities that satisfy the specified filter. Note that
            no more than 15 discrete comparisons are permitted within a $filter
            string. See http://msdn.microsoft.com/en-us/library/windowsazure/dd894031.aspx
            for more information on constructing filters.
        :param str select:
            Returns only the desired properties of an entity from the set.
        :param int top:
            The maximum number of entities to return.
        :param marker:
            A dictionary which identifies the portion of the query to be
            returned with the next query operation. The operation returns a
            next_marker element within the response body if the list returned
            was not complete. This value may then be used as a query parameter
            in a subsequent call to request the next portion of the list of
            queues. The marker value is opaque to the client.
        :type marker: obj
        :param str accept:
            Specifies the accepted content type of the response payload. See
            :class:`~azure.storage.table.models.TablePayloadFormat` for possible
            values.
        :param property_resolver:
            A function which given the partition key, row key, property name,
            property value, and the property EdmType if returned by the service,
            returns the EdmType of the property. Generally used if accept is set
            to JSON_NO_METADATA.
        :type property_resolver: callback function in format of func(pk, rk, prop_name, prop_value, service_edm_type)
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A list of entities, potentially with a next_marker property.
        :rtype: list of :class:`~azure.storage.table.models.Entity`
        '''
        _validate_not_none('table_name', table_name)
        _validate_not_none('accept', accept)
        next_partition_key = None if marker is None else marker.get('nextpartitionkey')
        next_row_key = None if marker is None else marker.get('nextrowkey')

        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _to_str(table_name) + '()'
        request.headers = [('Accept', _to_str(accept))]
        request.query = [
            ('$filter', _to_str(filter)),
            ('$select', _to_str(select)),
            ('$top', _int_to_str(max_results)),
            ('NextPartitionKey', _to_str(next_partition_key)),
            ('NextRowKey', _to_str(next_row_key)),
            ('timeout', _int_to_str(timeout)),
        ]

        response = self._perform_request(request)
        return _convert_json_response_to_entities(response, property_resolver)

Response: Query the table for the specified entity.


Instruction:
Given the following Python 3 function, write the documentation
def commit_batch(self, table_name, batch, timeout=None):
        '''
        Commits a :class:`~azure.storage.table.TableBatch` request.

        :param str table_name:
            The name of the table to commit the batch to.
        :param TableBatch batch:
            The batch to commit.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A list of the batch responses corresponding to the requests in the batch.
        :rtype: list of response objects
        '''
        _validate_not_none('table_name', table_name)

        # Construct the batch request
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + '$batch'
        request.query = [('timeout', _int_to_str(timeout))]

        # Update the batch operation requests with table and client specific info
        for row_key, batch_request in batch._requests:
            batch_request.host = self._get_host()
            if batch_request.method == 'POST':
                batch_request.path = '/' + _to_str(table_name)
            else:
                batch_request.path = _get_entity_path(table_name, batch._partition_key, row_key)
            _update_request(batch_request)

        # Construct the batch body
        request.body, boundary = _convert_batch_to_json(batch._requests)
        request.headers = [('Content-Type', boundary)]

        # Perform the batch request and return the response
        response = self._perform_request(request)
        responses = _parse_batch_response(response.body)
        return responses

Response: Commits a batch operation.


Instruction:
Write a Python 3 script for
creating a batch object which can be used as a context manager. Commits the batch on exit. :param str table_name: The name of the table to commit the batch to. :param int timeout: The server timeout, expressed in seconds.

Response:
def batch(self, table_name, timeout=None):
        '''
        Creates a batch object which can be used as a context manager. Commits the batch on exit.

        :param str table_name:
            The name of the table to commit the batch to.
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        batch = TableBatch()
        yield batch
        self.commit_batch(table_name, batch, timeout=timeout)


Instruction:
How would you implement a function in Python 3 that
gets an entity from the specified table.

Response:
def get_entity(self, table_name, partition_key, row_key, select=None,
                   accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
                   property_resolver=None, timeout=None):
        '''
        Get an entity from the specified table. Throws if the entity does not exist.

        :param str table_name:
            The name of the table to get the entity from.
        :param str partition_key:
            The PartitionKey of the entity.
        :param str row_key:
            The RowKey of the entity.
        :param str select:
            Returns only the desired properties of an entity from the set.
        :param str accept:
            Specifies the accepted content type of the response payload. See
            :class:`~azure.storage.table.models.TablePayloadFormat` for possible
            values.
        :param property_resolver:
            A function which given the partition key, row key, property name,
            property value, and the property EdmType if returned by the service,
            returns the EdmType of the property. Generally used if accept is set
            to JSON_NO_METADATA.
        :type property_resolver: callback function in format of func(pk, rk, prop_name, prop_value, service_edm_type)
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: The retrieved entity.
        :rtype: :class:`~azure.storage.table.models.Entity`
        '''
        _validate_not_none('table_name', table_name)
        request = _get_entity(partition_key, row_key, select, accept)
        request.host = self._get_host()
        request.path = _get_entity_path(table_name, partition_key, row_key)
        request.query += [('timeout', _int_to_str(timeout))]

        response = self._perform_request(request)
        return _convert_json_response_to_entity(response, property_resolver)


Instruction:
How would you implement a function in Python 3 that
inserts a new entity into the specified table.

Response:
def insert_entity(self, table_name, entity, timeout=None):
        '''
        Inserts a new entity into the table. Throws if an entity with the same
        PartitionKey and RowKey already exists.

        When inserting an entity into a table, you must specify values for the
        PartitionKey and RowKey system properties. Together, these properties
        form the primary key and must be unique within the table. Both the
        PartitionKey and RowKey values must be string values; each key value may
        be up to 64 KB in size. If you are using an integer value for the key
        value, you should convert the integer to a fixed-width string, because
        they are canonically sorted. For example, you should convert the value
        1 to 0000001 to ensure proper sorting.

        :param str table_name:
            The name of the table to insert the entity into.
        :param entity:
            The entity to insert. Could be a dict or an entity object.
            Must contain a PartitionKey and a RowKey.
        :type entity: a dict or :class:`~azure.storage.table.models.Entity`
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: The etag of the inserted entity.
        :rtype: str
        '''
        _validate_not_none('table_name', table_name)
        request = _insert_entity(entity)
        request.host = self._get_host()
        request.path = '/' + _to_str(table_name)
        request.query += [('timeout', _int_to_str(timeout))]

        response = self._perform_request(request)
        return _extract_etag(response)


Instruction:
Make a summary of the following Python 3 code
def update_entity(self, table_name, entity, if_match='*', timeout=None):
        '''
        Updates an existing entity in a table. Throws if the entity does not exist.
        The update_entity operation replaces the entire entity and can be used to
        remove properties.

        :param str table_name:
            The name of the table containing the entity to update.
        :param entity:
            The entity to update. Could be a dict or an entity object.
            Must contain a PartitionKey and a RowKey.
        :type entity: a dict or :class:`~azure.storage.table.models.Entity`
        :param str if_match:
            The client may specify the ETag for the entity on the
            request in order to compare to the ETag maintained by the service
            for the purpose of optimistic concurrency. The update operation
            will be performed only if the ETag sent by the client matches the
            value maintained by the server, indicating that the entity has
            not been modified since it was retrieved by the client. To force
            an unconditional update, set If-Match to the wildcard character (*).
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: The etag of the entity.
        :rtype: str
        '''
        _validate_not_none('table_name', table_name)
        request = _update_entity(entity, if_match)
        request.host = self._get_host()
        request.path = _get_entity_path(table_name, entity['PartitionKey'], entity['RowKey'])
        request.query += [('timeout', _int_to_str(timeout))]

        response = self._perform_request(request)
        return _extract_etag(response)

Response: Updates an existing entity in a table.


Instruction:
Write a Python 3 function for
deleting an existing entity in a table.

Response:
def delete_entity(self, table_name, partition_key, row_key,
                      if_match='*', timeout=None):
        '''
        Deletes an existing entity in a table. Throws if the entity does not exist.

        When an entity is successfully deleted, the entity is immediately marked
        for deletion and is no longer accessible to clients. The entity is later
        removed from the Table service during garbage collection.

        :param str table_name:
            The name of the table containing the entity to delete.
        :param str partition_key:
            The PartitionKey of the entity.
        :param str row_key:
            The RowKey of the entity.
        :param str if_match:
            The client may specify the ETag for the entity on the
            request in order to compare to the ETag maintained by the service
            for the purpose of optimistic concurrency. The delete operation
            will be performed only if the ETag sent by the client matches the
            value maintained by the server, indicating that the entity has
            not been modified since it was retrieved by the client. To force
            an unconditional delete, set If-Match to the wildcard character (*).
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('table_name', table_name)
        request = _delete_entity(partition_key, row_key, if_match)
        request.host = self._get_host()
        request.query += [('timeout', _int_to_str(timeout))]
        request.path = _get_entity_path(table_name, partition_key, row_key)

        self._perform_request(request)


Instruction:
How would you code a function in Python 3 to
insert an existing entity or replaces an existing entity if it does not exist in the table.

Response:
def insert_or_replace_entity(self, table_name, entity, timeout=None):
        '''
        Replaces an existing entity or inserts a new entity if it does not
        exist in the table. Because this operation can insert or update an
        entity, it is also known as an "upsert" operation.

        If insert_or_replace_entity is used to replace an entity, any properties
        from the previous entity will be removed if the new entity does not define
        them.

        :param str table_name:
            The name of the table in which to insert or replace the entity.
        :param entity:
            The entity to insert or replace. Could be a dict or an entity object.
            Must contain a PartitionKey and a RowKey.
        :type entity: a dict or :class:`~azure.storage.table.models.Entity`
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: The etag of the entity.
        :rtype: str
        '''
        _validate_not_none('table_name', table_name)
        request = _insert_or_replace_entity(entity)
        request.host = self._get_host()
        request.query += [('timeout', _int_to_str(timeout))]
        request.path = _get_entity_path(table_name, entity['PartitionKey'], entity['RowKey'])

        response = self._perform_request(request)
        return _extract_etag(response)


Instruction:
Can you tell what is the following Python 3 function doing
def insert_or_merge_entity(self, table_name, entity, timeout=None):
        '''
        Merges an existing entity or inserts a new entity if it does not exist
        in the table.

        If insert_or_merge_entity is used to merge an entity, any properties from
        the previous entity will be retained if the request does not define or
        include them.

        :param str table_name:
            The name of the table in which to insert or merge the entity.
        :param entity:
            The entity to insert or merge. Could be a dict or an entity object.
            Must contain a PartitionKey and a RowKey.
        :type entity: a dict or :class:`~azure.storage.table.models.Entity`
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: The etag of the entity.
        :rtype: str
        '''
        _validate_not_none('table_name', table_name)
        request = _insert_or_merge_entity(entity)
        request.host = self._get_host()
        request.query += [('timeout', _int_to_str(timeout))]
        request.path = _get_entity_path(table_name, entity['PartitionKey'], entity['RowKey'])

        response = self._perform_request(request)
        return _extract_etag(response)

Response: Inserts an existing entity or merges a new entity.


Instruction:
Write a Python 3 script to
extract the table name from the request. uri. The request. uri has either AttributeNames or "/mytable(...)" format.

Response:
def get_request_table(self, request):
        '''
        Extracts table name from request.uri. The request.uri has either
        "/mytable(...)" or "/mytable" format.

        request:
            the request to insert, update or delete entity
        '''
        if '(' in request.path:
            pos = request.path.find('(')
            return request.path[1:pos]
        else:
            return request.path[1:]


Instruction:
Make a summary of the following Python 3 code
def get_request_partition_key(self, request):
        '''
        Extracts PartitionKey from request.body if it is a POST request or from
        request.path if it is not a POST request. Only insert operation request
        is a POST request and the PartitionKey is in the request body.

        request:
            the request to insert, update or delete entity
        '''
        if request.method == 'POST':
            doc = ETree.fromstring(request.body)
            part_key = doc.find('./atom:content/m:properties/d:PartitionKey', _etree_entity_feed_namespaces)
            if part_key is None:
                raise AzureBatchValidationError(_ERROR_CANNOT_FIND_PARTITION_KEY)
            return _get_etree_text(part_key)
        else:
            uri = url_unquote(request.path)
            pos1 = uri.find('PartitionKey=\'')
            pos2 = uri.find('\',', pos1)
            if pos1 == -1 or pos2 == -1:
                raise AzureBatchValidationError(_ERROR_CANNOT_FIND_PARTITION_KEY)
            return uri[pos1 + len('PartitionKey=\''):pos2]

Response: Extracts PartitionKey from request. body or from request. path. Only insert operation request. body is a POST request or from request. path is a DELETE request. Returns the PartitionKey.


Instruction:
Implement a function in Python 3 to
extract RowKey from request. body or from request. path. Only insert operation request. body is a POST request or from request. path is a DELETE request. Returns the RowKey of the entity that was inserted or deleted.

Response:
def get_request_row_key(self, request):
        '''
        Extracts RowKey from request.body if it is a POST request or from
        request.path if it is not a POST request. Only insert operation request
        is a POST request and the Rowkey is in the request body.

        request:
            the request to insert, update or delete entity
        '''
        if request.method == 'POST':
            doc = ETree.fromstring(request.body)
            row_key = doc.find('./atom:content/m:properties/d:RowKey', _etree_entity_feed_namespaces)
            if row_key is None:
                raise AzureBatchValidationError(_ERROR_CANNOT_FIND_ROW_KEY)
            return _get_etree_text(row_key)
        else:
            uri = url_unquote(request.path)
            pos1 = uri.find('RowKey=\'')
            pos2 = uri.find('\')', pos1)
            if pos1 == -1 or pos2 == -1:
                raise AzureBatchValidationError(_ERROR_CANNOT_FIND_ROW_KEY)
            row_key = uri[pos1 + len('RowKey=\''):pos2]
            return row_key


Instruction:
Can you create a Python 3 function that
validates that all requests have the same table name. Set the table if it is the first request for the batch operation.

Response:
def validate_request_table(self, request):
        '''
        Validates that all requests have the same table name. Set the table
        name if it is the first request for the batch operation.

        request:
            the request to insert, update or delete entity
        '''
        if self.batch_table:
            if self.get_request_table(request) != self.batch_table:
                raise AzureBatchValidationError(_ERROR_INCORRECT_TABLE_IN_BATCH)
        else:
            self.batch_table = self.get_request_table(request)


Instruction:
Given the following Python 3 function, write the documentation
def validate_request_partition_key(self, request):
        '''
        Validates that all requests have the same PartitiionKey. Set the
        PartitionKey if it is the first request for the batch operation.

        request:
            the request to insert, update or delete entity
        '''
        if self.batch_partition_key:
            if self.get_request_partition_key(request) != \
                self.batch_partition_key:
                raise AzureBatchValidationError(_ERROR_INCORRECT_PARTITION_KEY_IN_BATCH)
        else:
            self.batch_partition_key = self.get_request_partition_key(request)

Response: Validates that all requests have the same PartitiionKey. Set the batch_partition_key if not set.


Instruction:
Given the following Python 3 function, write the documentation
def validate_request_row_key(self, request):
        '''
        Validates that all requests have the different RowKey and adds RowKey
        to existing RowKey list.

        request:
            the request to insert, update or delete entity
        '''
        if self.batch_row_keys:
            if self.get_request_row_key(request) in self.batch_row_keys:
                raise AzureBatchValidationError(_ERROR_DUPLICATE_ROW_KEY_IN_BATCH)
        else:
            self.batch_row_keys.append(self.get_request_row_key(request))

Response:
Validates that all requests have the same RowKey and adds RowKey
            to existing RowKey list.


Instruction:
Can you tell what is the following Python 3 function doing
def begin_batch(self):
        '''
        Starts the batch operation. Intializes the batch variables

        is_batch:
            batch operation flag.
        batch_table:
            the table name of the batch operation
        batch_partition_key:
            the PartitionKey of the batch requests.
        batch_row_keys:
            the RowKey list of adding requests.
        batch_requests:
            the list of the requests.
        '''
        self.is_batch = True
        self.batch_table = ''
        self.batch_partition_key = ''
        self.batch_row_keys = []
        self.batch_requests = []

Response: Starts the batch operation. Intializes the batch variables and sets the flag to True.


Instruction:
Create a Python 3 function for
adding request to batch operation.

Response:
def insert_request_to_batch(self, request):
        '''
        Adds request to batch operation.

        request:
            the request to insert, update or delete entity
        '''
        self.validate_request_table(request)
        self.validate_request_partition_key(request)
        self.validate_request_row_key(request)
        self.batch_requests.append(request)