Instruction:
Make a summary of the following Python 3 code
def draw(self,N=1.5):
        while N>0.5:
            for (l,mvmt) in self.ordering_step():
                pass
            N = N-1
        if N>0:
            for (l,mvmt) in self.ordering_step(oneway=True):
                pass
        self.setxy()
        self.draw_edges()

Response: draws every node coordinates after converging to optimal ordering by N - 1. 5 rounds and performs edge routing.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def rank_all(self,roots,optimize=False):
        self._edge_inverter()
        r = [x for x in self.g.sV if (len(x.e_in())==0 and x not in roots)]
        self._rank_init(roots+r)
        if optimize: self._rank_optimize()
        self._edge_inverter()

Response: Computes the rank of all vertices in the graph.


Instruction:
Implement a function in Python 3 to
initialize the rank of the unranked list of vertices and all .

Response:
def _rank_init(self,unranked):
        """Computes rank of provided unranked list of vertices and all
           their children. A vertex will be asign a rank when all its
           inward edges have been *scanned*. When a vertex is asigned
           a rank, its outward edges are marked *scanned*.
        """
        assert self.dag
        scan = {}
        # set rank of unranked based on its in-edges vertices ranks:
        while len(unranked)>0:
            l = []
            for v in unranked:
                self.setrank(v)
                # mark out-edges has scan-able:
                for e in v.e_out(): scan[e]=True
                # check if out-vertices are rank-able:
                for x in v.N(+1):
                    if not (False in [scan.get(e,False) for e in x.e_in()]):
                        if x not in l: l.append(x)
            unranked=l


Instruction:
Write a Python 3 script to
optimize ranking by pushing long edges toward lower layers as much as possible.

Response:
def _rank_optimize(self):
        """optimize ranking by pushing long edges toward lower layers as much as possible.
        see other interersting network flow solver to minimize total edge length
        (http://jgaa.info/accepted/2005/EiglspergerSiebenhallerKaufmann2005.9.3.pdf)
        """
        assert self.dag
        for l in reversed(self.layers):
            for v in l:
                gv = self.grx[v]
                for x in v.N(-1):
                   if all((self.grx[y].rank>=gv.rank for y in x.N(+1))):
                        gx = self.grx[x]
                        self.layers[gx.rank].remove(x)
                        gx.rank = gv.rank-1
                        self.layers[gv.rank-1].append(x)


Instruction:
Write a Python 3 script for
setting rank value for vertex v and add it to the corresponding layer.

Response:
def setrank(self,v):
        """set rank value for vertex v and add it to the corresponding layer.
           The Layer is created if it is the first vertex with this rank.
        """
        assert self.dag
        r=max([self.grx[x].rank for x in v.N(-1)]+[-1])+1
        self.grx[v].rank=r
        # add it to its layer:
        try:
            self.layers[r].append(v)
        except IndexError:
            assert r==len(self.layers)
            self.layers.append(Layer([v]))


Instruction:
Can you tell what is the following Python 3 function doing
def dummyctrl(self,r,ctrl):
        dv = DummyVertex(r)
        dv.view.w,dv.view.h=self.dw,self.dh
        self.grx[dv] = dv
        dv.ctrl = ctrl
        ctrl[r] = dv
        self.layers[r].append(dv)
        return dv

Response: creates a DummyVertex at rank r inserted in the ctrl dict and adds it to the edge s control vertices and returns it


Instruction:
Here you have a function in Python 3, explain what it does
def setdummies(self,e):
        v0,v1 = e.v
        r0,r1 = self.grx[v0].rank,self.grx[v1].rank
        if r0>r1:
            assert e in self.alt_e
            v0,v1 = v1,v0
            r0,r1 = r1,r0
        if (r1-r0)>1:
            # "dummy vertices" are stored in the edge ctrl dict,
            # keyed by their rank in layers.
            ctrl=self.ctrls[e]={}
            ctrl[r0]=v0
            ctrl[r1]=v1
            for r in xrange(r0+1,r1):
                self.dummyctrl(r,ctrl)

Response: creates and defines all needed dummy vertices for edge e.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ordering_step(self,oneway=False):
        self.dirv=-1
        crossings = 0
        for l in self.layers:
            mvmt = l.order()
            crossings += mvmt
            yield (l,mvmt)
        if oneway or (crossings == 0):
            return
        self.dirv=+1
        while l:
            mvmt = l.order()
            yield (l,mvmt)
            l = l.nextlayer()

Response: iterator that computes all vertices ordering in the layers.


Instruction:
Write a Python 3 script to
compute all vertex coordinates using Brandes & Kopf.

Response:
def setxy(self):
        """computes all vertex coordinates (x,y) using
        an algorithm by Brandes & Kopf.
        """
        self._edge_inverter()
        self._detect_alignment_conflicts()
        inf = float('infinity')
        # initialize vertex coordinates attributes:
        for l in self.layers:
            for v in l:
                self.grx[v].root  = v
                self.grx[v].align = v
                self.grx[v].sink  = v
                self.grx[v].shift = inf
                self.grx[v].X     = None
                self.grx[v].x     = [0.0]*4
        curvh = self.dirvh # save current dirvh value
        for dirvh in xrange(4):
            self.dirvh = dirvh
            self._coord_vertical_alignment()
            self._coord_horizontal_compact()
        self.dirvh = curvh # restore it
        # vertical coordinate assigment of all nodes:
        Y = 0
        for l in self.layers:
            dY = max([v.view.h/2. for v in l])
            for v in l:
                vx = sorted(self.grx[v].x)
                # mean of the 2 medians out of the 4 x-coord computed above:
                avgm = (vx[1]+vx[2])/2.
                # final xy-coordinates :
                v.view.xy = (avgm,Y+dY)
            Y += 2*dY+self.yspace
        self._edge_inverter()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _detect_alignment_conflicts(self):
        curvh = self.dirvh # save current dirvh value
        self.dirvh=0
        self.conflicts = []
        for L in self.layers:
            last = len(L)-1
            prev = L.prevlayer()
            if not prev: continue
            k0=0
            k1_init=len(prev)-1
            l=0
            for l1,v in enumerate(L):
                if not self.grx[v].dummy: continue
                if l1==last or v.inner(-1):
                    k1=k1_init
                    if v.inner(-1):
                        k1=self.grx[v.N(-1)[-1]].pos
                    for vl in L[l:l1+1]:
                        for vk in L._neighbors(vl):
                            k = self.grx[vk].pos
                            if (k<k0 or k>k1):
                                self.conflicts.append((vk,vl))
                    l=l1+1
                    k0=k1
        self.dirvh = curvh

Response: detect conflicts between dummy nodes and regular crossings


Instruction:
How would you implement a function in Python 3 that
performs vertical alignment according to current dirvh internal state.

Response:
def _coord_vertical_alignment(self):
        """performs vertical alignment according to current dirvh internal state.
        """
        dirh,dirv = self.dirh,self.dirv
        g = self.grx
        for l in self.layers[::-dirv]:
            if not l.prevlayer(): continue
            r=None
            for vk in l[::dirh]:
                for m in l._medianindex(vk):
                    # take the median node in dirv layer:
                    um = l.prevlayer()[m]
                    # if vk is "free" align it with um's root
                    if g[vk].align is vk:
                        if dirv==1: vpair = (vk,um)
                        else:       vpair = (um,vk)
                        # if vk<->um link is used for alignment
                        if (vpair not in self.conflicts) and \
                           (r==None or dirh*r<dirh*m):
                            g[um].align = vk
                            g[vk].root = g[um].root
                            g[vk].align = g[vk].root
                            r = m


Instruction:
Can you implement a function in Python 3 that
makes a cURL POST request to the given URL and returns the JSON response.

Response:
def make_request(cls, url, method, params=None, basic_auth=None, timeout=600):
        """ Makes a cURL POST request to the given URL, specifying the data to be passed in as
         {"method": method, "params": parameters}

        :param str url: URL to connect to.
        :param str method: The API method to call.
        :param dict params: Dictionary object of the parameters associated with the `method` given. None by default.
        :param list | tuple basic_auth: List containing your username and password as ['username', 'password'].
         This is empty by default, however it is required by all of the `lbrycrd` methods
        :param float timeout: Amount of seconds to wait for the server's response before we timeout.
        :raises LBRYException: If the request returns an error when calling the API
        :return: A `dict` of the JSON result member of the request
        :rtype: dict, PreparedResponse
        """

        # Default parameters
        params = {} if params is None else params

        # Increment the request ID
        cls.request_id += 1

        # Weed out all the None valued params
        params = {k: v for (k, v) in params.items() if v is not None}

        # This is the data to be sent
        data = {"method": method, "params": params, "jsonrpc": "2.0", "id": cls.request_id}

        headers = {"Content-Type": "application/json-rpc",  # sends the request as a json
                   "user-agent": "LBRY python3-api"}    # Sets the user agent

        # You could create a request object and then make a prepared request object
        # And then be able to print the Request that will be sent
        request = requests.Request('POST', url, json=data, headers=headers, auth=basic_auth)

        prepared = request.prepare()

        try:

            # Create a session object
            sesh = requests.Session()

            # Send the prepared request object through
            response = sesh.send(prepared, timeout=timeout)

            response_json = response.json()

            # Successful request was made
            if 'result' in response_json:

                # Returns the Result sub-JSON formatted as a dict
                return response_json['result'], response

            # If the response we received from the LBRY http post had an error
            elif 'error' in response_json:
                raise LBRYUtils.LBRYException("POST Request made to LBRY received an error",
                                              response_json, response.status_code, prepared)

        except requests.HTTPError as HE:
            print(HE)

            return None, None

        except requests.RequestException as RE:
            # Print the Request Exception given
            print(RE)

            print("Printing Request Created:\n")

            LBRYUtils.print_request(prepared)

            return None, None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def load_png(varNumVol, strPathPng, tplVslSpcSze=(200, 200), varStrtIdx=0,
             varZfill=3):
    """
    Load PNGs with stimulus information for pRF model creation.

    Parameters
    ----------
    varNumVol : int
        Number of PNG files.
    strPathPng : str
        Parent directory of PNG files. PNG files need to be organsied in
        numerical order (e.g. `file_001.png`, `file_002.png`, etc.).
    tplVslSpcSze : tuple
        Pixel size (x, y) at which PNGs are sampled. In case of large PNGs it
        is useful to sample at a lower than the original resolution.
    varStrtIdx : int
        Start index of PNG files. For instance, `varStrtIdx = 0` if the name of
        the first PNG file is `file_000.png`, or `varStrtIdx = 1` if it is
        `file_001.png`.
    varZfill : int
        Zero padding of PNG file names. For instance, `varStrtIdx = 3` if the
        name of PNG files is `file_007.png`, or `varStrtIdx = 4` if it is
        `file_0007.png`.

    Returns
    -------
    aryPngData : np.array
        3D Numpy array with the following structure:
        aryPngData[x-pixel-index, y-pixel-index, PngNumber]

    Notes
    -----
    Part of py_pRF_mapping library.
    """
    # Create list of png files to load:
    lstPngPaths = [None] * varNumVol
    for idx01 in range(0, varNumVol):
        lstPngPaths[idx01] = (strPathPng +
                              str(idx01 + varStrtIdx).zfill(varZfill) +
                              '.png')

    # The png data will be saved in a numpy array of the following order:
    # aryPngData[x-pixel, y-pixel, PngNumber].
    aryPngData = np.zeros((tplVslSpcSze[0],
                           tplVslSpcSze[1],
                           varNumVol))

    # Open first image in order to check dimensions (greyscale or RGB, i.e. 2D
    # or 3D).
    objIm = Image.open(lstPngPaths[0])
    aryTest = np.array(objIm.resize((objIm.size[0], objIm.size[1]),
                                    Image.ANTIALIAS))
    varNumDim = aryTest.ndim
    del(aryTest)

    # Loop trough PNG files:
    for idx01 in range(0, varNumVol):

        # Old version of reading images with scipy
        # aryPngData[:, :, idx01] = sp.misc.imread(lstPngPaths[idx01])[:, :, 0]
        # aryPngData[:, :, idx01] = sp.misc.imread(lstPngPaths[idx01])[:, :]

        # Load & resize image:
        objIm = Image.open(lstPngPaths[idx01])
        objIm = objIm.resize((tplVslSpcSze[0],
                              tplVslSpcSze[1]),
                             resample=Image.NEAREST)

        # Casting of array depends on dimensionality (greyscale or RGB, i.e. 2D
        # or 3D):
        if varNumDim == 2:
            aryPngData[:, :, idx01] = np.array(objIm.resize(
                (objIm.size[0], objIm.size[1]), Image.ANTIALIAS))[:, :]
        elif varNumDim == 3:
            aryPngData[:, :, idx01] = np.array(objIm.resize(
                (objIm.size[0], objIm.size[1]), Image.ANTIALIAS))[:, :, 0]
        else:
            # Error message:
            strErrMsg = ('ERROR: PNG files for model creation need to be RGB '
                         + 'or greyscale.')
            raise ValueError(strErrMsg)

    # Convert RGB values (0 to 255) to integer ones and zeros:
    aryPngData = (aryPngData > 200).astype(np.int8)

    return aryPngData

