Instruction:
Write a Python 3 function that can
raise ValidationException if value is not a month. Returns the titlecased month name.

Response:
def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None):
    """Raises ValidationException if value is not a month, like 'Jan' or 'March'.
    Returns the titlecased month.

    * value (str): The value being validated as an email address.
    * blank (bool):  If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * monthNames (Mapping): A mapping of uppercase month abbreviations to month names, i.e. {'JAN': 'January', ... }. The default provides English month names.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateMonth('Jan')
    'January'
    >>> pysv.validateMonth('MARCH')
    'March'
    """

    # returns full month name, e.g. 'January'

    # Validate parameters.
    _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)

    returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
    if returnNow:
        return value

    try:
        if (monthNames == ENGLISH_MONTHS) and (1 <= int(value) <= 12): # This check here only applies to months, not when validateDayOfWeek() calls this function.
            return ENGLISH_MONTH_NAMES[int(value) - 1]
    except:
        pass # continue if the user didn't enter a number 1 to 12.

    # Both month names and month abbreviations will be at least 3 characters.
    if len(value) < 3:
        _raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg)

    if value[:3].upper() in monthNames.keys(): # check if value is a month abbreviation
        return monthNames[value[:3].upper()] # It turns out that titlecase is good for all the month.
    elif value.upper() in monthNames.values(): # check if value is a month name
        return value.title()

    _raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg)


Instruction:
Write a Python 3 function that can
raise ValidationException if value is not a day of the week such as Mon or Friday. Returns the titlecased day of the week.

Response:
def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None):
    """Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.
    Returns the titlecased day of the week.

    * value (str): The value being validated as a day of the week.
    * blank (bool):  If True, a blank string will be accepted. Defaults to False.
    * strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
    * allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
    * blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
    * dayNames (Mapping): A mapping of uppercase day abbreviations to day names, i.e. {'SUN': 'Sunday', ...} The default provides English day names.
    * excMsg (str): A custom message to use in the raised ValidationException.

    >>> import pysimplevalidate as pysv
    >>> pysv.validateDayOfWeek('mon')
    'Monday'
    >>> pysv.validateDayOfWeek('THURSday')
    'Thursday'
    """

    # TODO - reuse validateChoice for this function

    # returns full day of the week str, e.g. 'Sunday'

    # Reuses validateMonth.
    try:
        return validateMonth(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, monthNames=ENGLISH_DAYS_OF_WEEK)
    except:
        # Replace the exception message.
        _raiseValidationException(_('%r is not a day of the week') % (_errstr(value)), excMsg)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
    try:
        daysInMonth = calendar.monthrange(year, month)[1]
    except:
        raise PySimpleValidateException('invalid arguments for year and/or month')

    try:
        return validateInt(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, min=1, max=daysInMonth)
    except:
        # Replace the exception message.
        _raiseValidationException(_('%r is not a day in the month of %s %s') % (_errstr(value), ENGLISH_MONTH_NAMES[month - 1], year), excMsg)

Response: Raises ValidationException if value is not a day of the month from the given year month.


Instruction:
Explain what the following Python 3 code does
def get_level(level_string):
    levels = {'debug': logging.DEBUG, 'info': logging.INFO,
              'warning': logging.WARNING, 'error': logging.ERROR,
              'critical': logging.CRITICAL}
    try:
        level = levels[level_string.lower()]
    except KeyError:
        sys.exit('{0} is not a recognized logging level'.format(level_string))
    else:
        return level

Response: Returns an appropriate logging level integer from a string name


Instruction:
Write a Python 3 function for
configuring the logging system.

Response:
def config_logging(no_log_file, log_to, log_level, silent, verbosity):
    """
    Configures and generates a Logger object, 'openaccess_epub' based on common
    parameters used for console interface script execution in OpenAccess_EPUB.

    These parameters are:
      no_log_file
          Boolean. Disables logging to file. If set to True, log_to and
          log_level become irrelevant.
      log_to
          A string name indicating a file path for logging.
      log_level
          Logging level, one of: 'debug', 'info', 'warning', 'error', 'critical'
      silent
          Boolean
      verbosity
          Console logging level, one of: 'debug', 'info', 'warning', 'error',
          'critical

    This method currently only configures a console StreamHandler with a
    message-only Formatter.
    """

    log_level = get_level(log_level)
    console_level = get_level(verbosity)

    #We want to configure our openaccess_epub as the parent log
    log = logging.getLogger('openaccess_epub')
    log.setLevel(logging.DEBUG)  # Don't filter at the log level
    standard = logging.Formatter(STANDARD_FORMAT)
    message_only = logging.Formatter(MESSAGE_ONLY_FORMAT)

    #Only add FileHandler IF it's allowed AND we have a name for it
    if not no_log_file and log_to is not None:
        fh = logging.FileHandler(filename=log_to)
        fh.setLevel(log_level)
        fh.setFormatter(standard)
        log.addHandler(fh)

    #Add on the console StreamHandler at verbosity level if silent not set
    if not silent:
        sh_echo = logging.StreamHandler(sys.stdout)
        sh_echo.setLevel(console_level)
        sh_echo.setFormatter(message_only)
        log.addHandler(sh_echo)


Instruction:
Can you tell what is the following Python 3 function doing
def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize,
                      varExtXmin, varExtXmax, varExtYmin, varExtYmax):
    """Remap x, y, sigma parameters from pixel to degree.

    Parameters
    ----------
    vecX : 1D numpy array
        Array with possible x parametrs in pixels
    vecY : 1D numpy array
        Array with possible y parametrs in pixels
    vecPrfSd : 1D numpy array
        Array with possible sd parametrs in pixels
    tplPngSize : tuple, 2
        Pixel dimensions of the visual space in pixel (width, height).
    varExtXmin : float
        Extent of visual space from centre in negative x-direction (width)
    varExtXmax : float
        Extent of visual space from centre in positive x-direction (width)
    varExtYmin : int
        Extent of visual space from centre in negative y-direction (height)
    varExtYmax : float
        Extent of visual space from centre in positive y-direction (height)

    Returns
    -------
    vecX : 1D numpy array
        Array with possible x parametrs in degree
    vecY : 1D numpy array
        Array with possible y parametrs in degree
    vecPrfSd : 1D numpy array
        Array with possible sd parametrs in degree

    """

    # Remap modelled x-positions of the pRFs:
    vecXdgr = rmp_rng(vecX, varExtXmin, varExtXmax, varOldThrMin=0.0,
                      varOldAbsMax=(tplPngSize[0] - 1))

    # Remap modelled y-positions of the pRFs:
    vecYdgr = rmp_rng(vecY, varExtYmin, varExtYmax, varOldThrMin=0.0,
                      varOldAbsMax=(tplPngSize[1] - 1))

    # We calculate the scaling factor from pixels to degrees of visual angle to
    # separately for the x- and the y-directions (the two should be the same).
    varPix2DgrX = np.divide((varExtXmax - varExtXmin), tplPngSize[0])
    varPix2DgrY = np.divide((varExtYmax - varExtYmin), tplPngSize[1])

    # Check whether varDgr2PixX and varDgr2PixY are similar:
    strErrMsg = 'ERROR. The ratio of X and Y dimensions in ' + \
        'stimulus space (in pixels) do not agree'
    assert 0.5 > np.absolute((varPix2DgrX - varPix2DgrY)), strErrMsg

    # Convert prf sizes from degrees of visual angles to pixel
    vecPrfSdDgr = np.multiply(vecPrfSd, varPix2DgrX)

    # Return new values.
    return vecXdgr, vecYdgr, vecPrfSdDgr

Response: Remap x y sigma parameters from pixel to degree.


Instruction:
Write a Python 3 script to
create an array with all possible model parameter combinations for a given set of pRF models.