Response: Load PNGs with stimulus information for pRF model creation.


Instruction:
Implement a Python 3 function for
loading information from event text file.

Response:
def load_ev_txt(strPthEv):
    """Load information from event text file.

    Parameters
    ----------
    input1 : str
        Path to event text file
    Returns
    -------
    aryEvTxt : 2d numpy array, shape [n_measurements, 3]
        Array with info about conditions: type, onset, duration
    Notes
    -----
    Part of py_pRF_mapping library.
    """
    aryEvTxt = np.loadtxt(strPthEv, dtype='float', comments='#', delimiter=' ',
                          skiprows=0, usecols=(0, 1, 2))
    return aryEvTxt


Instruction:
Implement a Python 3 function for
applying status mapping to a raw API result.

Response:
def adjust_status(info: dict) -> dict:
    """Apply status mapping to a raw API result."""
    modified_info = deepcopy(info)
    modified_info.update({
        'level':
            get_nearest_by_numeric_key(STATUS_MAP, int(info['level'])),
        'level2':
            STATUS_MAP[99] if info['level2'] is None else
            get_nearest_by_numeric_key(STATUS_MAP, int(info['level2']))
    })

    return modified_info


Instruction:
Create a Python 3 function for
returning the status of the CDC for the provided latitude and longitude.

Response:
async def status_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """Return the CDC status for the provided latitude/longitude."""
        cdc_data = await self.raw_cdc_data()
        nearest = await self.nearest_by_coordinates(latitude, longitude)
        return adjust_status(cdc_data[nearest['state']['name']])


Instruction:
Implement a Python 3 function for
returning the CDC status for the specified state.

Response:
async def status_by_state(self, state: str) -> dict:
        """Return the CDC status for the specified state."""
        data = await self.raw_cdc_data()

        try:
            info = next((v for k, v in data.items() if state in k))
        except StopIteration:
            return {}

        return adjust_status(info)


Instruction:
Can you create a Python 3 function that
returns the exception class and message of the exception as string.

Response:
def brief_exception_text(exception, secret_values):
    """
    Returns the Exception class and the message of the exception as string.

    :param exception: The exception to format
    :param secret_values: Values to hide in output
    """
    exception_text = _hide_secret_values(str(exception), secret_values)
    return '[{}]\n{}'.format(type(exception).__name__, exception_text)


Instruction:
Create a Python 3 function to
print the exception message and the name of the exception class to stderr.

Response:
def print_exception(exception, secret_values=None):
    """
    Prints the exception message and the name of the exception class to stderr.

    :param exception: The exception to print
    :param secret_values: Values to hide in output
    """
    print(brief_exception_text(exception, secret_values), file=sys.stderr)


Instruction:
Given the following Python 3 function, write the documentation
def insert(self, **kwargs):
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors

Response: Inserts the document into the database if it is valid. Returns errors otherwise.


Instruction:
Make a summary of the following Python 3 code
def update(self, **kwargs):
        if self.is_valid:
            if '_id' in self._document:
                to_update = self.find_one({'_id': self._id})

                if to_update:
                    before = self.before_update(old=to_update)
                    if before:
                        return before

                    try:
                        self.replace_one({'_id': self._id}, self._document)

                        self.after_update(old=to_update)

                        return self._document
                    except PyMongoException as exc:
                        return PyMongoError(
                            error_message=exc.details.get(
                                'errmsg', exc.details.get(
                                    'err', 'PyMongoError.'
                                )
                            ),
                            operation='update', collection=type(self).__name__,
                            document=self._document,
                        )
                else:
                    return DocumentNotFoundError(type(self).__name__, self._id)
            else:
                return UnidentifiedDocumentError(
                    type(self).__name__, self._document
                )

        return self._errors

Response: Updates the document with the given _id saved in the collection if it is valid. Returns errors otherwise.


Instruction:
Here you have a function in Python 3, explain what it does
def delete(self, **kwargs):
        if self.is_valid:
            if '_id' in self._document:
                to_delete = self.find_one({'_id': self._id})

                if to_delete:
                    before = self.before_delete()
                    if before:
                        return before

                    try:
                        self.delete_one({'_id': self._id})

                        self.after_delete()

                        return self._document
                    except PyMongoException as exc:
                        return PyMongoError(
                            error_message=exc.details.get(
                                'errmsg', exc.details.get(
                                    'err', 'PyMongoError.'
                                )
                            ),
                            operation='delete', collection=type(self).__name__,
                            document=self._document,
                        )
                else:
                    return DocumentNotFoundError(type(self).__name__, self._id)
            else:
                return UnidentifiedDocumentError(
                    type(self).__name__, self._document
                )

Response: Deletes the document if it is saved in the collection.


Instruction:
Create a Python 3 function for
returning one document dict if one passes the filter.

Response:
def find_one(cls, filter=None, *args, **kwargs):
        """
        Returns one document dict if one passes the filter.
        Returns None otherwise.
        """
        return cls.collection.find_one(filter, *args, **kwargs)


Instruction:
Can you tell what is the following Python 3 function doing
def find(cls, *args, **kwargs):
        return list(cls.collection.find(*args, **kwargs))

Response: Returns all document dicts that pass the filter


Instruction:
Can you tell what is the following Python 3 function doing
def aggregate(cls, pipeline=None, **kwargs):
        return list(cls.collection.aggregate(pipeline or [], **kwargs))

Response: Returns the document dicts returned from the Aggregation Pipeline


Instruction:
Here you have a function in Python 3, explain what it does
def insert_many(cls, documents, ordered=True):
        return cls.collection.insert_many(documents, ordered).inserted_ids

Response: Inserts a list of documents into the Collection and returns their _ids


Instruction:
Write a Python 3 script for
updating all the documents that pass the filter with the update value Will upsert a new document if upsert = True

Response:
def update_many(cls, filter, update, upsert=False):
        """
        Updates all documents that pass the filter with the update value
        Will upsert a new document if upsert=True and no document is filtered
        """
        return cls.collection.update_many(filter, update, upsert).raw_result


Instruction:
How would you implement a function in Python 3 that
replaces a single entry in the cache with a new value.

Response:
def replace_one(cls, filter, replacement, upsert=False):
        """
        Replaces a document that passes the filter.
        Will upsert a new document if upsert=True and no document is filtered
        """
        return cls.collection.replace_one(
            filter, replacement, upsert
        ).raw_result


Instruction:
Can you implement a function in Python 3 that
returns a Document if any document is filtered returns None otherwise

Response:
def get(cls, filter=None, **kwargs):
        """
        Returns a Document if any document is filtered, returns None otherwise
        """
        document = cls(cls.find_one(filter, **kwargs))
        return document if document.document else None


Instruction:
Here you have a function in Python 3, explain what it does
def documents(cls, filter=None, **kwargs):
        documents = [cls(document) for document in cls.find(filter, **kwargs)]
        return [document for document in documents if document.document]

Response: Returns a list of Documents if any document is filtered by the filter keyword arguments.


Instruction:
Write a Python 3 script to
return an iterator over all of the statements belonging to a file.

Response:
def in_file(self, fn: str) -> Iterator[Statement]:
        """
        Returns an iterator over all of the statements belonging to a file.
        """
        yield from self.__file_to_statements.get(fn, [])


Instruction:
How would you code a function in Python 3 to
return an iterator over all of the statements located at a given line.

Response:
def at_line(self, line: FileLine) -> Iterator[Statement]:
        """
        Returns an iterator over all of the statements located at a given line.
        """
        num = line.num
        for stmt in self.in_file(line.filename):
            if stmt.location.start.line == num:
                yield stmt


Instruction:
Can you generate the documentation for the following Python 3 function
def funcFindPrfGpu(idxPrc, vecMdlXpos, vecMdlYpos, vecMdlSd, aryFunc,  # noqa
                   aryPrfTc, varL2reg, queOut, lgcPrint=True):
    """
    Find best pRF model for voxel time course.

    Parameters
    ----------
    idxPrc : int
        Process ID of the process calling this function (for CPU
        multi-threading). In GPU version, this parameter is 0 (just one thread
        on CPU).
    vecMdlXpos : np.array
        1D array with pRF model x positions.
    vecMdlYpos : np.array
        1D array with pRF model y positions.
    vecMdlSd : np.array
        1D array with pRF model sizes (SD of Gaussian).
    aryFunc : np.array
        2D array with functional MRI data, with shape aryFunc[voxel, time].
    aryPrfTc : np.array
        Array with pRF model time courses, with shape
        aryPrfTc[x-pos, y-pos, SD, motion-direction, time]
    varL2reg : float
        L2 regularisation factor for ridge regression.
    queOut : multiprocessing.queues.Queue
        Queue to put the results on.
    lgcPrint : boolean
        Whether print statements should be executed.

    Returns
    -------
    lstOut : list
        List containing the following objects:
        idxPrc : int
            Process ID of the process calling this function (for CPU
            multi-threading). In GPU version, this parameter is 0.
        vecBstXpos : np.array
            1D array with best fitting x-position for each voxel, with shape
            vecBstXpos[voxel].
        vecBstYpos : np.array
            1D array with best fitting y-position for each voxel, with shape
            vecBstYpos[voxel].
        vecBstSd : np.array
            1D array with best fitting pRF size for each voxel, with shape
            vecBstSd[voxel].
        vecBstR2 : np.array
            1D array with R2 value of 'winning' pRF model for each voxel, with
            shape vecBstR2[voxel].
        dummy : np.array
            2D array that is supposed to contain the beta values of 'winning'
            pRF models for each voxel, with shape aryBeta[voxel, beta]. AT THE
            MOMENT, CONTAINS EMPTY DUMMY ARRAY (np.zeros).

    Notes
    -----
    Uses a queue that runs in a separate thread to put model time courses on
    the computational graph.
    """
    # -------------------------------------------------------------------------
    # *** Queue-feeding-function that will run in extra thread
    def funcPlcIn():
        """Place data on queue."""
        # Iteration counter:
        idxCnt = 0

        while True:

            # Feed example to Tensorflow placeholder
            aryTmp02 = lstPrfTc[idxCnt]
            dicIn = {objPlcHld01: aryTmp02}

            # Push to the queue:
            objSess.run(objEnQ, feed_dict=dicIn)

            idxCnt += 1

            # Stop if coordinator says stop:
            if objCoord.should_stop():
                break

            # Stop if all data has been put on the queue:
            elif idxCnt == varNumMdls:
                break

    # -------------------------------------------------------------------------
    # *** Prepare pRF model time courses for graph
    if lgcPrint:
        print('------Prepare pRF model time courses for graph')

    # Information about pRF model parameters:
    varNumX = np.shape(vecMdlXpos)[0]
    varNumY = np.shape(vecMdlYpos)[0]
    varNumPrfSizes = np.shape(vecMdlSd)[0]

    # Number of predictors (betas):
    varNumBeta = aryPrfTc.shape[3]

    # At this point, aryPrfTc has the following dimensions:
    # aryPrfTc[x-pos, y-pos, SD, motion-direction, time]

    # Reshape pRF model time courses:
    aryPrfTc = np.reshape(aryPrfTc,
                          ((aryPrfTc.shape[0]
                            * aryPrfTc.shape[1]
                            * aryPrfTc.shape[2]),
                           aryPrfTc.shape[3],
                           aryPrfTc.shape[4]))

    # Now, aryPrfTc has the following dimensions:
    # aryPrfTc[(x-pos * y-pos * SD), motion-direction, time]

    # Original total number of pRF time course models (before removing models
    # with zero variance):
    varNumMdlsTtl = aryPrfTc.shape[0]

    # Change type to float 32:
    aryPrfTc = aryPrfTc.astype(np.float32)

    # The pRF model is fitted only if variance along time dimension is not
    # zero. Get variance along time dimension:
    vecVarPrfTc = np.var(aryPrfTc, axis=2)

    # Zero with float32 precision for comparison:
    varZero32 = np.array(([0.0])).astype(np.float32)[0]

    # Boolean array for models with variance greater than zero for at least
    # one motion direction:
    vecLgcVar = np.max(
                       np.greater(vecVarPrfTc,
                                  varZero32),
                       axis=1
                       )

    # Take models with variance less than zero out of the array:
    aryPrfTc = aryPrfTc[vecLgcVar, :, :]

    # Swap axes, so that
    # aryPrfTc[(x-pos * y-pos * SD), time, motion-direction]
    aryPrfTc = np.swapaxes(aryPrfTc, 1, 2)

    # Add constant term (ones):
    # aryPrfTc = np.concatenate((aryPrfTc,
    #                            np.ones((aryPrfTc.shape[0],
    #                                     aryPrfTc.shape[1],
    #                                     1)).astype(np.float32)),
    #                           axis=2)

    # Size of pRF time courses in MB:
    varSzePrf = np.divide(float(aryPrfTc.nbytes),
                          1000000.0)
    if lgcPrint:
        print(('---------Size of pRF time courses: '
               + str(np.around(varSzePrf))
               + ' MB'))

    # Put pRF model time courses into list:
    lstPrfTc = [None] * aryPrfTc.shape[0]
    for idxMdl in range(int(aryPrfTc.shape[0])):
        lstPrfTc[idxMdl] = aryPrfTc[idxMdl, :, :]
    del(aryPrfTc)

    # Total number of pRF models to fit:
    varNumMdls = len(lstPrfTc)

    # -------------------------------------------------------------------------
    # *** Prepare functional data for graph
    if lgcPrint:
        print('------Prepare functional data for graph')

    # Number of voxels to be fitted:
    varNumVox = aryFunc.shape[0]

    # Number of volumes:
    varNumVol = aryFunc.shape[1]

    # We reshape the voxel time courses, so that time goes down the column,
    # i.e. from top to bottom.
    aryFunc = aryFunc.T

    # Change type to float 32:
    aryFunc = aryFunc.astype(np.float32)

    # We cannot commit the entire functional data to GPU memory, we need to
    # create chunks. Establish the limit (maximum size) of one chunk (in MB):
    varSzeMax = 50.0  # 20.0

    # Size of functional data in MB:
    varSzeFunc = np.divide(float(aryFunc.nbytes),
                           1000000.0)
    if lgcPrint:
        print(('---------Size of functional data: '
               + str(np.around(varSzeFunc))
               + ' MB'))

    # Number of chunks to create:
    varNumChnk = int(np.ceil(np.divide(varSzeFunc, varSzeMax)))

    if lgcPrint:
        print(('---------Functional data will be split into '
               + str(varNumChnk)
               + ' batches'))

    # Vector with the indicies at which the functional data will be separated
    # in order to be chunked up for the parallel processes:
    vecIdxChnks = np.linspace(0,
                              varNumVox,
                              num=varNumChnk,
                              endpoint=False)
    vecIdxChnks = np.hstack((vecIdxChnks, varNumVox))

    # List into which the chunks of functional data are put:
    lstFunc = [None] * varNumChnk

    # Put functional data into chunks:
    for idxChnk in range(0, varNumChnk):
        # Index of first voxel to be included in current chunk:
        varChnkStr = int(vecIdxChnks[idxChnk])
        # Index of last voxel to be included in current chunk:
        varChnkEnd = int(vecIdxChnks[(idxChnk+1)])
        # Put voxel array into list:
        lstFunc[idxChnk] = aryFunc[:, varChnkStr:varChnkEnd]

    # We delete the original array holding the functional data to conserve
    # memory. Therefore, we first need to calculate the mean (will be needed
    # for calculation of R2).

    # After finding the best fitting model for each voxel, we still have to
    # calculate the coefficient of determination (R-squared) for each voxel. We
    # start by calculating the total sum of squares (i.e. the deviation of the
    # data from the mean). The mean of each time course:
    vecFuncMean = np.mean(aryFunc, axis=0)
    # Deviation from the mean for each datapoint:
    vecFuncDev = np.subtract(aryFunc, vecFuncMean[None, :])
    # Sum of squares:
    vecSsTot = np.sum(np.power(vecFuncDev,
                               2.0),
                      axis=0)

    # We don't need the original array with the functional data anymore (the
    # above seems to have created a hard copy):
    del(vecFuncDev)
    del(aryFunc)

    # -------------------------------------------------------------------------
    # *** Miscellaneous preparations

    # Vector for minimum squared residuals:
    vecResSsMin = np.zeros((varNumVox), dtype=np.float32)

    # Vector for indices of models with minimum residuals:
    vecResSsMinIdx = np.zeros((varNumVox), dtype=np.int32)

    # Multiply L2 regularization factor with identity matrix:
    aryL2reg = np.multiply(np.eye(varNumBeta),
                           varL2reg).astype(np.float32)

    # Reduce logging verbosity:
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

    # -------------------------------------------------------------------------
    # *** Prepare status indicator

    # We create a status indicator for the time consuming pRF model finding
    # algorithm. Number of steps of the status indicator:
    varStsStpSze = 20

    # Vector with pRF values at which to give status feedback:
    vecStatPrf = np.linspace(0,
                             (varNumMdls * varNumChnk),
                             num=(varStsStpSze+1),
                             endpoint=True)
    vecStatPrf = np.ceil(vecStatPrf)
    vecStatPrf = vecStatPrf.astype(int)

    # Vector with corresponding percentage values at which to give status
    # feedback:
    vecStatPrc = np.linspace(0,
                             100,
                             num=(varStsStpSze+1),
                             endpoint=True)
    vecStatPrc = np.ceil(vecStatPrc)
    vecStatPrc = vecStatPrc.astype(int)

    # Counter for status indicator:
    varCntSts01 = 0
    varCntSts02 = 0

    # -------------------------------------------------------------------------
    # *** Loop through chunks
    if lgcPrint:
        print('------Run graph')

    for idxChnk in range(varNumChnk):
        if lgcPrint:
            print(('---------Chunk: ' + str(idxChnk)))
            print('lstPrfTc[0].shape')
            print(lstPrfTc[0].shape)

        # Define session:
        # objSess = tf.Session()
        with tf.Graph().as_default(), tf.Session() as objSess:

            # -----------------------------------------------------------------
            # *** Prepare queue
            if lgcPrint:
                print('------Define computational graph, queue & session')

            # Queue capacity:
            varCapQ = 10

            # Dimensions of placeholder have to be determined outside of the
            # tensor object, otherwise the object on which the size is
            # calculated is loaded into GPU memory.
            varDim01 = lstPrfTc[0].shape[0]
            varDim02 = lstPrfTc[0].shape[1]

            # The queue:
            objQ = tf.FIFOQueue(capacity=varCapQ,
                                dtypes=[tf.float32],
                                shapes=[(varDim01, varDim02)])

            # Method for getting queue size:
            objSzeQ = objQ.size()

            # Placeholder that is used to put design matrix on computational
            # graph:
            objPlcHld01 = tf.placeholder(tf.float32,
                                         shape=[varDim01, varDim02])

            # The enqueue operation that puts data on the graph.
            objEnQ = objQ.enqueue([objPlcHld01])

            # Number of threads that will be created:
            varNumThrd = 1

            # The queue runner (places the enqueue operation on the queue?).
            objRunQ = tf.train.QueueRunner(objQ, [objEnQ] * varNumThrd)
            tf.train.add_queue_runner(objRunQ)

            # The tensor object that is retrieved from the queue. Functions
            # like placeholders for the data in the queue when defining the
            # graph.
            objDsng = objQ.dequeue()

            # Coordinator needs to be initialised:
            objCoord = tf.train.Coordinator()

            # -----------------------------------------------------------------
            # *** Fill queue

            # Buffer size (number of samples to put on queue before starting
            # execution of graph):
            varBuff = 10

            # Define & run extra thread with graph that places data on queue:
            objThrd = threading.Thread(target=funcPlcIn)
            objThrd.setDaemon(True)
            objThrd.start()

            # Stay in this while loop until the specified number of samples
            # (varBuffer) have been placed on the queue).
            varTmpSzeQ = 0
            while varTmpSzeQ < varBuff:
                varTmpSzeQ = objSess.run(objSzeQ)

            # -----------------------------------------------------------------
            # *** Prepare & run the graph

            # Chunk of functional data:
            aryTmp01 = np.copy(lstFunc[idxChnk])
            with tf.device('/gpu:0'):
                objFunc = tf.Variable(aryTmp01)

            # Regularisation factor matrix:
            with tf.device('/gpu:0'):
                objL2reg = tf.Variable(aryL2reg)

            # The computational graph. Operation that solves matrix (in the
            # least squares sense), and calculates residuals along time
            # dimension. There are two versions: (1) The number of measurements
            # (e.g. volumes) is greater than or equal to the number of
            # predictors (betas). (2) The number of measurements is less than
            # the number of predictors.

            # (1) Number of measurements greater/equal to number of predictors:
            if np.greater_equal(varNumVol, varNumBeta):
                objMatSlve = tf.reduce_sum(
                                           tf.squared_difference(
                                                                 objFunc,
                                                                 tf.matmul(
                                                                           objDsng,
                                                                           tf.matmul(
                                                                                tf.matmul(
                                                                                tf.matrix_inverse(
                                                                                tf.add(
                                                                                tf.matmul(
                                                                                objDsng,
                                                                                objDsng,
                                                                                transpose_a=True,
                                                                                transpose_b=False
                                                                                ),
                                                                                objL2reg
                                                                                )
                                                                                ),
                                                                                objDsng,
                                                                                transpose_a=False,
                                                                                transpose_b=True
                                                                                ),
                                                                                objFunc
                                                                                )
                                                                           ),
                                                                 ),
                                           axis=0
                                           )

            # (2) Number of measurements less than number of predictors:
            else:
                objMatSlve = tf.reduce_sum(
                                           tf.squared_difference(
                                                                 objFunc,
                                                                 tf.matmul(
                                                                           objDsng,
                                                                           tf.matmul(
                                                                                tf.matmul(
                                                                                objDsng,
                                                                                tf.matrix_inverse(
                                                                                tf.add(
                                                                                tf.matmul(
                                                                                objDsng,
                                                                                objDsng,
                                                                                transpose_a=False,
                                                                                transpose_b=True
                                                                                ),
                                                                                objL2reg
                                                                                )
                                                                                ),
                                                                                transpose_a=True,
                                                                                transpose_b=False
                                                                                ),
                                                                                objFunc
                                                                                )
                                                                           ),
                                                                 ),
                                           axis=0
                                           )

            # Variables need to be (re-)initialised:
            objSess.run(tf.global_variables_initializer())

            # Mark graph as read-only (would throw an error in case of memory
            # leak):
            objSess.graph.finalize()

            # Index of first voxel in current chunk (needed to assign results):
            varChnkStr = int(vecIdxChnks[idxChnk])

            # Index of last voxel in current chunk (needed to assign results):
            varChnkEnd = int(vecIdxChnks[(idxChnk+1)])

            # Array for results of current chunk:
            aryTmpRes = np.zeros((varNumMdls,
                                  lstFunc[idxChnk].shape[1]),
                                 dtype=np.float32)

            # Loop through models:
            for idxMdl in range(varNumMdls):

                # Run main computational graph and put results in list:
                # varTme01 = time.time()

                aryTmpRes[idxMdl, :] = objSess.run(objMatSlve)

                # print(('---------Time for graph call: '
                #        + str(time.time() - varTme01)))

                # Status indicator:
                if varCntSts02 == vecStatPrf[varCntSts01]:
                    # Number of elements on queue:
                    varTmpSzeQ = objSess.run(objSzeQ)
                    # Prepare status message:
                    strStsMsg = ('---------Progress: '
                                 + str(vecStatPrc[varCntSts01])
                                 + ' % --- Number of elements on queue: '
                                 + str(varTmpSzeQ))
                    if lgcPrint:
                        print(strStsMsg)
                    # Only increment counter if the last value has not been
                    # reached yet:
                    if varCntSts01 < varStsStpSze:
                        varCntSts01 = varCntSts01 + int(1)
                # Increment status indicator counter:
                varCntSts02 = varCntSts02 + 1

            # Stop threads.
            objCoord.request_stop()
            # objSess.close()

        # Get indices of models with minimum residuals (minimum along
        # model-space) for current chunk:
        vecResSsMinIdx[varChnkStr:varChnkEnd] = np.argmin(aryTmpRes, axis=0)
        # Get minimum residuals of those models:
        vecResSsMin[varChnkStr:varChnkEnd] = np.min(aryTmpRes, axis=0)

    # -------------------------------------------------------------------------
    # *** Post-process results
    if lgcPrint:
        print('------Post-processing results')

    # Array for model parameters. At the moment, we have the indices of the
    # best fitting models, so we need an array that tells us what model
    # parameters these indices refer to.
    aryMdl = np.zeros((varNumMdlsTtl, 3), dtype=np.float32)

    # Model parameter can be represented as float32 as well:
    vecMdlXpos = vecMdlXpos.astype(np.float32)
    vecMdlYpos = vecMdlYpos.astype(np.float32)
    vecMdlSd = vecMdlSd.astype(np.float32)

    # The first column is to contain model x positions:
    aryMdl[:, 0] = np.repeat(vecMdlXpos, int(varNumY * varNumPrfSizes))

    # The second column is to contain model y positions:
    aryMdl[:, 1] = np.repeat(
                             np.tile(vecMdlYpos,
                                     varNumX),
                             varNumPrfSizes
                             )

    # The third column is to contain model pRF sizes:
    aryMdl[:, 2] = np.tile(vecMdlSd, int(varNumX * varNumY))

    # Earlier, we had removed models with a variance of zero. Thus, those
    # models were ignored and are not present in the results. We remove them
    # from the model-parameter-array:
    aryMdl = aryMdl[vecLgcVar]

    # Retrieve model parameters of 'winning' model for all voxels:
    vecBstXpos = aryMdl[:, 0][vecResSsMinIdx]
    vecBstYpos = aryMdl[:, 1][vecResSsMinIdx]
    vecBstSd = aryMdl[:, 2][vecResSsMinIdx]

    # Coefficient of determination (1 - ratio of (residual sum of squares by
    # total sum of squares)):
    vecBstR2 = np.subtract(1.0,
                           np.divide(vecResSsMin,
                                     vecSsTot)
                           )

    # Output list:
    lstOut = [idxPrc,
              vecBstXpos,
              vecBstYpos,
              vecBstSd,
              vecBstR2,
              np.zeros((varNumVox, (varNumBeta))).astype(np.float32)]

    queOut.put(lstOut)