Response:
def crt_mdl_prms(tplPngSize, varNum1, varExtXmin,  varExtXmax, varNum2,
                 varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin,
                 varPrfStdMax, kwUnt='pix', kwCrd='crt'):
    """Create an array with all possible model parameter combinations

    Parameters
    ----------
    tplPngSize : tuple, 2
        Pixel dimensions of the visual space (width, height).
    varNum1 : int, positive
        Number of x-positions to model
    varExtXmin : float
        Extent of visual space from centre in negative x-direction (width)
    varExtXmax : float
        Extent of visual space from centre in positive x-direction (width)
    varNum2 : float, positive
        Number of y-positions to model.
    varExtYmin : int
        Extent of visual space from centre in negative y-direction (height)
    varExtYmax : float
        Extent of visual space from centre in positive y-direction (height)
    varNumPrfSizes : int, positive
        Number of pRF sizes to model.
    varPrfStdMin : float, positive
        Minimum pRF model size (standard deviation of 2D Gaussian)
    varPrfStdMax : float, positive
        Maximum pRF model size (standard deviation of 2D Gaussian)
    kwUnt: str
        Keyword to set the unit for model parameter combinations; model
        parameters can be in pixels ["pix"] or degrees of visual angles ["deg"]
    kwCrd: str
        Keyword to set the coordinate system for model parameter combinations;
        parameters can be in cartesian ["crt"] or polar ["pol"] coordinates

    Returns
    -------
    aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
        Model parameters (x, y, sigma) for all models.

    """

    # Number of pRF models to be created (i.e. number of possible
    # combinations of x-position, y-position, and standard deviation):
    varNumMdls = varNum1 * varNum2 * varNumPrfSizes

    # Array for the x-position, y-position, and standard deviations for
    # which pRF model time courses are going to be created, where the
    # columns correspond to: (1) the x-position, (2) the y-position, and
    # (3) the standard deviation. The parameters are in units of the
    # upsampled visual space.
    aryMdlParams = np.zeros((varNumMdls, 3), dtype=np.float32)

    # Counter for parameter array:
    varCntMdlPrms = 0

    if kwCrd == 'crt':

        # Vector with the moddeled x-positions of the pRFs:
        vecX = np.linspace(varExtXmin, varExtXmax, varNum1, endpoint=True)

        # Vector with the moddeled y-positions of the pRFs:
        vecY = np.linspace(varExtYmin, varExtYmax, varNum2, endpoint=True)

        # Vector with standard deviations pRF models (in degree of vis angle):
        vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
                               endpoint=True)

        if kwUnt == 'deg':
            # since parameters are already in degrees of visual angle,
            # we do nothing
            pass

        elif kwUnt == 'pix':
            # convert parameters to pixels
            vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
                                                     tplPngSize, varExtXmin,
                                                     varExtXmax, varExtYmin,
                                                     varExtYmax)

        else:
            print('Unknown keyword provided for possible model parameter ' +
                  'combinations: should be either pix or deg')

        # Put all combinations of x-position, y-position, and standard
        # deviations into the array:

        # Loop through x-positions:
        for idxX in range(0, varNum1):

            # Loop through y-positions:
            for idxY in range(0, varNum2):

                # Loop through standard deviations (of Gaussian pRF models):
                for idxSd in range(0, varNumPrfSizes):

                    # Place index and parameters in array:
                    aryMdlParams[varCntMdlPrms, 0] = vecX[idxX]
                    aryMdlParams[varCntMdlPrms, 1] = vecY[idxY]
                    aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]

                    # Increment parameter index:
                    varCntMdlPrms += 1

    elif kwCrd == 'pol':

        # Vector with the radial position:
        vecRad = np.linspace(0.0, varExtXmax, varNum1, endpoint=True)

        # Vector with the angular position:
        vecTht = np.linspace(0.0, 2*np.pi, varNum2, endpoint=False)

        # Get all possible combinations on the grid, using matrix indexing ij
        # of output
        aryRad, aryTht = np.meshgrid(vecRad, vecTht, indexing='ij')

        # Flatten arrays to be able to combine them with meshgrid
        vecRad = aryRad.flatten()
        vecTht = aryTht.flatten()

        # Convert from polar to cartesian
        vecX, vecY = map_pol_to_crt(vecTht, vecRad)

        # Vector with standard deviations pRF models (in degree of vis angle):
        vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
                               endpoint=True)

        if kwUnt == 'deg':
            # since parameters are already in degrees of visual angle,
            # we do nothing
            pass

        elif kwUnt == 'pix':
            # convert parameters to pixels
            vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
                                                     tplPngSize, varExtXmin,
                                                     varExtXmax, varExtYmin,
                                                     varExtYmax)
        # Put all combinations of x-position, y-position, and standard
        # deviations into the array:

        # Loop through x-positions:
        for idxXY in range(0, varNum1*varNum2):

            # Loop through standard deviations (of Gaussian pRF models):
            for idxSd in range(0, varNumPrfSizes):

                # Place index and parameters in array:
                aryMdlParams[varCntMdlPrms, 0] = vecX[idxXY]
                aryMdlParams[varCntMdlPrms, 1] = vecY[idxXY]
                aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]

                # Increment parameter index:
                varCntMdlPrms += 1

    else:
        print('Unknown keyword provided for coordinate system for model ' +
              'parameter combinations: should be either crt or pol')

    return aryMdlParams


Instruction:
Write a Python 3 script for
creating 2D Gauss models to spatial conditions.

Response:
def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt',
                lgcPrint=True):
    """Create responses of 2D Gauss models to spatial conditions.

    Parameters
    ----------
    arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions]
        All spatial conditions stacked along second axis.
    tplPngSize : tuple, 2
        Pixel dimensions of the visual space (width, height).
    aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
        Model parameters (x, y, sigma) for all models.
    varPar : int, positive
        Number of cores to parallelize over.
    strCrd, string, either 'crt' or 'pol'
        Whether model parameters are provided in cartesian or polar coordinates
    lgcPrint : boolean
        Whether print statements should be executed.

    Returns
    -------
    aryMdlCndRsp : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, n_cond]
        Responses of 2D Gauss models to spatial conditions.

    """

    if varPar == 1:
        # if the number of cores requested by the user is equal to 1,
        # we save the overhead of multiprocessing by calling aryMdlCndRsp
        # directly
        aryMdlCndRsp = cnvl_2D_gauss(0, aryMdlParams, arySptExpInf,
                                     tplPngSize, None, strCrd=strCrd)

    else:

        # The long array with all the combinations of model parameters is put
        # into separate chunks for parallelisation, using a list of arrays.
        lstMdlParams = np.array_split(aryMdlParams, varPar)

        # Create a queue to put the results in:
        queOut = mp.Queue()

        # Empty list for results from parallel processes (for pRF model
        # responses):
        lstMdlTc = [None] * varPar

        # Empty list for processes:
        lstPrcs = [None] * varPar

        if lgcPrint:
            print('---------Running parallel processes')

        # Create processes:
        for idxPrc in range(0, varPar):
            lstPrcs[idxPrc] = mp.Process(target=cnvl_2D_gauss,
                                         args=(idxPrc, lstMdlParams[idxPrc],
                                               arySptExpInf, tplPngSize, queOut
                                               ),
                                         kwargs={'strCrd': strCrd},
                                         )
            # Daemon (kills processes when exiting):
            lstPrcs[idxPrc].Daemon = True

        # Start processes:
        for idxPrc in range(0, varPar):
            lstPrcs[idxPrc].start()

        # Collect results from queue:
        for idxPrc in range(0, varPar):
            lstMdlTc[idxPrc] = queOut.get(True)

        # Join processes:
        for idxPrc in range(0, varPar):
            lstPrcs[idxPrc].join()

        if lgcPrint:
            print('---------Collecting results from parallel processes')
        # Put output arrays from parallel process into one big array
        lstMdlTc = sorted(lstMdlTc)
        aryMdlCndRsp = np.empty((0, arySptExpInf.shape[-1]))
        for idx in range(0, varPar):
            aryMdlCndRsp = np.concatenate((aryMdlCndRsp, lstMdlTc[idx][1]),
                                          axis=0)

        # Clean up:
        del(lstMdlParams)
        del(lstMdlTc)

    return aryMdlCndRsp.astype('float16')


Instruction:
Given the following Python 3 function, write the documentation
def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol,
               varTmpOvsmpl, lgcPrint=True):
    """Create temporally upsampled neural time courses.

    Parameters
    ----------
    aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
        Responses of 2D Gauss models to spatial conditions.
    aryCnd : np.array
        1D array with condition identifiers (every condition has its own int)
    aryOns : np.array, same len as aryCnd
        1D array with condition onset times in seconds.
    aryDrt : np.array, same len as aryCnd
        1D array with condition durations of different conditions in seconds.
    varTr : float, positive
        Time to repeat (TR) of the (fMRI) experiment
    varNumVol : float, positive
        Number of data point (volumes) in the (fMRI) data
    varTmpOvsmpl : float, positive
        Factor by which the time courses should be temporally upsampled.
    lgcPrint: boolean, default True
        Should print messages be sent to user?

    Returns
    -------
    aryNrlTc : 2d numpy array,
               shape [n_x_pos * n_y_pos * n_sd, varNumVol*varTmpOvsmpl]
        Neural time course models in temporally upsampled space

    Notes
    ---------
    [1] This function first creates boxcar functions based on the  conditions
        as they are specified in the temporal experiment information, provided
        by the user in the csv file. Second, it then replaces the 1s in the
        boxcar function by predicted condition values that were previously
        calculated based on the overlap between the assumed 2D Gaussian for the
        current model and the presented stimulus aperture for that condition.
        Since the 2D Gaussian is normalized, the overlap value will be between
        0 and 1.

    """

    # adjust the input, if necessary, such that input is 2D
    tplInpShp = aryMdlRsp.shape
    aryMdlRsp = aryMdlRsp.reshape((-1, aryMdlRsp.shape[-1]))

    # the first spatial condition might code the baseline (blank periods) with
    # all zeros. If this is the case, remove the first spatial condition, since
    # for temporal conditions this is removed automatically below and we need
    # temporal and sptial conditions to maych
    if np.all(aryMdlRsp[:, 0] == 0):
        if lgcPrint:
            print('------------Removed first spatial condition (all zeros)')
        aryMdlRsp = aryMdlRsp[:, 1:]

    # create boxcar functions in temporally upsampled space
    aryBxCarTmp = create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol,
                                aryExclCnd=np.array([0.]),
                                varTmpOvsmpl=varTmpOvsmpl).T

    # Make sure that aryMdlRsp and aryBxCarTmp have the same number of
    # conditions
    assert aryMdlRsp.shape[-1] == aryBxCarTmp.shape[0]

    # pre-allocate pixelwise boxcar array
    aryNrlTc = np.zeros((aryMdlRsp.shape[0], aryBxCarTmp.shape[-1]),
                        dtype='float16')
    # loop through boxcar functions of conditions
    for ind, vecCndOcc in enumerate(aryBxCarTmp):
        # get response predicted by models for this specific spatial condition
        rspValPrdByMdl = aryMdlRsp[:, ind]
        # insert predicted response value several times using broad-casting
        aryNrlTc[..., vecCndOcc.astype('bool')] = rspValPrdByMdl[:, None]

    # determine output shape
    tplOutShp = tplInpShp[:-1] + (int(varNumVol*varTmpOvsmpl), )

    return aryNrlTc.reshape(tplOutShp).astype('float16')