Response: This function returns a list of objects containing the best pRF model for the given voxel time course.


Instruction:
Create a Python 3 function to
wrap multiple paragraphs of text returning a list of wrapped lines.

Response:
def wrap(text, width=70, **kwargs):
    """Wrap multiple paragraphs of text, returning a list of wrapped lines.

    Reformat the multiple paragraphs  'text' so they fit in lines of no
    more than 'width' columns, and return a list of wrapped lines.  By
    default, tabs in 'text' are expanded with string.expandtabs(), and
    all other whitespace characters (including newline) are converted to
    space.  See ParagraphWrapper class for available keyword args to customize
    wrapping behaviour.
    """
    w = ParagraphWrapper(width=width, **kwargs)
    return w.wrap(text)


Instruction:
Explain what the following Python 3 code does
def fill(text, width=70, **kwargs):
    w = ParagraphWrapper(width=width, **kwargs)
    return w.fill(text)

Response: Fill multiple paragraphs of text returning a new string.


Instruction:
Can you generate the documentation for the following Python 3 function
def split(cls, text):
        result = [line.strip('\n') for line in cls.parasep_re.split(text)]
        if result == ['', '']:
            result = ['']
        return result

Response:
Splits text into multiple paragraphs and returns a list of each
        paragraph.


Instruction:
How would you implement a function in Python 3 that
wraps multiple paragraphs in text and return a list of wrapped lines.

Response:
def wrap(self, text):
        """wrap(text : string) -> [string]

        Reformat the multiple paragraphs in 'text' so they fit in lines of
        no more than 'self.width' columns, and return a list of wrapped
        lines.  Tabs in 'text' are expanded with string.expandtabs(),
        and all other whitespace characters (including newline) are
        converted to space.
        """
        lines = []

        linewrap = partial(textwrap.TextWrapper.wrap, self)
        for para in self.split(text):
            lines.extend(linewrap(para))
            lines.append('')    # Add newline between paragraphs

        # Remove trailing newline
        lines = lines[:-1]

        return lines


Instruction:
Write a Python 3 script for
getting the URL of the sender number MGT.

Response:
def getSenderNumberMgtURL(self, CorpNum, UserID):
        """ 팩스 전송내역 팝업 URL
            args
                CorpNum : 회원 사업자번호
                UserID  : 회원 팝빌아이디
            return
                30초 보안 토큰을 포함한 url
            raise
                PopbillException
        """
        result = self._httpget('/FAX/?TG=SENDER', CorpNum, UserID)
        return result.url


Instruction:
Here you have a function in Python 3, explain what it does
def getUnitCost(self, CorpNum):

        result = self._httpget('/FAX/UnitCost', CorpNum)
        return int(result.unitCost)

Response: Get UnitCost of a user.


Instruction:
Can you tell what is the following Python 3 function doing
def getFaxResultRN(self, CorpNum, RequestNum, UserID=None):

        if RequestNum == None or RequestNum == '':
            raise PopbillException(-99999999, "요청번호가 입력되지 않았습니다.")

        return self._httpget('/FAX/Get/' + RequestNum, CorpNum, UserID)

Response: Get the list of Fax Result


Instruction:
Can you generate the documentation for the following Python 3 function
def sendFax(self, CorpNum, SenderNum, ReceiverNum, ReceiverName, FilePath, ReserveDT=None, UserID=None,
                SenderName=None, adsYN=False, title=None, RequestNum=None):
        """ 팩스 단건 전송
            args
                CorpNum : 팝빌회원 사업자번호
                SenderNum : 발신자 번호
                ReceiverNum : 수신자 번호
                ReceiverName : 수신자 명
                FilePath : 발신 파일경로
                ReserveDT : 예약시간(형식 yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                SenderName : 발신자명 (동보전송용)
                adsYN : 광고팩스 여부
                title : 팩스제목
                RequestNum : 전송요청시 할당한 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException
        """
        receivers = []
        receivers.append(FaxReceiver(receiveNum=ReceiverNum,
                                     receiveName=ReceiverName)
                         )

        return self.sendFax_multi(CorpNum, SenderNum, receivers, FilePath, ReserveDT, UserID, SenderName, adsYN, title,
                                  RequestNum)

Response:
팩스 단건 전송
            args
                CorpNum : 팝빌회원 사업자번호
                SenderNum : 발신자 번호
                ReceiverNum : 수신자 번호
                ReceiverName : 수신자 명
                FilePath : 발신 파일경로
                ReserveDT : 예약시간(형식 yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                SenderName : 발신자명 (동보전송용)
                adsYN : 광고팩스 여부
                title : 팩스제목
                RequestNum : 전송요청시 할당한 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException


Instruction:
Implement a Python 3 function for
sending anFax message to the AFIP.

Response:
def sendFax_multi(self, CorpNum, SenderNum, Receiver, FilePath, ReserveDT=None, UserID=None, SenderName=None,
                      adsYN=False, title=None, RequestNum=None):
        """ 팩스 전송
            args
                CorpNum : 팝빌회원 사업자번호
                SenderNum : 발신자 번호 (동보전송용)
                Receiver : 수신자 번호(동보전송용)
                FilePath : 발신 파일경로
                ReserveDT : 예약시간(형식 yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                SenderName : 발신자명 (동보전송용)
                adsYN : 광고팩스 여부
                title : 팩스제목
                RequestNum : 전송요청시 할당한 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException
        """

        if SenderNum == None or SenderNum == "":
            raise PopbillException(-99999999, "발신자 번호가 입력되지 않았습니다.")
        if Receiver == None:
            raise PopbillException(-99999999, "수신자 정보가 입력되지 않았습니다.")
        if not (type(Receiver) is str or type(Receiver) is FaxReceiver or type(Receiver) is list):
            raise PopbillException(-99999999, "'Receiver' argument type error. 'FaxReceiver' or List of 'FaxReceiver'.")
        if FilePath == None:
            raise PopbillException(-99999999, "발신 파일경로가 입력되지 않았습니다.")
        if not (type(FilePath) is str or type(FilePath) is list):
            raise PopbillException(-99999999, "발신 파일은 파일경로 또는 경로목록만 입력 가능합니다.")
        if type(FilePath) is list and (len(FilePath) < 1 or len(FilePath) > 20):
            raise PopbillException(-99999999, "파일은 1개 이상, 20개 까지 전송 가능합니다.")

        req = {"snd": SenderNum, "sndnm": SenderName, "fCnt": 1 if type(FilePath) is str else len(FilePath), "rcvs": [],
               "sndDT": None}

        if (type(Receiver) is str):
            Receiver = FaxReceiver(receiveNum=Receiver)

        if (type(Receiver) is FaxReceiver):
            Receiver = [Receiver]

        if adsYN:
            req['adsYN'] = True

        for r in Receiver:
            req['rcvs'].append({"rcv": r.receiveNum, "rcvnm": r.receiveName})

        if ReserveDT != None:
            req['sndDT'] = ReserveDT

        if title != None:
            req['title'] = title

        if RequestNum != None:
            req['requestNum'] = RequestNum

        postData = self._stringtify(req)

        if (type(FilePath) is str):
            FilePath = [FilePath]

        files = []

        for filePath in FilePath:
            with open(filePath, "rb") as f:
                files.append(File(fieldName='file',
                                  fileName=f.name,
                                  fileData=f.read())
                             )
        result = self._httppost_files('/FAX', postData, files, CorpNum, UserID)

        return result.receiptNum


Instruction:
Explain what the following Python 3 code does
def resendFaxRN(self, CorpNum, OrgRequestNum, SenderNum, SenderName, ReceiverNum, ReceiverName, ReserveDT=None,
                    UserID=None, title=None, RequestNum=None):
        """ 팩스 단건 전송
            args
                CorpNum : 팝빌회원 사업자번호
                OrgRequestNum : 원본 팩스 전송시 할당한 전송요청번호
                ReceiptNum : 팩스 접수번호
                SenderNum : 발신자 번호
                SenderName : 발신자명
                ReceiverNum : 수신번호
                ReceiverName : 수신자명
                ReserveDT : 예약시간(형식 yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                title : 팩스제목
                RequestNum : 전송요청시 할당한 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException
        """
        receivers = None

        if ReceiverNum != "" or ReceiverName != "":
            receivers = []
            receivers.append(FaxReceiver(receiveNum=ReceiverNum,
                                         receiveName=ReceiverName)
                             )
        return self.resendFaxRN_multi(CorpNum, OrgRequestNum, SenderNum, SenderName, receivers, ReserveDT,
                                      UserID, title, RequestNum)

Response: Resend anFaxRN to a specific sender.


Instruction:
Can you implement a function in Python 3 that
gets URL of a preview of a given receipt.

Response:
def getPreviewURL(self, CorpNum, ReceiptNum, UserID):
        """ 팩스 발신번호 목록 확인
            args
                CorpNum : 팝빌회원 사업자번호
                UserID : 팝빌회원 아이디
            return
                처리결과. list of SenderNumber
            raise
                PopbillException
        """
        return self._httpget('/FAX/Preview/' + ReceiptNum, CorpNum, UserID).url


Instruction:
Can you tell what is the following Python 3 function doing
def prepare_outdir(outdir):
    if outdir:
        outdir = os.path.expanduser(outdir)
        if not os.path.isdir(outdir):
            try:
                os.makedirs(outdir)
            except os.error as e:
                raise JobExecutionError('Failed to create outdir "{}".\n{}'.format(outdir, str(e)))

Response: Creates the output directory if not existing.


Instruction:
Make a summary of the following Python 3 code
def requestJob(self, CorpNum, Type, SDate, EDate, UserID=None):

        if Type == None or Type == '':
            raise PopbillException(-99999999, "문서형태이 입력되지 않았습니다.")

        if SDate == None or SDate == '':
            raise PopbillException(-99999999, "시작일자가 입력되지 않았습니다.")

        if EDate == None or EDate == '':
            raise PopbillException(-99999999, "종료일자가 입력되지 않았습니다.")

        uri = '/HomeTax/Cashbill/' + Type
        uri += '?SDate=' + SDate
        uri += '&EDate=' + EDate

        return self._httppost(uri, "", CorpNum, UserID).jobID

Response: Request a job from the Cashbill.


Instruction:
How would you explain what the following Python 3 function does
def summary(self, CorpNum, JobID, TradeType, TradeUsage, UserID=None):
        if JobID == None or len(JobID) != 18:
            raise PopbillException(-99999999, "작업아이디(jobID)가 올바르지 않습니다.")

        uri = '/HomeTax/Cashbill/' + JobID + '/Summary'
        uri += '?TradeType=' + ','.join(TradeType)
        uri += '&TradeUsage=' + ','.join(TradeUsage)

        return self._httpget(uri, CorpNum, UserID)

Response:
수집 결과 요약정보 조회
            args
                CorpNum : 팝빌회원 사업자번호
                JobID : 작업아이디
                TradeType : 문서형태 배열, N-일반 현금영수증, C-취소 현금영수증
                TradeUsage : 거래구분 배열, P-소등공제용, C-지출증빙용
                UserID : 팝빌회원 아이디
            return
                수집 결과 요약정보
            raise
                PopbillException


Instruction:
How would you explain what the following Python 3 function does
def model_node(**kwargs):
    kwargs.setdefault('default', {})

    def decorator(model):
        return types.ModelType(model, **kwargs)

    return decorator

Response:
A simple decorator for creating a schematics. Model class to add it as a field
    of type schematics. types. ModelType.


Instruction:
Explain what the following Python 3 code does
def for_each_file(base_dir, func):

    for dir_path, _, file_names in os.walk(base_dir):
        for filename in file_names:
            func(os.path.join(dir_path, filename))

Response: Calls func for every file under base_dir.


Instruction:
Given the following Python 3 function, write the documentation
def make_file_read_only(file_path):
    old_permissions = os.stat(file_path).st_mode
    os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)

Response: Removes the write permissions for the given file.