Response: This function creates a neural time courses in a temporary space that is compatible with the neural time courses provided by the user.


Instruction:
Can you write a function in Python 3 where it
creates all spatial x feature prf time courses for a given set of features.

Response:
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
                   switchHrfSet, tplPngSize, varPar, dctPrm=None,
                   lgcPrint=True):
    """Create all spatial x feature prf time courses.

    Parameters
    ----------
    aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
        Responses of 2D Gauss models to spatial conditions
    aryTmpExpInf: 2d numpy array, shape [unknown, 4]
        Temporal information about conditions
    varNumVol : float, positive
        Number of volumes of the (fMRI) data.
    varTr : float, positive
        Time to repeat (TR) of the (fMRI) experiment.
    varTmpOvsmpl : int, positive
        Factor by which the data hs been temporally upsampled.
    switchHrfSet : int, (1, 2, 3)
        Switch to determine which hrf basis functions are used
    tplPngSize : tuple
        Pixel dimensions of the visual space (width, height).
    varPar : int, positive
        Description of input 1.
    dctPrm : dictionary, default None
        Dictionary with customized hrf parameters. If this is None, default
        hrf parameters will be used.
    lgcPrint: boolean, default True
        Should print messages be sent to user?

    Returns
    -------
    aryNrlTcConv : 3d numpy array,
                   shape [nr of models, nr of unique feautures, varNumVol]
        Prf time course models

    """

    # Identify number of unique features
    vecFeat = np.unique(aryTmpExpInf[:, 3])
    vecFeat = vecFeat[np.nonzero(vecFeat)[0]]

    # Preallocate the output array
    aryPrfTc = np.zeros((aryMdlRsp.shape[0], 0, varNumVol),
                        dtype=np.float32)

    # Loop over unique features
    for indFtr, ftr in enumerate(vecFeat):

        if lgcPrint:
            print('---------Create prf time course model for feature ' +
                  str(ftr))
        # Derive sptial conditions, onsets and durations for this specific
        # feature
        aryTmpCnd = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 0]
        aryTmpOns = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 1]
        aryTmpDrt = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 2]

        # Create temporally upsampled neural time courses.
        aryNrlTcTmp = crt_nrl_tc(aryMdlRsp, aryTmpCnd, aryTmpOns, aryTmpDrt,
                                 varTr, varNumVol, varTmpOvsmpl,
                                 lgcPrint=lgcPrint)
        # Convolve with hrf to create model pRF time courses.
        aryPrfTcTmp = crt_prf_tc(aryNrlTcTmp, varNumVol, varTr, varTmpOvsmpl,
                                 switchHrfSet, tplPngSize, varPar,
                                 dctPrm=dctPrm, lgcPrint=lgcPrint)
        # Add temporal time course to time course that will be returned
        aryPrfTc = np.concatenate((aryPrfTc, aryPrfTcTmp), axis=1)

    return aryPrfTc


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fnd_unq_rws(A, return_index=False, return_inverse=False):

    A = np.require(A, requirements='C')
    assert A.ndim == 2, "array must be 2-dim'l"

    B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
                  return_index=return_index,
                  return_inverse=return_inverse)

    if return_index or return_inverse:
        return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
            + B[1:]
    else:
        return B.view(A.dtype).reshape((-1, A.shape[1]), order='C')

Response: Find unique rows in 2D array.


Instruction:
Explain what the following Python 3 code does
async def _request(
            self, method: str, endpoint: str, *, headers: dict = None) -> dict:
        """Make a request against air-matters.com."""
        url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)

        if not headers:
            headers = {}
        headers.update({
            'Host': DEFAULT_HOST,
            'Origin': DEFAULT_ORIGIN,
            'Referer': DEFAULT_ORIGIN,
            'User-Agent': DEFAULT_USER_AGENT,
        })

        async with self._websession.request(
                method,
                url,
                headers=headers,
        ) as resp:
            try:
                resp.raise_for_status()
                return await resp.json(content_type=None)
            except client_exceptions.ClientError as err:
                raise RequestError(
                    'Error requesting data from {0}: {1}'.format(
                        endpoint, err)) from None

Response: Make a request against air - matters. com.


Instruction:
Make a summary of the following Python 3 code
def filter_transform_response(get_response, params):

    async def decorated_filter(request, *args, **kwargs):
        response = await get_response(request, *args, **kwargs)

        if isinstance(response, HTTPResponse) and \
                not isinstance(response, Response):
            return response

        if not isinstance(response, Response):
            response = Response(response)

        return response

    return decorated_filter

Response: This filter handles the response and transforms it to a Response instance.


Instruction:
Implement a Python 3 function for
returning user report data.

Response:
async def _raw_user_report_data(self) -> list:
        """Return user report data (if accompanied by latitude/longitude)."""
        data = await self._request('get', 'map/markers')
        return [
            location for location in data
            if location['latitude'] and location['longitude']
        ]


Instruction:
Write a Python 3 function that can
return a list of states.

Response:
async def _raw_state_data(self) -> list:
        """Return a list of states."""
        data = await self._request('get', 'states')
        return [
            location for location in data
            if location['name'] != 'United States'
        ]


Instruction:
Write a Python 3 script for
getting the nearest report to a lat / lon.

Response:
async def nearest_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """Get the nearest report (with local and state info) to a lat/lon."""
        # Since user data is more granular than state or CDC data, find the
        # user report whose coordinates are closest to the provided
        # coordinates:
        nearest_user_report = get_nearest_by_coordinates(
            await self.user_reports(), 'latitude', 'longitude', latitude,
            longitude)

        try:
            # If the user report corresponds to a known state in
            # flunearyou.org's database, we can safely assume that's the
            # correct state:
            nearest_state = next((
                state for state in await self.state_data()
                if state['place_id'] == nearest_user_report['contained_by']))
        except StopIteration:
            # If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a
            # place ID), calculate the nearest state by measuring the distance
            # from the provided latitude/longitude to flunearyou.org's
            # latitude/longitude that defines each state:
            nearest_state = get_nearest_by_coordinates(
                await self.state_data(), 'lat', 'lon', latitude, longitude)

        return {'local': nearest_user_report, 'state': nearest_state}


Instruction:
Can you generate the documentation for the following Python 3 function
def initialize(self, maxsize, history=None):
        '''size specifies the maximum amount of history to keep'''
        super().__init__()

        self.maxsize = int(maxsize)
        self.history = deque(maxlen=self.maxsize)  # Preserves order history

        # If `items` are specified, then initialize with them
        if history is not None:
            for key, value in history:
                self.insert(key, value)

Response: initialize the internal state of the object


Instruction:
Given the following Python 3 function, write the documentation
def insert(self, key, value):
        '''Adds a new key-value pair. Returns any discarded values.'''

        # Add to history and catch expectorate
        if len(self.history) == self.maxsize:
            expectorate = self.history[0]
        else:
            expectorate = None

        self.history.append((key, value))

        # Add to the appropriate list of values
        if key in self:
            super().__getitem__(key).append(value)
        else:
            super().__setitem__(key, [value])

        # Clean up old values
        if expectorate is not None:
            old_key, old_value = expectorate
            super().__getitem__(old_key).pop(0)
            if len(super().__getitem__(old_key)) == 0:
                super().__delitem__(old_key)

            return (old_key, old_value)

Response: Adds a new key - value pair. Returns any discarded values.


Instruction:
Write a Python 3 script for
getting the recently inserted values up to a key

Response:
def up_to(self, key):
        '''Gets the recently inserted values up to a key'''
        for okey, ovalue in reversed(self.history):
            if okey == key:
                break
            else:
                yield ovalue


Instruction:
How would you explain what the following Python 3 function does
def resource(self, uri, methods=frozenset({'GET'}), **kwargs):
        def decorator(f):
            if kwargs.get('stream'):
                f.is_stream = kwargs['stream']
            self.add_resource(f, uri=uri, methods=methods, **kwargs)

        return decorator

Response: Decorator to add a resource route to the routing list.


Instruction:
Can you implement a function in Python 3 that
registers a resource route.

Response:
def add_resource(self, handler, uri, methods=frozenset({'GET'}),
                     **kwargs):
        """
        Register a resource route.

        :param handler: function or class instance
        :param uri: path of the URL
        :param methods: list or tuple of methods allowed
        :param host:
        :param strict_slashes:
        :param version:
        :param name: user defined route name for url_for
        :param filters: List of callable that will filter request and
                        response data
        :param validators: List of callable added to the filter list.

        :return: function or class instance
        """

        sanic_args = ('host', 'strict_slashes', 'version', 'name')
        view_kwargs = dict((k, v) for k, v in kwargs.items()
                           if k in sanic_args)

        filters = kwargs.get('filters', self.default_filters)
        validators = kwargs.get('validators', [])

        filter_list = list(filters) + list(validators)
        filter_options = {
            'filter_list': filter_list,
            'handler': handler,
            'uri': uri,
            'methods': methods
        }
        filter_options.update(kwargs)

        handler = self.init_filters(filter_list, filter_options)(handler)
        return self.add_route(handler=handler, uri=uri, methods=methods,
                              **view_kwargs)