Instruction:
Can you generate the documentation for the following Python 3 function
def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True):

    # Dictionary with config information:
    dicCnfg = {}

    # Open file with parameter configuration:
    # fleConfig = open(strCsvCnfg, 'r')
    with open(strCsvCnfg, 'r') as fleConfig:

        # Read file  with ROI information:
        csvIn = csv.reader(fleConfig,
                           delimiter='\n',
                           skipinitialspace=True)

        # Loop through csv object to fill list with csv data:
        for lstTmp in csvIn:

            # Skip comments (i.e. lines starting with '#') and empty lines.
            # Note: Indexing the list (i.e. lstTmp[0][0]) does not work for
            # empty lines. However, if the first condition is no fullfilled
            # (i.e. line is empty and 'if lstTmp' evaluates to false), the
            # second logical test (after the 'and') is not actually carried
            # out.
            if lstTmp and not (lstTmp[0][0] == '#'):

                # Name of current parameter (e.g. 'varTr'):
                strParamKey = lstTmp[0].split(' = ')[0]
                # print(strParamKey)

                # Current parameter value (e.g. '2.94'):
                strParamVlu = lstTmp[0].split(' = ')[1]
                # print(strParamVlu)

                # Put paramter name (key) and value (item) into dictionary:
                dicCnfg[strParamKey] = strParamVlu

    # Are model parameters in cartesian or polar coordinates?
    # set either pol (polar) or crt (cartesian)
    dicCnfg['strKwCrd'] = ast.literal_eval(dicCnfg['strKwCrd'])
    if lgcPrint:
        print('---Model coordinates are in: ' + str(dicCnfg['strKwCrd']))

    # Number of x- or radial positions to model:
    dicCnfg['varNum1'] = int(dicCnfg['varNum1'])
    # Number of y- or angular positions to model:
    dicCnfg['varNum2'] = int(dicCnfg['varNum2'])

    if lgcPrint:
        if dicCnfg['strKwCrd'] == 'crt':
            print('---Number of x-positions to model: ' +
                  str(dicCnfg['varNum1']))
            print('---Number of y-positions to model: ' +
                  str(dicCnfg['varNum2']))

        elif dicCnfg['strKwCrd'] == 'pol':
            print('---Number of radial positions to model: ' +
                  str(dicCnfg['varNum1']))
            print('---Number of angular positions to model: ' +
                  str(dicCnfg['varNum2']))

    # Number of pRF sizes to model:
    dicCnfg['varNumPrfSizes'] = int(dicCnfg['varNumPrfSizes'])
    if lgcPrint:
        print('---Number of pRF sizes to model: '
              + str(dicCnfg['varNumPrfSizes']))

    # Extent of visual space from centre of the screen in negative x-direction
    # (i.e. from the fixation point to the left end of the screen) in degrees
    # of visual angle.
    dicCnfg['varExtXmin'] = float(dicCnfg['varExtXmin'])
    if lgcPrint:
        print('---Extent of visual space in negative x-direction: '
              + str(dicCnfg['varExtXmin']))

    # Extent of visual space from centre of the screen in positive x-direction
    # (i.e. from the fixation point to the right end of the screen) in degrees
    # of visual angle.
    dicCnfg['varExtXmax'] = float(dicCnfg['varExtXmax'])
    if lgcPrint:
        print('---Extent of visual space in positive x-direction: '
              + str(dicCnfg['varExtXmax']))

    # Extent of visual space from centre of the screen in negative y-direction
    # (i.e. from the fixation point to the lower end of the screen) in degrees
    # of visual angle.
    dicCnfg['varExtYmin'] = float(dicCnfg['varExtYmin'])
    if lgcPrint:
        print('---Extent of visual space in negative y-direction: '
              + str(dicCnfg['varExtYmin']))

    # Extent of visual space from centre of the screen in positive y-direction
    # (i.e. from the fixation point to the upper end of the screen) in degrees
    # of visual angle.
    dicCnfg['varExtYmax'] = float(dicCnfg['varExtYmax'])
    if lgcPrint:
        print('---Extent of visual space in positive y-direction: '
              + str(dicCnfg['varExtYmax']))

    # Minimum pRF model size (standard deviation of 2D Gaussian) [degrees of
    # visual angle]:
    dicCnfg['varPrfStdMin'] = float(dicCnfg['varPrfStdMin'])
    if lgcPrint:
        print('---Minimum pRF model size: ' + str(dicCnfg['varPrfStdMin']))

    # Maximum pRF model size (standard deviation of 2D Gaussian) [degrees of
    # visual angle]:
    dicCnfg['varPrfStdMax'] = float(dicCnfg['varPrfStdMax'])
    if lgcPrint:
        print('---Maximum pRF model size: ' + str(dicCnfg['varPrfStdMax']))

    # Volume TR of input data [s]:
    dicCnfg['varTr'] = float(dicCnfg['varTr'])
    if lgcPrint:
        print('---Volume TR of input data [s]: ' + str(dicCnfg['varTr']))

    # Voxel resolution of fMRI data [mm]:
    dicCnfg['varVoxRes'] = float(dicCnfg['varVoxRes'])
    if lgcPrint:
        print('---Voxel resolution of fMRI data [mm]: '
              + str(dicCnfg['varVoxRes']))

    # Number of fMRI volumes and png files to load:
    dicCnfg['varNumVol'] = int(dicCnfg['varNumVol'])
    if lgcPrint:
        print('---Total number of fMRI volumes and png files: '
              + str(dicCnfg['varNumVol']))

    # Extent of temporal smoothing for fMRI data and pRF time course models
    # [standard deviation of the Gaussian kernel, in seconds]:
    # same temporal smoothing will be applied to pRF model time courses
    dicCnfg['varSdSmthTmp'] = float(dicCnfg['varSdSmthTmp'])
    if lgcPrint:
        print('---Extent of temporal smoothing (Gaussian SD in [s]): '
              + str(dicCnfg['varSdSmthTmp']))

    # Number of processes to run in parallel:
    dicCnfg['varPar'] = int(dicCnfg['varPar'])
    if lgcPrint:
        print('---Number of processes to run in parallel: '
              + str(dicCnfg['varPar']))

    # Size of space model in which the pRF models are
    # created (x- and y-dimension).
    dicCnfg['tplVslSpcSze'] = tuple([int(dicCnfg['varVslSpcSzeX']),
                                     int(dicCnfg['varVslSpcSzeY'])])
    if lgcPrint:
        print('---Size of visual space model (x & y): '
              + str(dicCnfg['tplVslSpcSze']))

    # Path(s) of functional data:
    dicCnfg['lstPathNiiFunc'] = ast.literal_eval(dicCnfg['lstPathNiiFunc'])
    if lgcPrint:
        print('---Path(s) of functional data:')
        for strTmp in dicCnfg['lstPathNiiFunc']:
            print('   ' + str(strTmp))

    # Path of mask (to restrict pRF model finding):
    dicCnfg['strPathNiiMask'] = ast.literal_eval(dicCnfg['strPathNiiMask'])
    if lgcPrint:
        print('---Path of mask (to restrict pRF model finding):')
        print('   ' + str(dicCnfg['strPathNiiMask']))

    # Output basename:
    dicCnfg['strPathOut'] = ast.literal_eval(dicCnfg['strPathOut'])
    if lgcPrint:
        print('---Output basename:')
        print('   ' + str(dicCnfg['strPathOut']))

    # Which version to use for pRF finding. 'numpy' or 'cython' for pRF finding
    # on CPU, 'gpu' for using GPU.
    dicCnfg['strVersion'] = ast.literal_eval(dicCnfg['strVersion'])
    if lgcPrint:
        print('---Version (numpy, cython, or gpu): '
              + str(dicCnfg['strVersion']))

    # Create pRF time course models?
    dicCnfg['lgcCrteMdl'] = (dicCnfg['lgcCrteMdl'] == 'True')
    if lgcPrint:
        print('---Create pRF time course models: '
              + str(dicCnfg['lgcCrteMdl']))

    # Path to npy file with pRF time course models (to save or laod). Without
    # file extension.
    dicCnfg['strPathMdl'] = ast.literal_eval(dicCnfg['strPathMdl'])
    if lgcPrint:
        print('---Path to npy file with pRF time course models (to save '
              + 'or load):')
        print('   ' + str(dicCnfg['strPathMdl']))

    # switch to determine which hrf functions should be used
    # 1: canonical, 2: can and temp derivative, 3: can, temp and spat deriv
    dicCnfg['switchHrfSet'] = ast.literal_eval(dicCnfg['switchHrfSet'])
    if lgcPrint:
        print('---Switch to determine which hrf functions should be used: '
              + str(dicCnfg['switchHrfSet']))

    # should model fitting be based on k-fold cross-validation?
    # if not, set to 1
    dicCnfg['varNumXval'] = ast.literal_eval(dicCnfg['varNumXval'])
    if lgcPrint:
        print('---Model fitting will have this number of folds for xval: '
              + str(dicCnfg['varNumXval']))

    # If we create new pRF time course models, the following parameters have to
    # be provided:
    if dicCnfg['lgcCrteMdl']:

        # Name of the npy that holds spatial info about conditions
        dicCnfg['strSptExpInf'] = ast.literal_eval(dicCnfg['strSptExpInf'])
        if lgcPrint:
            print('---Path to npy file with spatial condition info: ')
            print('   ' + str(dicCnfg['strSptExpInf']))

        # Name of the npy that holds temporal info about conditions
        dicCnfg['strTmpExpInf'] = ast.literal_eval(dicCnfg['strTmpExpInf'])
        if lgcPrint:
            print('---Path to npy file with temporal condition info: ')
            print('   ' + str(dicCnfg['strTmpExpInf']))

        # Factor by which time courses and HRF will be upsampled for the
        # convolutions
        dicCnfg['varTmpOvsmpl'] = ast.literal_eval(dicCnfg['varTmpOvsmpl'])
        if lgcPrint:
            print('---Factor by which time courses and HRF will be upsampled: '
                  + str(dicCnfg['varTmpOvsmpl']))

    # Is this a test?
    if lgcTest:

        # Prepend absolute path of this file to config file paths:
        dicCnfg['strPathNiiMask'] = (strDir + dicCnfg['strPathNiiMask'])
        dicCnfg['strPathOut'] = (strDir + dicCnfg['strPathOut'])
        dicCnfg['strPathMdl'] = (strDir + dicCnfg['strPathMdl'])
        dicCnfg['strSptExpInf'] = (strDir + dicCnfg['strSptExpInf'])
        dicCnfg['strTmpExpInf'] = (strDir + dicCnfg['strTmpExpInf'])

        # Loop through functional runs:
        varNumRun = len(dicCnfg['lstPathNiiFunc'])
        for idxRun in range(varNumRun):
            dicCnfg['lstPathNiiFunc'][idxRun] = (
                strDir
                + dicCnfg['lstPathNiiFunc'][idxRun]
                )

    return dicCnfg

Response: Load the config file and return a dictionary with the ROI information.


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def status_by_coordinates(
            self, latitude: float, longitude: float) -> dict:
        """Get symptom data for the location nearest to the user's lat/lon."""
        return await self.nearest_by_coordinates(latitude, longitude)

Response: Get the status of the user from the given latitude and longitude.


Instruction:
Can you write a function in Python 3 where it
gets symptom data for the provided ZIP code.

Response:
async def status_by_zip(self, zip_code: str) -> dict:
        """Get symptom data for the provided ZIP code."""
        try:
            location = next((
                d for d in await self.user_reports()
                if d['zip'] == zip_code))
        except StopIteration:
            return {}

        return await self.status_by_coordinates(
            float(location['latitude']), float(location['longitude']))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_request(request):
    print('{}\n{}\n{}\n\n{}'.format(
        '-----------START-----------',
        request.method + ' ' + request.url,
        '\n'.join('{}: {}'.format(k, v) for k, v in request.headers.items()),
        request.body,
    ))

Response: Prints a request to give the user info as to what they re sending