Instruction:
How would you explain what the following Python 3 function does
def check(session, rev_id, page_id=None, radius=defaults.RADIUS,
          before=None, window=None, rvprop=None):
    """
    Checks the revert status of a revision.  With this method, you can
    determine whether an edit is a 'reverting' edit, was 'reverted' by another
    edit and/or was 'reverted_to' by another edit.

    :Parameters:
        session : :class:`mwapi.Session`
            An API session to make use of
        rev_id : int
            the ID of the revision to check
        page_id : int
            the ID of the page the revision occupies (slower if not provided)
        radius : int
            a positive integer indicating the maximum number of revisions
            that can be reverted
        before : :class:`mwtypes.Timestamp`
            if set, limits the search for *reverting* revisions to those which
            were saved before this timestamp
        window : int
            if set, limits the search for *reverting* revisions to those which
            were saved within `window` seconds after the reverted edit
        rvprop : set( str )
            a set of properties to include in revisions

    :Returns:
        A triple :class:`mwreverts.Revert` | `None`

        * reverting -- If this edit reverted other edit(s)
        * reverted -- If this edit was reverted by another edit
        * reverted_to -- If this edit was reverted to by another edit

    :Example:

        >>> import mwapi
        >>> import mwreverts.api
        >>>
        >>> session = mwapi.Session("https://en.wikipedia.org")
        >>>
        >>> def print_revert(revert):
        ...     if revert is None:
        ...         print(None)
        ...     else:
        ...         print(revert.reverting['revid'],
        ...               [r['revid'] for r in revert.reverteds],
        ...               revert.reverted_to['revid'])
        ...
        >>> reverting, reverted, reverted_to = \
        ...     mwreverts.api.check(session, 679778587)
        >>> print_revert(reverting)
        None
        >>> print_revert(reverted)
        679778743 [679778587] 679742862
        >>> print_revert(reverted_to)
        None

    """

    rev_id = int(rev_id)
    radius = int(radius)
    if radius < 1:
        raise TypeError("invalid radius.  Expected a positive integer.")

    page_id = int(page_id) if page_id is not None else None
    before = Timestamp(before) if before is not None else None

    rvprop = set(rvprop) if rvprop is not None else set()

    # If we don't have the page_id, we're going to need to look them up
    if page_id is None:
        page_id = get_page_id(session, rev_id)

    # Load history and current rev
    current_and_past_revs = list(n_edits_before(
        session,
        rev_id,
        page_id,
        n=radius + 1,
        rvprop={'ids', 'timestamp', 'sha1'} | rvprop
    ))

    if len(current_and_past_revs) < 1:
        raise KeyError("Revision {0} not found in page {1}."
                       .format(rev_id, page_id))

    current_rev, past_revs = (
        current_and_past_revs[-1],  # Current
        current_and_past_revs[:-1]  # Past revisions
    )

    if window is not None and before is None:
        before = Timestamp(current_rev['timestamp']) + window

    # Load future revisions
    future_revs = list(n_edits_after(
        session,
        rev_id + 1,
        page_id,
        n=radius,
        timestamp=before,
        rvprop={'ids', 'timestamp', 'sha1'} | rvprop
    ))

    return build_revert_tuple(
        rev_id, past_revs, current_rev, future_revs, radius)

Response: This method checks the revert status of a revision.


Instruction:
Implement a Python 3 function for
checking the revert status of a deleted revision.

Response:
def check_deleted(session, rev_id, title=None, timestamp=None,
                  radius=defaults.RADIUS, before=None, window=None,
                  rvprop=None):
    """
    Checks the revert status of a deleted revision.  With this method, you can
    determine whether an edit is a 'reverting' edit, was 'reverted' by another
    edit and/or was 'reverted_to' by another edit.

    :Parameters:
        session : :class:`mwapi.Session`
            An API session to make use of
        rev_id : int
            the ID of the revision to check
        title : str
            the title of the page the revision occupies (slower if not
            provided) Note that the MediaWiki API expects the title to
            include the namespace prefix (e.g. "User_talk:EpochFail")
        radius : int
            a positive integer indicating the maximum number of revisions
            that can be reverted
        before : :class:`mwtypes.Timestamp`
            if set, limits the search for *reverting* revisions to those which
            were saved before this timestamp
        window : int
            if set, limits the search for *reverting* revisions to those which
            were saved within `window` seconds after the reverted edit
        rvprop : set( str )
            a set of properties to include in revisions

    :Returns:
        A triple :class:`mwreverts.Revert` | `None`

        * reverting -- If this edit reverted other edit(s)
        * reverted -- If this edit was reverted by another edit
        * reverted_to -- If this edit was reverted to by another edit
    """

    rev_id = int(rev_id)
    radius = int(radius)
    if radius < 1:
        raise TypeError("invalid radius.  Expected a positive integer.")

    title = str(title) if title is not None else None
    before = Timestamp(before) if before is not None else None

    rvprop = set(rvprop) if rvprop is not None else set()

    # If we don't have the title, we're going to need to look it up
    if title is None or timestamp is None:
        title, timestamp = get_deleted_title_and_timestamp(session, rev_id)

    # Load history and current rev
    current_and_past_revs = list(n_deleted_edits_before(
        session, rev_id, title, timestamp, n=radius + 1,
        rvprop={'ids', 'timestamp', 'sha1'} | rvprop
    ))

    if len(current_and_past_revs) < 1:
        raise KeyError("Revision {0} not found in page {1}."
                       .format(rev_id, title))

    current_rev, past_revs = (
        current_and_past_revs[-1],  # Current
        current_and_past_revs[:-1]  # Past revisions
    )

    if window is not None and before is None:
        before = Timestamp(current_rev['timestamp']) + window

    # Load future revisions
    future_revs = list(n_deleted_edits_after(
        session, rev_id + 1, title, timestamp, n=radius, before=before,
        rvprop={'ids', 'timestamp', 'sha1'} | rvprop
    ))

    return build_revert_tuple(
        rev_id, past_revs, current_rev, future_revs, radius)


Instruction:
Explain what the following Python 3 code does
def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
    repo = Repo(repo_dir)
    commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
    if hide_merges:
        return [x for x in commits if not x.summary.startswith("Merge ")]
    else:
        return list(commits)

Response: Find all commits between two commit SHAs.


Instruction:
Can you tell what is the following Python 3 function doing
def get_commit_url(repo_url):
    if "github.com" in repo_url:
        return repo_url[:-4] if repo_url.endswith(".git") else repo_url
    if "git.openstack.org" in repo_url:
        uri = '/'.join(repo_url.split('/')[-2:])
        return "https://github.com/{0}".format(uri)

    # If it didn't match these conditions, just return it.
    return repo_url

Response: Determine URL to view commits for repo.


Instruction:
How would you explain what the following Python 3 function does
def get_projects(osa_repo_dir, commit):
    # Check out the correct commit SHA from the repository
    repo = Repo(osa_repo_dir)
    checkout(repo, commit)

    yaml_files = glob.glob(
        '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir)
    )
    yaml_parsed = []
    for yaml_file in yaml_files:
        with open(yaml_file, 'r') as f:
            yaml_parsed.append(yaml.load(f))

    merged_dicts = {k: v for d in yaml_parsed for k, v in d.items()}

    return normalize_yaml(merged_dicts)

Response: Get all projects from multiple YAML files.


Instruction:
Can you implement a function in Python 3 that
reads OSA role information at a particular commit.

Response:
def get_roles(osa_repo_dir, commit, role_requirements):
    """Read OSA role information at a particular commit."""
    repo = Repo(osa_repo_dir)

    checkout(repo, commit)

    log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir,
                                                       f=role_requirements))
    filename = "{0}/{1}".format(osa_repo_dir, role_requirements)
    with open(filename, 'r') as f:
        roles_yaml = yaml.load(f)

    return normalize_yaml(roles_yaml)


Instruction:
Write a Python 3 function that can
create an OAI - OSS report header for OpenStack - Ansible.

Response:
def make_osa_report(repo_dir, old_commit, new_commit,
                    args):
    """Create initial RST report header for OpenStack-Ansible."""
    update_repo(repo_dir, args.osa_repo_url, args.update)

    # Are these commits valid?
    validate_commits(repo_dir, [old_commit, new_commit])

    # Do we have a valid commit range?
    validate_commit_range(repo_dir, old_commit, new_commit)

    # Get the commits in the range
    commits = get_commits(repo_dir, old_commit, new_commit)

    # Start off our report with a header and our OpenStack-Ansible commits.
    template_vars = {
        'args': args,
        'repo': 'openstack-ansible',
        'commits': commits,
        'commit_base_url': get_commit_url(args.osa_repo_url),
        'old_sha': old_commit,
        'new_sha': new_commit
    }
    return render_template('offline-header.j2', template_vars)


Instruction:
Can you generate the documentation for the following Python 3 function
def make_report(storage_directory, old_pins, new_pins, do_update=False,
                version_mappings=None):
    """Create RST report from a list of projects/roles."""
    report = ""
    version_mappings = version_mappings or {}
    for new_pin in new_pins:
        repo_name, repo_url, commit_sha = new_pin
        commit_sha = version_mappings.get(repo_name, {}
                                          ).get(commit_sha, commit_sha)

        # Prepare our repo directory and clone the repo if needed. Only pull
        # if the user requests it.
        repo_dir = "{0}/{1}".format(storage_directory, repo_name)
        update_repo(repo_dir, repo_url, do_update)

        # Get the old SHA from the previous pins. If this pin didn't exist
        # in the previous OSA revision, skip it. This could happen with newly-
        # added projects and roles.
        try:
            commit_sha_old = next(x[2] for x in old_pins if x[0] == repo_name)
        except Exception:
            continue
        else:
            commit_sha_old = version_mappings.get(repo_name, {}
                                                  ).get(commit_sha_old,
                                                        commit_sha_old)

        # Loop through the commits and render our template.
        validate_commits(repo_dir, [commit_sha_old, commit_sha])
        commits = get_commits(repo_dir, commit_sha_old, commit_sha)
        template_vars = {
            'repo': repo_name,
            'commits': commits,
            'commit_base_url': get_commit_url(repo_url),
            'old_sha': commit_sha_old,
            'new_sha': commit_sha
        }
        rst = render_template('offline-repo-changes.j2', template_vars)
        report += rst

    return report