Instruction:
Make a summary of the following Python 3 code
def make_EPUB(parsed_article,
              output_directory,
              input_path,
              image_directory,
              config_module=None,
              epub_version=None,
              batch=False):
    """
    Standard workflow for creating an EPUB document.

    make_EPUB is used to produce an EPUB file from a parsed article. In addition
    to the article it also requires a path to the appropriate image directory
    which it will insert into the EPUB file, as well the output directory
    location for the EPUB file.

    Parameters
    ----------
    article : openaccess_epub.article.Article instance
        `article` is an Article instance for the XML document to be converted to
        EPUB.
    output_directory : str
        `output_directory` is a string path to the directory in which the EPUB
        will be produced. The name of the directory will be used as the EPUB's
        filename.
    input_path : str
        `input_path` is a string absolute path to the input XML file, used to
        locate input-relative images.
    image_directory : str
        `image_directory` is a string path indicating an explicit image
        directory. If supplied, other image input methods will not be used.
    config_module : config module, optional
        `config_module` is a pre-loaded config module for OpenAccess_EPUB; if
        not used then this function will load the global config file. Might be
        useful in certain cases to dynamically alter configuration.
    epub_version : {None, 2, 3}
        `epub_version` dictates which version of EPUB to be created. An error
        will be raised if the specified version is not supported for the
        publisher. If left to the default, the created version will defer to the
        publisher default version.
    batch : bool, optional
        `batch` indicates that batch creation is being used (such as with the
        `oaepub batch` command). In this case, directory conflicts will be
        automatically resolved (in favor of keeping previous data, skipping
        creation of EPUB).

    Returns False in the case of a fatal error, True if successful.
    """
    #command_log.info('Creating {0}.epub'.format(output_directory))
    if config_module is None:
        config_module = openaccess_epub.utils.load_config_module()

    if epub_version not in (None, 2, 3):
        log.error('Invalid EPUB version: {0}'.format(epub_version))
        raise ValueError('Invalid EPUB version. Should be 2 or 3')

    if epub_version is None:
        epub_version = parsed_article.publisher.epub_default

    #Handle directory output conflicts
    if os.path.isdir(output_directory):
        if batch:  # No user prompt, default to protect previous data
            log.error('Directory conflict during batch conversion, skipping.')
            return False
        else:  # User prompting
            openaccess_epub.utils.dir_exists(output_directory)
    else:
        try:
            os.makedirs(output_directory)
        except OSError as err:
            if err.errno != 17:
                log.exception('Unable to recursively create output directories')

    #Copy over the basic epub directory
    make_epub_base(output_directory)

    #Get the images, if possible, fail gracefully if not
    success = openaccess_epub.utils.images.get_images(output_directory,
                                                      image_directory,
                                                      input_path,
                                                      config_module,
                                                      parsed_article)
    if not success:
        log.critical('Images for the article were not located! Aborting!')
        return False

    #Instantiate Navigation and Package
    epub_nav = Navigation()
    epub_package = Package()

    #Process the article for navigation and package info
    epub_nav.process(parsed_article)
    epub_package.process(parsed_article)

    #Render the content using publisher-specific methods
    parsed_article.publisher.render_content(output_directory, epub_version)
    if epub_version == 2:
        epub_nav.render_EPUB2(output_directory)
        epub_package.render_EPUB2(output_directory)
    elif epub_version == 3:
        epub_nav.render_EPUB3(output_directory)
        epub_package.render_EPUB3(output_directory)

    #Zip the directory into EPUB
    epub_zip(output_directory)

    return True

Response: This function creates an EPUB file from an OpenAccess_EPUB article.


Instruction:
Create a Python 3 function to
create the base structure for an EPUB file in a specified location.

Response:
def make_epub_base(location):
    """
    Creates the base structure for an EPUB file in a specified location.

    This function creates constant components for the structure of the EPUB in
    a specified directory location.

    Parameters
    ----------
    location : str
        A path string to a local directory in which the EPUB is to be built
    """
    log.info('Making EPUB base files in {0}'.format(location))
    with open(os.path.join(location, 'mimetype'), 'w') as out:  # mimetype file
        out.write('application/epub+zip')

    #Create EPUB and META-INF directorys
    os.mkdir(os.path.join(location, 'META-INF'))
    os.mkdir(os.path.join(location, 'EPUB'))
    os.mkdir(os.path.join(location, 'EPUB', 'css'))

    with open(os.path.join(location, 'META-INF', 'container.xml'), 'w') as out:
        out.write('''\
<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
   <rootfiles>
      <rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>''')

    with open(os.path.join(location, 'EPUB', 'css', 'default.css') ,'wb') as out:
        out.write(bytes(DEFAULT_CSS, 'UTF-8'))


Instruction:
Given the following Python 3 function, write the documentation
def epub_zip(outdirect):

    def recursive_zip(zipf, directory, folder=None):
        if folder is None:
            folder = ''
        for item in os.listdir(directory):
            if os.path.isfile(os.path.join(directory, item)):
                zipf.write(os.path.join(directory, item),
                           os.path.join(directory, item))
            elif os.path.isdir(os.path.join(directory, item)):
                recursive_zip(zipf, os.path.join(directory, item),
                              os.path.join(folder, item))

    log.info('Zipping up the directory {0}'.format(outdirect))
    epub_filename = outdirect + '.epub'
    epub = zipfile.ZipFile(epub_filename, 'w')
    current_dir = os.getcwd()
    os.chdir(outdirect)
    epub.write('mimetype')
    log.info('Recursively zipping META-INF and EPUB')
    for item in os.listdir('.'):
        if item == 'mimetype':
            continue
        recursive_zip(epub, item)
    os.chdir(current_dir)
    epub.close()

Response: Zips the input file directory into an EPUB file.


Instruction:
Write a Python 3 script to
write data to CSV file with validation.

Response:
def _write_int(fname, data, append=True):
    """Write data to CSV file with validation."""
    # pylint: disable=W0705
    data_ex = pexdoc.exh.addex(ValueError, "There is no data to save to file")
    fos_ex = pexdoc.exh.addex(
        OSError, "File *[fname]* could not be created: *[reason]*"
    )
    data_ex((len(data) == 0) or ((len(data) == 1) and (len(data[0]) == 0)))
    try:
        pmisc.make_dir(fname)
        mode = "w" if append is False else "a"
        if sys.hexversion < 0x03000000:  # pragma: no cover, no branch
            with open(fname, mode) as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
        else:  # pragma: no cover
            with open(fname, mode, newline="") as file_handle:
                csv.writer(file_handle, delimiter=",").writerows(data)
    except (IOError, OSError) as eobj:
        fos_ex(True, _MF("fname", fname, "reason", eobj.strerror))


Instruction:
How would you implement a function in Python 3 that
generates a directory description from a given input directory.

Response:
def _input_directory_description(input_identifier, arg_item, input_dir):
    """
     Produces a directory description. A directory description is a dictionary containing the following information.

     - 'path': An array containing the paths to the specified directories.
     - 'debugInfo': A field to possibly provide debug information.
     - 'found': A boolean that indicates, if the directory exists in the local filesystem.
     - 'listing': A listing that shows which files are in the given directory. This could be None.

    :param input_identifier: The input identifier in the cwl description file
    :param arg_item: The corresponding job information
    :param input_dir: TODO
    :return: A directory description
    :raise DirectoryError: If the given directory does not exist or is not a directory.
    """
    description = {
        'path': None,
        'found': False,
        'debugInfo': None,
        'listing': None,
        'basename': None
    }

    try:
        path = location(input_identifier, arg_item)

        if input_dir and not os.path.isabs(path):
            path = os.path.join(os.path.expanduser(input_dir), path)

        description['path'] = path
        if not os.path.exists(path):
            raise DirectoryError('path does not exist')
        if not os.path.isdir(path):
            raise DirectoryError('path is not a directory')

        description['listing'] = arg_item.get('listing')
        description['basename'] = os.path.basename(path)

        description['found'] = True
    except:
        description['debugInfo'] = exception_format()

    return description


Instruction:
Create a Python 3 function to
check that the given directory listing is well - formed and if not raises an exception.

Response:
def _check_input_directory_listing(base_directory, listing):
    """
    Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem.

    :param base_directory: The path to the directory to check
    :param listing: A listing given as dictionary
    :raise DirectoryError: If the given base directory does not contain all of the subdirectories and subfiles given in
    the listing.
    """

    for sub in listing:
        path = os.path.join(base_directory, sub['basename'])
        if sub['class'] == 'File':
            if not os.path.isfile(path):
                raise DirectoryError('File \'{}\' not found but specified in listing.'.format(path))
        if sub['class'] == 'Directory':
            if not os.path.isdir(path):
                raise DirectoryError('Directory \'{}\' not found but specified in listing'.format(path))
            sub_listing = sub.get('listing')
            if sub_listing:
                _check_input_directory_listing(path, sub_listing)


Instruction:
Can you implement a function in Python 3 that
parses cwl type string into a dictionary containing information about the cwl type string.

Response:
def parse_cwl_type(cwl_type_string):
    """
    Parses cwl type information from a cwl type string.

    Examples:

    - "File[]" -> {'type': 'File', 'isArray': True, 'isOptional': False}
    - "int?" -> {'type': 'int', 'isArray': False, 'isOptional': True}

    :param cwl_type_string: The cwl type string to extract information from
    :return: A dictionary containing information about the parsed cwl type string
    """

    is_optional = cwl_type_string.endswith('?')
    if is_optional:
        cwl_type_string = cwl_type_string[:-1]

    is_array = cwl_type_string.endswith('[]')
    if is_array:
        cwl_type_string = cwl_type_string[:-2]

    return {'type': cwl_type_string, 'isArray': is_array, 'isOptional': is_optional}


Instruction:
Write a Python 3 script for
searching for Directories and in the cwl data and produces a dictionary containing the input file information.

Response:
def cwl_input_directories(cwl_data, job_data, input_dir=None):
    """
    Searches for Directories and in the cwl data and produces a dictionary containing input file information.

    :param cwl_data: The cwl data as dictionary
    :param job_data: The job data as dictionary
    :param input_dir: TODO
    :return: Returns the a dictionary containing information about input files.
             The keys of this dictionary are the input/output identifiers of the files specified in the cwl description.
             The corresponding value is a dictionary again with the following keys and values:
             - 'isOptional': A bool indicating whether this input directory is optional
             - 'isArray': A bool indicating whether this could be a list of directories
             - 'files': A list of input file descriptions

             A input file description is a dictionary containing the following information
             - 'path': The path to the specified directory
             - 'debugInfo': A field to possibly provide debug information
    """

    results = {}

    for input_identifier, input_data in cwl_data['inputs'].items():
        cwl_type = parse_cwl_type(input_data['type'])

        (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type)

        if cwl_type == 'Directory':
            result = {
                'isOptional': is_optional,
                'isArray': is_array,
                'directories': None
            }

            if input_identifier in job_data:
                arg = job_data[input_identifier]

                if is_array:
                    result['directories'] = [_input_directory_description(input_identifier, i, input_dir) for i in arg]
                else:
                    result['directories'] = [_input_directory_description(input_identifier, arg, input_dir)]

            results[input_identifier] = result

    return results


Instruction:
Create a Python 3 function to
return a dictionary containing information about the output files given in cwl_data.