Response: Create a RST report from a list of projects and roles.


Instruction:
Given the following Python 3 function, write the documentation
def normalize_yaml(yaml):
    if isinstance(yaml, list):
        # Normalize the roles YAML data
        normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
                           for x in yaml]
    else:
        # Extract the project names from the roles YAML and create a list of
        # tuples.
        projects = [x[:-9] for x in yaml.keys() if x.endswith('git_repo')]
        normalized_yaml = []
        for project in projects:
            repo_url = yaml['{0}_git_repo'.format(project)]
            commit_sha = yaml['{0}_git_install_branch'.format(project)]
            normalized_yaml.append((project, repo_url, commit_sha))

    return normalized_yaml

Response: Normalize the YAML from project and role lookups.


Instruction:
How would you implement a function in Python 3 that
posts the report to a GitHub Gist and return the URL of the gist.

Response:
def post_gist(report_data, old_sha, new_sha):
    """Post the report to a GitHub Gist and return the URL of the gist."""
    payload = {
        "description": ("Changes in OpenStack-Ansible between "
                        "{0} and {1}".format(old_sha, new_sha)),
        "public": True,
        "files": {
            "osa-diff-{0}-{1}.rst".format(old_sha, new_sha): {
                "content": report_data
            }
        }
    }
    url = "https://api.github.com/gists"
    r = requests.post(url, data=json.dumps(payload))
    response = r.json()
    return response['html_url']


Instruction:
Given the following Python 3 function, write the documentation
def prepare_storage_dir(storage_directory):
    storage_directory = os.path.expanduser(storage_directory)
    if not os.path.exists(storage_directory):
        os.mkdir(storage_directory)

    return storage_directory

Response: Prepare the storage directory.


Instruction:
Can you implement a function in Python 3 that
renders a jinja template.

Response:
def render_template(template_file, template_vars):
    """Render a jinja template."""
    # Load our Jinja templates
    template_dir = "{0}/templates".format(
        os.path.dirname(os.path.abspath(__file__))
    )
    jinja_env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_dir),
        trim_blocks=True
    )
    rendered = jinja_env.get_template(template_file).render(template_vars)

    return rendered


Instruction:
Create a Python 3 function for
resetting repository and optionally update it.

Response:
def repo_pull(repo_dir, repo_url, fetch=False):
    """Reset repository and optionally update it."""
    # Make sure the repository is reset to the master branch.
    repo = Repo(repo_dir)
    repo.git.clean("-df")
    repo.git.reset("--hard")
    repo.git.checkout("master")
    repo.head.reset(index=True, working_tree=True)

    # Compile the refspec appropriately to ensure
    # that if the repo is from github it includes
    # all the refs needed, including PR's.
    refspec_list = [
        "+refs/heads/*:refs/remotes/origin/*",
        "+refs/heads/*:refs/heads/*",
        "+refs/tags/*:refs/tags/*"
    ]
    if "github.com" in repo_url:
        refspec_list.extend([
            "+refs/pull/*:refs/remotes/origin/pr/*",
            "+refs/heads/*:refs/remotes/origin/*"])

    # Only get the latest updates if requested.
    if fetch:
        repo.git.fetch(["-u", "-v", "-f",
                        repo_url,
                        refspec_list])
    return repo


Instruction:
Write a Python 3 function for
cloning the repo if it doesn t exist already otherwise update it.

Response:
def update_repo(repo_dir, repo_url, fetch=False):
    """Clone the repo if it doesn't exist already, otherwise update it."""
    repo_exists = os.path.exists(repo_dir)
    if not repo_exists:
        log.info("Cloning repo {}".format(repo_url))
        repo = repo_clone(repo_dir, repo_url)

    # Make sure the repo is properly prepared
    # and has all the refs required
    log.info("Fetching repo {} (fetch: {})".format(repo_url, fetch))
    repo = repo_pull(repo_dir, repo_url, fetch)

    return repo


Instruction:
How would you code a function in Python 3 to
test if a commit exists in the repository.

Response:
def validate_commits(repo_dir, commits):
    """Test if a commit is valid for the repository."""
    log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir))
    repo = Repo(repo_dir)
    for commit in commits:
        try:
            commit = repo.commit(commit)
        except Exception:
            msg = ("Commit {commit} could not be found in repo {repo}. "
                   "You may need to pass --update to fetch the latest "
                   "updates to the git repositories stored on "
                   "your local computer.".format(repo=repo_dir, commit=commit))
            raise exceptions.InvalidCommitException(msg)

    return True


Instruction:
Given the following Python 3 function, write the documentation
def validate_commit_range(repo_dir, old_commit, new_commit):
    # Are there any commits between the two commits that were provided?
    try:
        commits = get_commits(repo_dir, old_commit, new_commit)
    except Exception:
        commits = []
    if len(commits) == 0:
        # The user might have gotten their commits out of order. Let's flip
        # the order of the commits and try again.
        try:
            commits = get_commits(repo_dir, new_commit, old_commit)
        except Exception:
            commits = []
        if len(commits) == 0:
            # Okay, so there really are no commits between the two commits
            # provided by the user. :)
            msg = ("The commit range {0}..{1} is invalid for {2}."
                   "You may need to use the --update option to fetch the "
                   "latest updates to the git repositories stored on your "
                   "local computer.".format(old_commit, new_commit, repo_dir))
            raise exceptions.InvalidCommitRangeException(msg)
        else:
            return 'flip'

    return True

Response: Check if commit range is valid. Flip it if needed.


Instruction:
Can you tell what is the following Python 3 function doing
def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit):
    repo = Repo(osa_repo_dir)

    # Get a list of tags, sorted
    tags = repo.git.tag().split('\n')
    tags = sorted(tags, key=LooseVersion)
    # Currently major tags are being printed after rc and
    # b tags. We need to fix the list so that major
    # tags are printed before rc and b releases
    tags = _fix_tags_list(tags)

    # Find the closest tag from a given SHA
    # The tag found here is the tag that was cut
    # either on or before the given SHA
    checkout(repo, osa_old_commit)
    old_tag = repo.git.describe()

    # If the SHA given is between two release tags, then
    # 'git describe' will return a tag in form of
    # <tag>-<commitNum>-<sha>. For example:
    # 14.0.2-3-g6931e26
    # Since reno does not support this format, we need to
    # strip away the commit number and sha bits.
    if '-' in old_tag:
        old_tag = old_tag[0:old_tag.index('-')]

    # Get the nearest tag associated with the new commit
    checkout(repo, osa_new_commit)
    new_tag = repo.git.describe()
    if '-' in new_tag:
        nearest_new_tag = new_tag[0:new_tag.index('-')]
    else:
        nearest_new_tag = new_tag

    # Truncate the tags list to only include versions
    # between old_sha and new_sha. The latest release
    # is not included in this list. That version will be
    # printed separately in the following step.
    tags = tags[tags.index(old_tag):tags.index(nearest_new_tag)]

    release_notes = ""
    # Checkout the new commit, then run reno to get the latest
    # releasenotes that have been created or updated between
    # the latest release and this new commit.
    repo.git.checkout(osa_new_commit, '-f')
    reno_report_command = ['reno',
                           'report',
                           '--earliest-version',
                           nearest_new_tag]
    reno_report_p = subprocess.Popen(reno_report_command,
                                     cwd=osa_repo_dir,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
    reno_output = reno_report_p.communicate()[0].decode('UTF-8')
    release_notes += reno_output

    # We want to start with the latest packaged release first, so
    # the tags list is reversed
    for version in reversed(tags):
        # If version is an rc or b tag, and it has a major
        # release tag, then skip it. There is no need to print
        # release notes for an rc or b release unless we are
        # comparing shas between two rc or b releases.
        repo.git.checkout(version, '-f')
        # We are outputing one version at a time here
        reno_report_command = ['reno',
                               'report',
                               '--branch',
                               version,
                               '--earliest-version',
                               version]
        reno_report_p = subprocess.Popen(reno_report_command,
                                         cwd=osa_repo_dir,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE)
        reno_output = reno_report_p.communicate()[0].decode('UTF-8')
        # We need to ensure the output includes the version we are concerned
        # about.
        # This is due to https://bugs.launchpad.net/reno/+bug/1670173
        if version in reno_output:
            release_notes += reno_output

    # Clean up "Release Notes" title. We don't need this title for
    # each tagged release.
    release_notes = release_notes.replace(
        "=============\nRelease Notes\n=============",
        ""
    )
    # Replace headers that contain '=' with '~' to comply with osa-differ's
    # formatting
    release_notes = re.sub('===+', _equal_to_tilde, release_notes)
    # Replace headers that contain '-' with '#' to comply with osa-differ's
    # formatting
    release_notes = re.sub('---+', _dash_to_num, release_notes)
    return release_notes

Response: Get release notes between the two revisions.


Instruction:
Write a Python 3 script to
compare to xml.dom.minidom, lxml's treatment of text as .text and .tail attributes of elements is an oddity. It can even be a little frustrating when one is attempting to copy everything underneath some element to another element; one has to write in extra code to handle the text. This method provides the functionality of adding everything underneath the source element, in preserved order, to the destination element.

Response:
def append_all_below(destination, source, join_str=None):
    """
    Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail
    attributes of elements is an oddity. It can even be a little frustrating
    when one is attempting to copy everything underneath some element to
    another element; one has to write in extra code to handle the text. This
    method provides the functionality of adding everything underneath the
    source element, in preserved order, to the destination element.
    """
    if join_str is None:
        join_str = ' '
    if source.text is not None:  # If source has text
        if len(destination) == 0:  # Destination has no children
            if destination.text is None:  # Destination has no text
                destination.text = source.text
            else:  # Destination has a text
                destination.text = join_str.join([destination.text, source.text])
        else:  # Destination has children
            #Select last child
            last = destination[-1]
            if last.tail is None:  # Last child has no tail
                last.tail = source.text
            else:  # Last child has a tail
                last.tail = join_str.join([last.tail, source.text])
    for each_child in source:
        destination.append(deepcopy(each_child))


Instruction:
Given the following Python 3 function, write the documentation
def all_text(element):
    if element.text is None:
        text = []
    else:
        text = [element.text]
    tails = [child.tail for child in element if child.tail is not None]
    tails = [tail.strip() for tail in tails if tail.strip()]
    return ' '.join(text + tails)

Response: This method returns all text data underneath the given element.


Instruction:
Can you tell what is the following Python 3 function doing
def ns_format(element, namespaced_string):
    if ':' not in namespaced_string:
        print('This name contains no namespace, returning it unmodified: ' + namespaced_string)
        return namespaced_string
    namespace, name = namespaced_string.split(':')
    return '{' + element.nsmap[namespace] + '}' + name

Response: This method returns a convenient method for adapting a tag or attribute name to a tag or attribute name.


Instruction:
How would you explain what the following Python 3 function does
def rename_attributes(element, attrs):
    for name in attrs.keys():
        if name not in element.attrib:
            continue
        else:
            element.attrib[attrs[name]] = element.attrib.pop(name)

Response: Renames the attributes of the element.


Instruction:
Make a summary of the following Python 3 code
def replace(old, new):
    parent = old.getparent()
    parent.replace(old, new)

Response: A simple way to replace one element node with another.


Instruction:
Can you create a Python 3 function that
converts the node received to a comment in place and returns the comment element.

Response:
def comment(node):
    """
    Converts the node received to a comment, in place, and will also return the
    comment element.
    """
    parent = node.parentNode
    comment = node.ownerDocument.createComment(node.toxml())
    parent.replaceChild(comment, node)
    return comment


Instruction:
Here you have a function in Python 3, explain what it does
def uncomment(comment):
    parent = comment.parentNode
    h = html.parser.HTMLParser()
    data = h.unescape(comment.data)
    try:
        node = minidom.parseString(data).firstChild
    except xml.parsers.expat.ExpatError:  # Could not parse!
        log.error('Could not uncomment node due to parsing error!')
        return None
    else:
        parent.replaceChild(node, comment)
        return node

Response: Converts the comment node received to a non - commented element in place and returns the new node.


Instruction:
Write a Python 3 script for
serializing an element to text.

Response:
def serialize(element, strip=False):
    """
    A handy way to serialize an element to text.
    """
    text = etree.tostring(element, method='text', encoding='utf-8')
    if strip:
        text = text.strip()
    return str(text, encoding='utf-8')


Instruction:
Write a Python 3 function that can
parse the Command Line Arguments using argparse.

Response:
def get_arg_parse():
    """Parses the Command Line Arguments using argparse."""
    # Create parser object:
    objParser = argparse.ArgumentParser()

    # Add argument to namespace -config file path:
    objParser.add_argument('-config', required=True,
                           metavar='/path/to/config.csv',
                           help='Absolute file path of config file with \
                                 parameters for pRF analysis. Ignored if in \
                                 testing mode.'
                           )

    # Add argument to namespace -prior results file path:
    objParser.add_argument('-strPthPrior', required=True,
                           metavar='/path/to/my_prior_res',
                           help='Absolute file path of prior pRF results. \
                                 Ignored if in testing mode.'
                           )

    # Add argument to namespace -varNumOpt1 flag:
    objParser.add_argument('-varNumOpt1', required=True, type=int,
                           metavar='N1',
                           help='Number of radial positions.'
                           )

    # Add argument to namespace -varNumOpt2 flag:
    objParser.add_argument('-varNumOpt2', required=True, type=int,
                           metavar='N2',
                           help='Number of angular positions.'
                           )

    # Add argument to namespace -varNumOpt3 flag:
    objParser.add_argument('-varNumOpt3', default=None, metavar='N3',
                           help='Max displacement in radial direction.'
                           )

    # Add argument to namespace -lgcRstrCentre flag:
    objParser.add_argument('-lgcRstrCentre', dest='lgcRstrCentre',
                           action='store_true', default=False,
                           help='Restrict fitted models to stimulated area.')

    objParser.add_argument('-strPathHrf', default=None, required=False,
                           metavar='/path/to/custom_hrf_parameter.npy',
                           help='Path to npy file with custom hrf parameters. \
                           Ignored if in testing mode.')

    objParser.add_argument('-supsur', nargs='+',
                           help='List of floats that represent the ratio of \
                                 size neg surround to size pos center.',
                           type=float, default=None)

    # Namespace object containign arguments and values:
    objNspc = objParser.parse_args()

    return objNspc


Instruction:
Given the following Python 3 function, write the documentation
def _homogenize_data_filter(dfilter):
    if isinstance(dfilter, tuple) and (len(dfilter) == 1):
        dfilter = (dfilter[0], None)
    if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
        dfilter = (None, None)
    elif isinstance(dfilter, dict):
        dfilter = (dfilter, None)
    elif isinstance(dfilter, (list, str)) or (
        isinstance(dfilter, int) and (not isinstance(dfilter, bool))
    ):
        dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])
    elif isinstance(dfilter[0], dict) or (
        (dfilter[0] is None) and (not isinstance(dfilter[1], dict))
    ):
        pass
    else:
        dfilter = (dfilter[1], dfilter[0])
    return dfilter

Response: Make data filter definition consistent.


Instruction:
Explain what the following Python 3 code does
def _tofloat(obj):
    if "inf" in obj.lower().strip():
        return obj
    try:
        return int(obj)
    except ValueError:
        try:
            return float(obj)
        except ValueError:
            return obj

Response: Convert to float string.


Instruction:
Create a Python 3 function for
validating column identifier ( s ).

Response:
def _in_header(self, col):
        """Validate column identifier(s)."""
        # pylint: disable=R1704
        if not self._has_header:
            # Conditionally register exceptions so that they do not appear
            # in situations where has_header is always True. In this way
            # they are not auto-documented by default
            icol_ex = pexdoc.exh.addex(RuntimeError, "Invalid column specification")
        hnf_ex = pexdoc.exh.addex(ValueError, "Column *[column_identifier]* not found")
        col_list = [col] if isinstance(col, (str, int)) else col
        for col in col_list:
            edata = {"field": "column_identifier", "value": col}
            if not self._has_header:
                # Condition not subsumed in raise_exception_if
                # so that calls that always have has_header=True
                # do not pick up this exception
                icol_ex(not isinstance(col, int))
                hnf_ex((col < 0) or (col > len(self._header) - 1), edata)
            else:
                hnf_ex(
                    (isinstance(col, int) and ((col < 0) or (col > self._data_cols)))
                    or (
                        isinstance(col, str) and (col.upper() not in self._header_upper)
                    ),
                    edata,
                )
        return col_list


Instruction:
Write a Python 3 script to
validate that all columns in filter are in header.

Response:
def _validate_rfilter(self, rfilter, letter="d"):
        """Validate that all columns in filter are in header."""
        if letter == "d":
            pexdoc.exh.addai(
                "dfilter",
                (
                    (not self._has_header)
                    and any([not isinstance(item, int) for item in rfilter.keys()])
                ),
            )
        else:
            pexdoc.exh.addai(
                "rfilter",
                (
                    (not self._has_header)
                    and any([not isinstance(item, int) for item in rfilter.keys()])
                ),
            )
        for key in rfilter:
            self._in_header(key)
            rfilter[key] = (
                [rfilter[key]] if isinstance(rfilter[key], str) else rfilter[key]
            )


Instruction:
Can you tell what is the following Python 3 function doing
def data(self, filtered=False, no_empty=False):
        return self._apply_filter(filtered, no_empty)

Response: r Returns the file data.


Instruction:
Can you generate the documentation for the following Python 3 function
def header(self, filtered=False):
        return (
            self._header
            if (not filtered) or (filtered and self._cfilter is None)
            else self._cfilter
        )

Response: r Returns the data header.


Instruction:
How would you explain what the following Python 3 function does
def write(self, fname=None, filtered=False, header=True, append=False):
        # pylint: disable=R0913
        write_ex = pexdoc.exh.addex(ValueError, "There is no data to save to file")
        fname = self._fname if fname is None else fname
        data = self.data(filtered=filtered)
        write_ex((len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)))
        if header:
            header = [header] if isinstance(header, str) else header
            cfilter = self._gen_col_index(filtered=filtered)
            filtered_header = (
                [self._header[item] for item in cfilter]
                if self._has_header
                else cfilter
            )
            file_header = filtered_header if isinstance(header, bool) else header
        # Convert None's to ''
        data = [["''" if item is None else item for item in row] for row in data]
        _write_int(fname, [file_header] + data if header else data, append=append)