Response:
def cwl_output_files(cwl_data, inputs_to_reference, output_dir=None):
    """
    Returns a dictionary containing information about the output files given in cwl_data.

    :param cwl_data: The cwl data from where to extract the output file information.
    :param inputs_to_reference: Inputs which are used to resolve input references.
    :param output_dir: Path to the directory where output files are expected.
    :return: A dictionary containing information about every output file.
    """
    results = {}

    for key, val in cwl_data['outputs'].items():
        cwl_type = parse_cwl_type(val['type'])
        (is_optional, is_array, cwl_type) = itemgetter('isOptional', 'isArray', 'type')(cwl_type)

        if not cwl_type == 'File':
            continue

        result = {
            'isOptional': is_optional,
            'path': None,
            'size': None,
            'debugInfo': None
        }

        glob_path = os.path.expanduser(val['outputBinding']['glob'])
        if output_dir and not os.path.isabs(glob_path):
            glob_path = os.path.join(os.path.expanduser(output_dir), glob_path)

        glob_path = resolve_input_references(glob_path, inputs_to_reference)
        matches = glob(glob_path)
        try:
            if len(matches) != 1:
                raise FileError('glob path "{}" does not match exactly one file'.format(glob_path))

            file_path = matches[0]
            result['path'] = file_path

            if not os.path.isfile(file_path):
                raise FileError('path is not a file')

            result['size'] = os.path.getsize(file_path) / (1024 * 1024)
        except:
            result['debugInfo'] = exception_format()

        results[key] = result

    return results


Instruction:
Create a Python 3 function to
read from the FIFO and returns the data.

Response:
def read(self, length=-1):
        """
        Reads from the FIFO.

        Reads as much data as possible from the FIFO up to the specified
        length. If the length argument is negative or ommited all data
        currently available in the FIFO will be read. If there is no data
        available in the FIFO an empty string is returned.

        Args:
            length: The amount of data to read from the FIFO. Defaults to -1.
        """
        if 0 <= length < len(self):
            newpos = self.pos + length
            data = self.buf[self.pos:newpos]
            self.pos = newpos
            self.__discard()
            return data

        data = self.buf[self.pos:]
        self.clear()
        return data


Instruction:
Explain what the following Python 3 code does
def readuntil(self, token, size=0):
        self.__append()

        i = self.buf.find(token, self.pos)
        if i < 0:
            index = max(len(token) - 1, size)
            newpos = max(len(self.buf) - index, self.pos)
            data = self.buf[self.pos:newpos]
            self.pos = newpos
            self.__discard()
            return False, data

        newpos = i + len(token)
        data = self.buf[self.pos:newpos]
        self.pos = newpos
        self.__discard()
        return True, data

Response: Reads data from the FIFO until a token is encountered.


Instruction:
Create a Python 3 function for
reading a line into the FIFO.

Response:
def peekline(self):
        """
        Peeks a line into the FIFO.

        Perfroms the same function as readline() without removing data from the
        FIFO. See readline() for further information.
        """
        self.__append()

        i = self.buf.find(self.eol, self.pos)
        if i < 0:
            return ''

        newpos = i + len(self.eol)
        return self.buf[self.pos:newpos]


Instruction:
Explain what the following Python 3 code does
def peekuntil(self, token, size=0):
        self.__append()

        i = self.buf.find(token, self.pos)
        if i < 0:
            index = max(len(token) - 1, size)
            newpos = max(len(self.buf) - index, self.pos)
            return False, self.buf[self.pos:newpos]

        newpos = i + len(token)
        return True, self.buf[self.pos:newpos]

Response: Reads the next size bytes from the FIFO.


Instruction:
Write a Python 3 script to
get URL from Akamai.

Response:
def getURL(self, CorpNum, UserID, ToGo):
        """
        :param CorpNum: 팝빌회원 사업자번호
        :param UserID: 팝빌회원 아이디
        :param ToGo: [PLUSFRIEND-플러스친구계정관리, SENDER-발신번호관리, TEMPLATE-알림톡템플릿관리, BOX-카카오톡전송내용]
        :return: 팝빌 URL
        """
        if ToGo == None or ToGo == '':
            raise PopbillException(-99999999, "TOGO값이 입력되지 않았습니다.")

        if ToGo == 'SENDER':
            result = self._httpget('/Message/?TG=' + ToGo, CorpNum, UserID)
        else:
            result = self._httpget('/KakaoTalk/?TG=' + ToGo, CorpNum, UserID)
        return result.url


Instruction:
Implement a function in Python 3 to
get Plus Friend Mgt URL.

Response:
def getPlusFriendMgtURL(self, CorpNum, UserID):
        """
        플러스친구 계정관리 팝업 URL
        :param CorpNum: 팝빌회원 사업자번호
        :param UserID: 팝빌회원 아이디
        :return: 팝빌 URL
        """
        result = self._httpget('/KakaoTalk/?TG=PLUSFRIEND', CorpNum, UserID)
        return result.url


Instruction:
How would you explain what the following Python 3 function does
def getATSTemplateMgtURL(self, CorpNum, UserID):
        result = self._httpget('/KakaoTalk/?TG=TEMPLATE', CorpNum, UserID)
        return result.url

Response: Get A TG URL


Instruction:
Can you implement a function in Python 3 that
gets the URL of the list of items.

Response:
def getSentListURL(self, CorpNum, UserID):
        """
        카카오톡 전송내역 팝업 URL
        :param CorpNum: 팝빌회원 사업자번호
        :param UserID: 팝빌회원 아이디
        :return: 팝빌 URL
        """
        result = self._httpget('/KakaoTalk/?TG=BOX', CorpNum, UserID)
        return result.url


Instruction:
Given the following Python 3 function, write the documentation
def sendATS_same(self, CorpNum, TemplateCode, Sender, Content, AltContent, AltSendType, SndDT, KakaoMessages,
                     UserID=None, RequestNum=None, ButtonList=None):
        """
       알림톡 대량 전송
       :param CorpNum: 팝빌회원 사업자번호
       :param TemplateCode: 템플릿코드
       :param Sender: 발신번호
       :param Content: [동보] 알림톡 내용
       :param AltContent: [동보] 대체문자 내용
       :param AltSendType: 대체문자 유형 [공백-미전송, C-알림톡내용, A-대체문자내용]
       :param SndDT: 예약일시 [작성형식 : yyyyMMddHHmmss]
       :param KakaoMessages: 알림톡 내용 (배열)
       :param UserID: 팝빌회원 아이디
       :param RequestNum : 요청번호
       :return: receiptNum (접수번호)
       """
        if TemplateCode is None or TemplateCode == '':
            raise PopbillException(-99999999, "알림톡 템플릿코드가 입력되지 않았습니다.")
        if Sender is None or Sender == '':
            raise PopbillException(-99999999, "발신번호가 입력되지 않았습니다.")

        req = {}

        if TemplateCode is not None or TemplateCode != '':
            req['templateCode'] = TemplateCode
        if Sender is not None or Sender != '':
            req['snd'] = Sender
        if Content is not None or Content != '':
            req['content'] = Content
        if AltContent is not None or AltContent != '':
            req['altContent'] = AltContent
        if AltSendType is not None or AltSendType != '':
            req['altSendType'] = AltSendType
        if SndDT is not None or SndDT != '':
            req['sndDT'] = SndDT
        if KakaoMessages is not None or KakaoMessages != '':
            req['msgs'] = KakaoMessages
        if ButtonList is not None:
            req['btns'] = ButtonList
        if RequestNum is not None or RequestNum != '':
            req['requestnum'] = RequestNum

        postData = self._stringtify(req)

        result = self._httppost('/ATS', postData, CorpNum, UserID)

        return result.receiptNum

Response: 전송 발신 번호 가 작성 발신 번호


Instruction:
Explain what the following Python 3 code does
def sendFTS_same(self, CorpNum, PlusFriendID, Sender, Content, AltContent, AltSendType, SndDT,
                     KakaoMessages, KakaoButtons, AdsYN=False, UserID=None, RequestNum=None):
        """
        친구톡 텍스트 대량 전송
        :param CorpNum: 팝빌회원 사업자번호
        :param PlusFriendID: 플러스친구 아이디
        :param Sender: 발신번호
        :param Content: [동보] 친구톡 내용
        :param AltContent: [동보] 대체문자 내용
        :param AltSendType: 대체문자 유형 [공백-미전송, C-알림톡내용, A-대체문자내용]
        :param SndDT: 예약일시 [작성형식 : yyyyMMddHHmmss]
        :param KakaoMessages: 친구톡 내용 (배열)
        :param KakaoButtons: 버튼 목록 (최대 5개)
        :param AdsYN: 광고 전송여부
        :param UserID: 팝빌회원 아이디
        :param RequestNum : 요청번호
        :return: receiptNum (접수번호)
        """
        if PlusFriendID is None or PlusFriendID == '':
            raise PopbillException(-99999999, "플러스친구 아이디가 입력되지 않았습니다.")
        if Sender is None or Sender == '':
            raise PopbillException(-99999999, "발신번호가 입력되지 않았습니다.")

        req = {}
        if PlusFriendID is not None or PlusFriendID != '':
            req['plusFriendID'] = PlusFriendID
        if Sender is not None or Sender != '':
            req['snd'] = Sender
        if AltSendType is not None or AltSendType != '':
            req['altSendType'] = AltSendType
        if Content is not None or Content != '':
            req['content'] = Content
        if AltContent is not None or AltContent != '':
            req['altContent'] = AltContent
        if SndDT is not None or SndDT != '':
            req['sndDT'] = SndDT
        if KakaoMessages:
            req['msgs'] = KakaoMessages
        if KakaoButtons:
            req['btns'] = KakaoButtons
        if AdsYN:
            req['adsYN'] = True
        if RequestNum is not None or RequestNum != '':
            req['requestNum'] = RequestNum

        postData = self._stringtify(req)

        result = self._httppost('/FTS', postData, CorpNum, UserID)

        return result.receiptNum

Response:
친구톡 텍스트 대량 전송
        :param CorpNum: 팝빌회원 사업자번호
        :param PlusFriendID: 플러스친구 아이디
        :param Sender: 발신번호
        :param Content: [동보] 친구톡 내용
        :param AltContent: [동보] 대체문자 내용
        :param AltSendType: 대체문자 유형 [공백-미전송, C-알림톡내용, A-대체문자내용]
        :param SndDT: 예약일시 [작성형식 : yyyyMMddHHmmss]
        :param KakaoMessages: 친구톡 내용 (배열)
        :param KakaoButtons: 버튼 목록 (최대 5개)
        :param AdsYN: 광고 전송여부
        :param UserID: 팝빌회원 아이디
        :param RequestNum : 요청번호
        :return: receiptNum (접수번호)


Instruction:
How would you implement a function in Python 3 that
gets UnitCost of a user.

Response:
def getUnitCost(self, CorpNum, MsgType, UserID=None):
        """
        전송단가 확인
        :param CorpNum: 팝빌회원 사업자번호
        :param MsgType: 카카오톡 유형
        :param UserID: 팝빌 회원아이디
        :return: unitCost
        """
        if MsgType is None or MsgType == "":
            raise PopbillException(-99999999, "전송유형이 입력되지 않았습니다.")

        result = self._httpget("/KakaoTalk/UnitCost?Type=" + MsgType, CorpNum)
        return float(result.unitCost)