Response: r Write the data to a specified comma - separated values file.


Instruction:
Can you generate the documentation for the following Python 3 function
def model_creation(dicCnfg, varRat=None, strPathHrf=None):
    # *************************************************************************
    # *** Load parameters from config file

    # Load config parameters from dictionary into namespace:
    cfg = cls_set_config(dicCnfg)
    # *************************************************************************

    if cfg.lgcCrteMdl:

        # *********************************************************************
        # *** Load spatial condition information

        print('------Load spatial condition information')

        arySptExpInf = np.load(cfg.strSptExpInf)

        # Here we assume scientific convention and orientation of images where
        # the origin should fall in the lower left corner, the x-axis occupies
        # the width and the y-axis occupies the height dimension of the screen.
        # We also assume that the first dimension that the user provides
        # indexes x and the second indexes the y-axis. Since python is column
        # major (i.e. first indexes columns, only then rows), we need to rotate
        # arySptExpInf by 90 degrees rightward. This will insure that with the
        # 0th axis we index the scientific x-axis and higher values move us to
        # the right on that x-axis. It will also ensure that the 1st
        # python axis indexes the scientific y-axis and higher values will
        # move us up.
        arySptExpInf = np.rot90(arySptExpInf, k=3)

        # Calculate the areas that were stimulated during the experiment
        aryStimArea = np.sum(arySptExpInf, axis=-1).astype(np.bool)

        # *********************************************************************

        # *********************************************************************
        # *** Load temporal condition information

        print('------Load temporal condition information')

        aryTmpExpInf = np.load(cfg.strTmpExpInf)
        # add fourth column to make it appropriate for pyprf_feature
        if aryTmpExpInf.shape[-1] == 3:
            print('---------Added fourth column')
            vecNewCol = np.greater(aryTmpExpInf[:, 0], 0).astype(np.float16)
            aryTmpExpInf = np.concatenate(
                (aryTmpExpInf, np.expand_dims(vecNewCol, axis=1)), axis=1)

        # *********************************************************************

        # *********************************************************************
        # *** Create model parameter combination, for now in pixel.
        aryMdlParams = crt_mdl_prms((int(cfg.varVslSpcSzeX),
                                     int(cfg.varVslSpcSzeY)), cfg.varNum1,
                                    cfg.varExtXmin, cfg.varExtXmax,
                                    cfg.varNum2, cfg.varExtYmin,
                                    cfg.varExtYmax, cfg.varNumPrfSizes,
                                    cfg.varPrfStdMin, cfg.varPrfStdMax,
                                    kwUnt='pix', kwCrd=cfg.strKwCrd)

        # If desired by user, also create model parameters for supp surround
        if varRat is not None:
            aryMdlParamsSur = np.copy(aryMdlParams)
            aryMdlParamsSur[:, 2] = aryMdlParamsSur[:, 2] * varRat

        # Exclude model parameters whose prf center would lie outside the
        # stimulated area
        print('------Exclude model params with prf center outside stim area')
        varNumMdlBfr = aryMdlParams.shape[0]
        # Get logical for model inclusion
        lgcMdlInc = aryStimArea[aryMdlParams[:, 0].astype(np.int32),
                                aryMdlParams[:, 1].astype(np.int32)]
        # Exclude models with prf center outside stimulated area
        aryMdlParams = aryMdlParams[lgcMdlInc, :]
        # Also apply the logical to the surround parameters, if they exist
        if varRat is not None:
            aryMdlParamsSur = aryMdlParamsSur[lgcMdlInc, :]

        print('---------Number of models excluded: ' +
              str(varNumMdlBfr-aryMdlParams.shape[0]))

        # *********************************************************************

        # *********************************************************************
        # *** Create 2D Gauss model responses to spatial conditions.

        print('------Create 2D Gauss model responses to spatial conditions')

        aryMdlRsp = crt_mdl_rsp(arySptExpInf, (int(cfg.varVslSpcSzeX),
                                               int(cfg.varVslSpcSzeY)),
                                aryMdlParams, cfg.varPar)

        # If desired by user, also create model responses for supp surround
        if varRat is not None:
            aryMdlRspSur = crt_mdl_rsp(arySptExpInf, (int(cfg.varVslSpcSzeX),
                                                      int(cfg.varVslSpcSzeY)),
                                       aryMdlParamsSur, cfg.varPar)

        # Delete array to save memory
        del(arySptExpInf)

        # *********************************************************************

        # *********************************************************************
        # *** Create prf time course models

        print('------Create prf time course models')

        # Check whether path to npy file with hrf parameters was provided
        if strPathHrf is not None:
            print('---------Load custom hrf parameters')
            aryCstPrm = np.load(strPathHrf)
            dctPrm = {}
            dctPrm['peak_delay'] = aryCstPrm[0]
            dctPrm['under_delay'] = aryCstPrm[1]
            dctPrm['peak_disp'] = aryCstPrm[2]
            dctPrm['under_disp'] = aryCstPrm[3]
            dctPrm['p_u_ratio'] = aryCstPrm[4]
        # If not, set dctPrm to None, which will result in default hrf params
        else:
            print('---------Use default hrf parameters')
            dctPrm = None

        aryPrfTc = crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, cfg.varNumVol,
                                  cfg.varTr, cfg.varTmpOvsmpl,
                                  cfg.switchHrfSet, (int(cfg.varVslSpcSzeX),
                                                     int(cfg.varVslSpcSzeY)),
                                  cfg.varPar, dctPrm=dctPrm)

        # If desired by user, create prf time course models for supp surround
        if varRat is not None:
            print('---------Add suppressive surround')
            aryPrfTcSur = crt_prf_ftr_tc(aryMdlRspSur, aryTmpExpInf,
                                         cfg.varNumVol, cfg.varTr,
                                         cfg.varTmpOvsmpl, cfg.switchHrfSet,
                                         (int(cfg.varVslSpcSzeX),
                                          int(cfg.varVslSpcSzeY)),
                                         cfg.varPar, dctPrm=dctPrm)
            # Concatenate aryPrfTc and aryPrfTcSur
            aryPrfTc = np.concatenate((aryPrfTc, aryPrfTcSur), axis=1)

        # *********************************************************************

        # *********************************************************************
        # *** Save pRF time course models, corresponding params and responses

        print('------Save pRF time course models to disk')

        # Prepare file name extensions
        strNmeExtMdl = ''
        strNmeExtPrm = '_params'
        strNmeExtRsp = '_mdlRsp'
        strNmeExtMdlInc = '_lgcMdlInc'

        # Check whether extensions need to be modified with ratio name
        if varRat is not None:
            strNmeExtMdl = strNmeExtMdl + '_' + str(varRat)
            strNmeExtPrm = strNmeExtPrm + '_' + str(varRat)
            strNmeExtRsp = strNmeExtRsp + '_' + str(varRat)
            # Also include model the parameters and responses of the surround
            # For the pRF time course models, the surround is included above
            aryMdlParams = np.stack((aryMdlParams, aryMdlParamsSur),
                                    axis=1)
            aryMdlRsp = np.stack((aryMdlRsp, aryMdlRspSur),
                                 axis=1)
            # Append the npy file name for model exlusion in unstimulated area
            # with general _supsur suffic since it does not depend on specific
            # surround
            strNmeExtMdlInc = '_supsur' + strNmeExtMdlInc

        # Save pRF time course models
        np.save(cfg.strPathMdl + strNmeExtMdl, aryPrfTc)
        # Save the corresponding model parameters
        np.save(cfg.strPathMdl + strNmeExtPrm, aryMdlParams)
        # Save the corresponding model responses
        np.save(cfg.strPathMdl + strNmeExtRsp, aryMdlRsp)

        # Save logical for parameter exclusion in unstimulated area
        np.save(cfg.strPathMdl + strNmeExtMdlInc, lgcMdlInc)

        del(aryMdlParams)
        del(aryMdlRsp)

        # *********************************************************************

    else:

        # *********************************************************************
        # %% Load existing pRF time course models

        print('------Load pRF time course models from disk')

        # Load the file:
        aryPrfTc = np.load((cfg.strPathMdl + '.npy'))

        # Check whether pRF time course model matrix has the expected
        # dimensions:
        vecPrfTcShp = aryPrfTc.shape

        # Logical test for correct dimensions:
        strErrMsg = ('---Error: Dimensions of specified pRF time course ' +
                     'models do not agree with specified model parameters')
        assert vecPrfTcShp[0] == cfg.varNum1 * \
            cfg.varNum2 * cfg.varNumPrfSizes, strErrMsg
        assert vecPrfTcShp[-1] == cfg.varNumVol, strErrMsg
        # Check number of feature. If fitting is performed with sup surround,
        # number of features will be twice as many as simple fitting
        if varRat is None:
            assert vecPrfTcShp[1] == cfg.switchHrfSet, strErrMsg
        else:
            assert vecPrfTcShp[1] == cfg.switchHrfSet*2, strErrMsg

        # Load logical for parameter exclusion in unstimulated area
        lgcMdlInc = np.load(cfg.strPathMdl + '_lgcMdlInc.npy')

    # *************************************************************************

    return aryPrfTc, lgcMdlInc

Response: Create or load pRF model time courses.


Instruction:
How would you explain what the following Python 3 function does
def register(self, CorpNum, cashbill, UserID=None):
        if cashbill == None:
            raise PopbillException(-99999999, "현금영수증 정보가 입력되지 않았습니다.")

        postData = self._stringtify(cashbill)

        return self._httppost('/Cashbill', postData, CorpNum, UserID)

Response: 요청처트 정보 요청처트 정보 요청처트 정보 요청처트 정보 요청처트 정�


Instruction:
Here you have a function in Python 3, explain what it does
def update(self, CorpNum, MgtKey, cashbill, UserID=None):
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
        if cashbill == None:
            raise PopbillException(-99999999, "현금영수증 정보가 입력되지 않았습니다.")

        postData = self._stringtify(cashbill)

        return self._httppost('/Cashbill/' + MgtKey, postData, CorpNum, UserID, "PATCH")

Response: A method to update a single entry in a particular resource.


Instruction:
Write a Python 3 function that can
issue a new entry in the specified resource.

Response:
def issue(self, CorpNum, MgtKey, Memo=None, UserID=None):
        """ 발행
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKey : 원본 현금영수증 문서관리번호
                Memo : 발행 메모
                UserID : 팝빌회원 아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """

        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        postData = ""
        req = {}

        if Memo != None or Memo != '':
            req["memo"] = Memo

        postData = self._stringtify(req)

        return self._httppost('/Cashbill/' + MgtKey, postData, CorpNum, UserID, "ISSUE")


Instruction:
Given the following Python 3 function, write the documentation
def delete(self, CorpNum, MgtKey, UserID=None):

        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httppost('/Cashbill/' + MgtKey, '', CorpNum, UserID, "DELETE")

Response: 삭제 제 영수증 현금영수증 서 정보 않았습니다.


Instruction:
Can you generate the documentation for the following Python 3 function
def getInfo(self, CorpNum, MgtKey):

        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httpget('/Cashbill/' + MgtKey, CorpNum)

Response: Get information about a particular item.


Instruction:
Create a Python 3 function to
get the details of a particular item.

Response:
def getDetailInfo(self, CorpNum, MgtKey):
        """ 상세정보 조회
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKey : 문서관리번호
            return
                문서 상세정보 object
            raise
                PopbillException
        """

        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httpget('/Cashbill/' + MgtKey + '?Detail', CorpNum)


Instruction:
Can you generate the documentation for the following Python 3 function
def getLogs(self, CorpNum, MgtKey):
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httpget('/Cashbill/' + MgtKey + '/Logs', CorpNum)

Response:
문서이력 조회
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKey : 문서관리번호
            return
                문서 이력 목록 as List
            raise
                PopbillException


Instruction:
Make a summary of the following Python 3 code
def updateEmailConfig(self, Corpnum, EmailType, SendYN, UserID=None):
        if EmailType == None or EmailType == '':
            raise PopbillException(-99999999, "메일전송 타입이 입력되지 않았습니다.")

        if SendYN == None or SendYN == '':
            raise PopbillException(-99999999, "메일전송 여부 항목이 입력되지 않았습니다.")

        uri = "/Cashbill/EmailSendConfig?EmailType=" + EmailType + "&SendYN=" + str(SendYN)
        return self._httppost(uri, "", Corpnum, UserID)

Response: 전송 요청한 정보 요청한 정보 요청한 정보 요청한 정보 요청한 정보 요청해요과과과 요자 정보 요자 정보 요자 정보 요자 정보 요요과 요요자 정보 요자 정보 요자 정보 정보정보정보요자 자 정보요요요요요요요요요자 요자 정보 요자 정보 정보요요요자 자 요요요요요요요요요요요요요요요요요요요요요요요자 자 요요요요요요자 자 요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요요� 요요요� 요요� 요요�요�요�요�요�요��


Instruction:
Make a summary of the following Python 3 code
def list(self, request):
        pipeline = [{'$match': request.args.pop('match', {})}]

        sort = request.args.pop('sort', {})
        if sort:
            pipeline.append({'$sort': sort})

        project = request.args.pop('project', {})
        if project:
            pipeline.append({'$project': project})

        return Response(serialize(self.collection.aggregate(pipeline)))

Response: Returns the list of documents found on the collection


Instruction:
Write a Python 3 script to
create a new document based on the given data.

Response:
def create(self, request):
        """
        Creates a new document based on the given data
        """
        document = self.collection(request.json)
        document.created_at = datetime.utcnow()
        document.updated_at = document.created_at

        created = document.insert()
        return Response(
            response=serialize(created),
            status=(
                201 if not all(
                    key in created for key in [
                        'error_code', 'error_type', 'error_message'
                    ]
                ) else 400
            )
        )


Instruction:
Create a Python 3 function for
retrieving the document with the given _id or 404

Response:
def retrieve(self, request, _id):
        """
        Returns the document containing the given _id or 404
        """
        _id = deserialize(_id)

        retrieved = self.collection.find_one({'_id': _id})
        if retrieved:
            return Response(serialize(retrieved))
        else:
            return Response(
                response=serialize(
                    DocumentNotFoundError(self.collection.__name__, _id)
                ),
                status=400
            )


Instruction:
How would you implement a function in Python 3 that
updates the document with the given _id using the given data

Response:
def update(self, request, _id):
        """
        Updates the document with the given _id using the given data
        """
        _id = deserialize(_id)

        to_update = self.collection.find_one({'_id': _id})
        if to_update:
            document = self.collection(dict(to_update, **request.json))
            document.updated_at = datetime.utcnow()

            updated = document.update()
            return Response(
                response=serialize(updated),
                status=(
                    200 if not all(
                        key in updated for key in [
                            'error_code', 'error_type', 'error_message'
                        ]
                    ) else 400
                )
            )
        else:
            return Response(
                response=serialize(
                    DocumentNotFoundError(self.collection.__name__, _id)
                ),
                status=400
            )


Instruction:
Write a Python 3 function for
deleting the document with the given _id if it exists.

Response:
def delete(self, request, _id):
        """
        Deletes the document with the given _id if it exists
        """
        _id = deserialize(_id)

        to_delete = self.collection.get({'_id': _id})
        if to_delete:
            deleted = to_delete.delete()

            return Response(
                response=serialize(deleted),
                status=(
                    200 if not all(
                        key in deleted for key in [
                            'error_code', 'error_type', 'error_message'
                        ]
                    ) else 400
                )
            )
        else:
            return Response(
                response=serialize(
                    DocumentNotFoundError(self.collection.__name__, _id)
                ),
                status=404
            )


Instruction:
Given the following Python 3 function, write the documentation
def with_reactor(*dec_args, **dec_kwargs):

    # This method takes care of the decorator protocol, it
    # distinguishes between using the decorator with brackets
    # and without brackets. It then calls `_twisted_test_sync()`.

    if len(dec_args) == 1 and callable(dec_args[0]) and not dec_kwargs:
        # decorator used without brackets:
        #   @twisted_test
        #   def test_xxx():
        #     ....
        callee = dec_args[0]
        dec_args = ()
        dec_kwargs = {}

        @functools.wraps(callee)
        def wrapper(*call_args, **call_kwargs):
            return _twisted_test_sync(callee, call_args, call_kwargs)
        return wrapper

    else:
        # decorator used with brackets:
        #   @twisted_test(*dec_args, **dec_args)
        #   def test_xxx():
        #     ....
        def decorator(callee):
            @functools.wraps(callee)
            def wrapper(*call_args, **call_kwargs):
                return _twisted_test_sync(callee, call_args, call_kwargs, *dec_args, **dec_kwargs)
            return wrapper
        return decorator

Response: Decorator for test functions that require a running reactor.


Instruction:
Create a Python 3 function to
start the twisted reactor if it is not running already.

Response:
def _ensure_reactor_running():
    """
    Starts the twisted reactor if it is not running already.

    The reactor is started in a new daemon-thread.

    Has to perform dirty hacks so that twisted can register
    signals even if it is not running in the main-thread.
    """
    if not reactor.running:

        # Some of the `signal` API can only be called
        # from the main-thread. So we do a dirty workaround.
        #
        # `signal.signal()` and `signal.wakeup_fd_capture()`
        # are temporarily monkey-patched while the reactor is
        # starting.
        #
        # The patched functions record the invocations in
        # `signal_registrations`.
        #
        # Once the reactor is started, the main-thread
        # is used to playback the recorded invocations.

        signal_registrations = []

        # do the monkey patching
        def signal_capture(*args, **kwargs):
            signal_registrations.append((orig_signal, args, kwargs))
        def set_wakeup_fd_capture(*args, **kwargs):
            signal_registrations.append((orig_set_wakeup_fd, args, kwargs))
        orig_signal = signal.signal
        signal.signal = signal_capture
        orig_set_wakeup_fd = signal.set_wakeup_fd
        signal.set_wakeup_fd = set_wakeup_fd_capture

        # start the reactor in a daemon-thread
        reactor_thread = threading.Thread(target=reactor.run, name="reactor")
        reactor_thread.daemon = True
        reactor_thread.start()
        while not reactor.running:
            time.sleep(0.01)

        # Give the reactor a moment to register the signals.
        # Apparently the 'running' flag is set before that.
        time.sleep(0.01)

        # Undo the monkey-paching
        signal.signal = orig_signal
        signal.set_wakeup_fd = orig_set_wakeup_fd

        # Playback the recorded calls
        for func, args, kwargs in signal_registrations:
            func(*args, **kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def _timeoutDeferred(deferred, timeout):
    delayedCall = reactor.callLater(timeout, deferred.cancel)
    def gotResult(result):
        if delayedCall.active():
            delayedCall.cancel()
        return result
    deferred.addBoth(gotResult)

Response: Cancels the given deferred after the given time.