Instruction:
Make a summary of the following Python 3 code
def convert_fn_elements(self):
        for footnote in self.main.getroot().findall('.//fn'):
            #Use only the first paragraph
            paragraph = footnote.find('p')
            #If no paragraph, move on
            if paragraph is None:
                remove(footnote)
                continue
            #Simply remove corrected errata items
            paragraph_text = str(etree.tostring(paragraph, method='text', encoding='utf-8'), encoding='utf-8')
            if paragraph_text.startswith('Erratum') and 'Corrected' in paragraph_text:
                remove(footnote)
                continue
            #Transfer some attribute information from the fn element to the paragraph
            if 'id' in footnote.attrib:
                paragraph.attrib['id'] = footnote.attrib['id']
            if 'fn-type' in footnote.attrib:
                paragraph.attrib['class'] = 'fn-type-{0}'.footnote.attrib['fn-type']
            else:
                paragraph.attrib['class'] = 'fn'
                #Replace the
            replace(footnote, paragraph)

Response: Convert all fn elements in the main text body into a list of nparrays.


Instruction:
Given the following Python 3 function, write the documentation
def convert_list_elements(self):
        #I have yet to gather many examples of this element, and may have to
        #write a recursive method for the processing of lists depending on how
        #PLoS produces their XML, for now this method is ignorant of nesting

        #TODO: prefix-words, one possible solution would be to have this method
        #edit the CSS to provide formatting support for arbitrary prefixes...

        #This is a block level element, so elevate it if found in p
        for list_el in self.main.getroot().findall('.//list'):
            if list_el.getparent().tag == 'p':
                elevate_element(list_el)

        #list_el is used instead of list (list is reserved)
        for list_el in self.main.getroot().findall('.//list'):
            if 'list-type' not in list_el.attrib:
                list_el_type = 'order'
            else:
                list_el_type = list_el.attrib['list-type']
            #Unordered lists
            if list_el_type in ['', 'bullet', 'simple']:
                list_el.tag = 'ul'
                #CSS must be used to recognize the class and suppress bullets
                if list_el_type == 'simple':
                    list_el.attrib['class'] = 'simple'
            #Ordered lists
            else:
                list_el.tag = 'ol'
                list_el.attrib['class'] = list_el_type
            #Convert the list-item element tags to 'li'
            for list_item in list_el.findall('list-item'):
                list_item.tag = 'li'
            remove_all_attributes(list_el, exclude=['id', 'class'])

Response: Convert the list elements to XML.


Instruction:
Can you generate the documentation for the following Python 3 function
def convert_def_list_elements(self):
        for def_list in self.main.getroot().findall('.//def-list'):
            #Remove the attributes, excepting id
            remove_all_attributes(def_list, exclude=['id'])
            #Modify the def-list element
            def_list.tag = 'div'
            def_list.attrib['class'] = 'def-list'
            for def_item in def_list.findall('def-item'):
                #Get the term being defined, modify it
                term = def_item.find('term')
                term.tag = 'p'
                term.attrib['class']= 'def-item-term'
                #Insert it before its parent def_item
                insert_before(def_item, term)
                #Get the definition, handle missing with a warning
                definition = def_item.find('def')
                if definition is None:
                    log.warning('Missing def element in def-item')
                    remove(def_item)
                    continue
                #PLoS appears to consistently place all definition text in a
                #paragraph subelement of the def element
                def_para = definition.find('p')
                def_para.attrib['class'] = 'def-item-def'
                #Replace the def-item element with the p element
                replace(def_item, def_para)

Response: This method converts the XML elements in the def - list element to a list of elements which are in turn of two parts.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def convert_ref_list_elements(self):
        #TODO: Handle nested ref-lists
        for ref_list in self.main.getroot().findall('.//ref-list'):
            remove_all_attributes(ref_list)
            ref_list.tag = 'div'
            ref_list.attrib['class'] = 'ref-list'
            label = ref_list.find('label')
            if label is not None:
                label.tag = 'h3'
            for ref in ref_list.findall('ref'):
                ref_p = etree.Element('p')
                ref_p.text = str(etree.tostring(ref, method='text', encoding='utf-8'), encoding='utf-8')
                replace(ref, ref_p)

Response: Convert all the ref - list elements in the article to the appropriate format.


Instruction:
Can you create a Python 3 function that
converts JPTS 3. 0 <table - wrap > elements to EPUB content.

Response:
def convert_table_wrap_elements(self):
        """
        Responsible for the correct conversion of JPTS 3.0 <table-wrap>
        elements to EPUB content.

        The 'id' attribute is treated as mandatory by this method.
        """
        for table_wrap in self.main.getroot().findall('.//table-wrap'):

            table_div = etree.Element('div', {'id': table_wrap.attrib['id']})

            label = table_wrap.find('label')
            caption = table_wrap.find('caption')
            alternatives = table_wrap.find('alternatives')
            graphic = table_wrap.find('graphic')
            table = table_wrap.find('table')
            if graphic is None:
                if alternatives is not None:
                    graphic = alternatives.find('graphic')
            if table is None:
                if alternatives is not None:
                    table = alternatives.find('table')

            #Handling the label and caption
            if label is not None and caption is not None:
                caption_div = etree.Element('div', {'class': 'table-caption'})
                caption_div_b = etree.SubElement(caption_div, 'b')
                if label is not None:
                    append_all_below(caption_div_b, label)
                if caption is not None:
                    #Find, optional, title element and paragraph elements
                    caption_title = caption.find('title')
                    if caption_title is not None:
                        append_all_below(caption_div_b, caption_title)
                    caption_ps = caption.findall('p')
                    #For title and each paragraph, give children to the div
                    for caption_p in caption_ps:
                        append_all_below(caption_div, caption_p)
                #Add this to the table div
                table_div.append(caption_div)

            ### Practical Description ###
            #A table may have both, one of, or neither of graphic and table
            #The different combinations should be handled, but a table-wrap
            #with neither should fail with an error
            #
            #If there is both an image and a table, the image should be placed
            #in the text flow with a link to the html table
            #
            #If there is an image and no table, the image should be placed in
            #the text flow without a link to an html table
            #
            #If there is a table with no image, then the table should be placed
            #in the text flow.

            if graphic is not None:
                #Create the image path for the graphic
                xlink_href = ns_format(graphic, 'xlink:href')
                graphic_xlink_href = graphic.attrib[xlink_href]
                file_name = graphic_xlink_href.split('.')[-1] + '.png'
                img_dir = 'images-' + self.doi_suffix()
                img_path = '/'.join([img_dir, file_name])
                #Create the new img element
                img_element = etree.Element('img', {'alt': 'A Table',
                                                    'src': img_path,
                                                    'class': 'table'})
                #Add this to the table div
                table_div.append(img_element)
                #If table, add it to the list, and link to it
                if table is not None:  # Both graphic and table
                    #The label attribute is just a means of transmitting some
                    #plaintext which will be used for the labeling in the html
                    #tables file
                    div = etree.SubElement(self.tables.find('body'),
                                           'div',
                                           {'id': table_wrap.attrib['id']})

                    if label is not None:
                        bold_label = etree.SubElement(div, 'b')
                        append_all_below(bold_label, label)
                    #Add the table to the tables list
                    div.append(deepcopy(table))
                    #Also add the table's foot if it exists
                    table_wrap_foot = table_wrap.find('table-wrap-foot')
                    if table_wrap_foot is not None:
                        table_wrap_foot.tag = 'div'
                        table_wrap_foot.attrib['class'] = 'table-wrap-foot'
                        div.append(table_wrap_foot)
                    #Create a link to the html version of the table
                    html_table_link = etree.Element('a')
                    html_table_link.attrib['href'] = self.tables_fragment.format(table_wrap.attrib['id'])
                    html_table_link.text = 'Go to HTML version of this table'
                    #Add this to the table div
                    table_div.append(html_table_link)
                    remove(table)

            elif table is not None:  # Table only
                #Simply append the table to the table div
                table_div.append(table)
            elif graphic is None and table is None:
                sys.exit('Encountered table-wrap element with neither graphic nor table. Exiting.')

            #Replace the original table-wrap with the newly constructed div
            replace(table_wrap, table_div)


Instruction:
Can you create a Python 3 function that
converts all graphic elements in the main XML file into a single image.

Response:
def convert_graphic_elements(self):
        """
        This is a method for the odd special cases where <graphic> elements are
        standalone, or rather, not a part of a standard graphical element such
        as a figure or a table. This method should always be employed after the
        standard cases have already been handled.
        """
        for graphic in self.main.getroot().findall('.//graphic'):
            graphic.tag = 'img'
            graphic.attrib['alt'] = 'unowned-graphic'
            ns_xlink_href = ns_format(graphic, 'xlink:href')
            if ns_xlink_href in graphic.attrib:
                xlink_href = graphic.attrib[ns_xlink_href]
                file_name = xlink_href.split('.')[-1] + '.png'
                img_dir = 'images-' + self.doi_suffix()
                img_path = '/'.join([img_dir, file_name])
                graphic.attrib['src'] = img_path
            remove_all_attributes(graphic, exclude=['id', 'class', 'alt', 'src'])


Instruction:
Here you have a function in Python 3, explain what it does
def getChargeInfo(self, CorpNum, MsgType, UserID=None):
        if MsgType == None or MsgType == "":
            raise PopbillException(-99999999, "전송유형이 입력되지 않았습니다.")

        return self._httpget('/Message/ChargeInfo?Type=' + MsgType, CorpNum, UserID)

Response:
과금정보 확인
            args
                CorpNum : 회원 사업자번호
                MsgType : 문자전송 유형
                UserID : 팝빌 회원아이디
            return
                과금정보 객체
            raise
                PopbillException


Instruction:
Make a summary of the following Python 3 code
def sendMMS_Multi(self, CorpNum, Sender, Subject, Contents, Messages, FilePath, reserveDT, adsYN=False, UserID=None,
                      RequestNum=None):
        """ 멀티 문자메시지 다량 전송
            args
                CorpNum : 팝빌회원 사업자번호
                Sender : 발신자번호 (동보전송용)
                Subject : 장문 메시지 제목 (동보전송용)
                Contents : 장문 문자 내용 (동보전송용)
                Messages : 개별전송정보 배열
                FilePath : 전송하고자 하는 파일 경로
                reserveDT : 예약전송시간 (형식. yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                RequestNum = 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException
        """
        if Messages == None or len(Messages) < 1:
            raise PopbillException(-99999999, "전송할 메시지가 입력되지 않았습니다.")

        req = {}

        if Sender != None or Sender != '':
            req['snd'] = Sender
        if Contents != None or Contents != '':
            req['content'] = Contents
        if Subject != None or Subject != '':
            req['subject'] = Subject
        if reserveDT != None or reserveDT != '':
            req['sndDT'] = reserveDT
        if Messages != None or Messages != '':
            req['msgs'] = Messages
        if RequestNum != None or RequestNum != '':
            req['requestNum'] = RequestNum
        if adsYN:
            req['adsYN'] = True

        postData = self._stringtify(req)

        files = []
        try:
            with open(FilePath, "rb") as F:
                files = [File(fieldName='file',
                              fileName=F.name,
                              fileData=F.read())]
        except IOError:
            raise PopbillException(-99999999, "해당경로에 파일이 없거나 읽을 수 없습니다.")

        result = self._httppost_files('/MMS', postData, files, CorpNum, UserID)

        return result.receiptNum

Response:
멀티 문자메시지 다량 전송
            args
                CorpNum : 팝빌회원 사업자번호
                Sender : 발신자번호 (동보전송용)
                Subject : 장문 메시지 제목 (동보전송용)
                Contents : 장문 문자 내용 (동보전송용)
                Messages : 개별전송정보 배열
                FilePath : 전송하고자 하는 파일 경로
                reserveDT : 예약전송시간 (형식. yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                RequestNum = 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException


Instruction:
Here you have a function in Python 3, explain what it does
def sendMessage(self, MsgType, CorpNum, Sender, SenderName, Subject, Contents, Messages, reserveDT, adsYN=False,
                    UserID=None, RequestNum=None):
        """ 문자 메시지 전송
            args
                MsgType : 문자 전송 유형(단문:SMS, 장문:LMS, 단/장문:XMS)
                CorpNum : 팝빌회원 사업자번호
                Sender : 발신자번호 (동보전송용)
                Subject : 장문 메시지 제목 (동보전송용)
                Contents : 장문 문자 내용 (동보전송용)
                Messages : 개별전송정보 배열
                reserveDT : 예약전송시간 (형식. yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                RequestNum : 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException
        """
        if MsgType == None or MsgType == '':
            raise PopbillException(-99999999, "문자 전송 유형이 입력되지 않았습니다.")

        if Messages == None or len(Messages) < 1:
            raise PopbillException(-99999999, "전송할 메시지가 입력되지 않았습니다.")

        req = {}

        if Sender != None or Sender != '':
            req['snd'] = Sender
        if SenderName != None or SenderName != '':
            req['sndnm'] = SenderName
        if Contents != None or Contents != '':
            req['content'] = Contents
        if Subject != None or Subject != '':
            req['subject'] = Subject
        if reserveDT != None or reserveDT != '':
            req['sndDT'] = reserveDT
        if Messages != None or Messages != '':
            req['msgs'] = Messages
        if RequestNum != None or RequestNum != '':
            req['requestnum'] = RequestNum
        if adsYN:
            req['adsYN'] = True

        postData = self._stringtify(req)

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

        return result.receiptNum

Response:
문자 메시지 전송
            args
                MsgType : 문자 전송 유형(단문:SMS, 장문:LMS, 단/장문:XMS)
                CorpNum : 팝빌회원 사업자번호
                Sender : 발신자번호 (동보전송용)
                Subject : 장문 메시지 제목 (동보전송용)
                Contents : 장문 문자 내용 (동보전송용)
                Messages : 개별전송정보 배열
                reserveDT : 예약전송시간 (형식. yyyyMMddHHmmss)
                UserID : 팝빌회원 아이디
                RequestNum : 전송요청번호
            return
                접수번호 (receiptNum)
            raise
                PopbillException


Instruction:
Write a Python 3 script for
canceling a reserve request.

Response:
def cancelReserveRN(self, CorpNum, RequestNum, UserID=None):
        """ 문자 예약전송 취소
            args
                CorpNum : 팝빌회원 사업자번호
                RequestNum : 전송요청시 할당한 전송요청번호
                UserID : 팝빌회원 아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """
        if RequestNum == None or RequestNum == '':
            raise PopbillException(-99999999, "요청번호가 입력되지 않았습니다.")

        return self._httpget('/Message/Cancel/' + RequestNum, CorpNum, UserID)


Instruction:
Here you have a function in Python 3, explain what it does
def getURL(self, CorpNum, UserID, ToGo):
        if ToGo == None or ToGo == '':
            raise PopbillException(-99999999, "TOGO값이 입력되지 않았습니다.")

        result = self._httpget('/Message/?TG=' + ToGo, CorpNum, UserID)

        return result.url

Response:
문자 관련 팝빌 URL
            args
                CorpNum : 팝빌회원 사업자번호
                UserID : 팝빌회원 아이디
                TOGO : BOX (전송내역조회 팝업)
            return
                팝빌 URL
            raise
                PopbillException


Instruction:
Given the following Python 3 function, write the documentation
def getStates(self, Corpnum, reciptNumList, UserID=None):
        if reciptNumList == None or len(reciptNumList) < 1:
            raise PopbillException(-99999999, "접수번호가 입력되지 않았습니다.")

        postData = self._stringtify(reciptNumList)

        return self._httppost('/Message/States', postData, Corpnum, UserID)

Response:
전송내역 요약정보 확인
            args
                CorpNum : 팝빌회원 사업자번호
                reciptNumList : 문자전송 접수번호 배열
                UserID : 팝빌회원 아이디
            return
                전송정보 as list
            raise
                PopbillException


Instruction:
Can you tell what is the following Python 3 function doing
def funcGauss1D(x, mu, sig):
    arrOut = np.exp(-np.power((x - mu)/sig, 2.)/2)
    # normalize
    arrOut = arrOut/(np.sqrt(2.*np.pi)*sig)

    return arrOut

Response:
Create 1D Gaussian. Source :
    http://mathworld. wolfram. com / GaussianFunction. html


Instruction:
Can you generate a brief explanation for the following Python 3 code
def absolute_path(user_path):
    if os.path.abspath(user_path):
        return unix_path_coercion(user_path)
    else:
        try:
            openaccess_epub.utils.evaluate_relative_path(relative=user_path)
        except:
            raise ValidationError('This path could not be rendered as absolute')

Response: Convert user_path to absolute path.


Instruction:
Write a Python 3 script for
configuring the quickstart base control loops for user interaction during quickstart configuration.

Response:
def configure(default=None, dev=None):
    """
    The inner control loops for user interaction during quickstart
    configuration.
    """
    cache_loc = openaccess_epub.utils.cache_location()
    config_loc = openaccess_epub.utils.config_location()

    #Make the cache directory
    openaccess_epub.utils.mkdir_p(cache_loc)

    defaults = {'now': time.asctime(),
                'oae-version': openaccess_epub.__version__,
                'cache-location': unix_path_coercion(cache_loc),
                'input-relative-images': 'images-*',
                'use-input-relative-images': 'y',
                'image-cache': os.path.join(cache_loc, 'img_cache'),
                'use-image-cache': 'n',
                'use-image-fetching': 'y',
                'default-output': '.',
                'input-relative-css': '.',
                'epubcheck-jarfile': os.path.join(cache_loc,
                                                 'epubcheck-3.0',
                                                 'epubcheck-3.0.jar')}

    if default or dev:  # Skip interactive and apply defaults
        #Pass through the validation/modification steps
        if dev:  # The only current difference between dev and default
            defaults['use-image-cache'] = 'y'
        defaults['input-relative-images'] = list_opts(defaults['input-relative-images'])
        defaults['use-input-relative-images'] = boolean(defaults['use-input-relative-images'])
        defaults['image-cache'] = absolute_path(defaults['image-cache'])
        defaults['use-image-cache'] = boolean(defaults['use-image-cache'])
        defaults['use-image-fetching'] = boolean(defaults['use-image-fetching'])
        defaults['default-output'] = nonempty(defaults['default-output'])
        defaults['input-relative-css'] = nonempty(defaults['input-relative-css'])
        defaults['epubcheck-jarfile'] = absolute_path(defaults['epubcheck-jarfile'])
        config = config_formatter(CONFIG_TEXT, defaults)

        with open(config_loc, 'wb') as conf_out:
            conf_out.write(bytes(config, 'UTF-8'))
        print('The config file has been written to {0}'.format(config_loc))
        return

    config_dict = {'now': time.asctime(),
                   'oae-version': openaccess_epub.__version__,
                   'cache-location': unix_path_coercion(cache_loc)}

    print('''\nWelcome to the interactive configuration for OpenAccess_EPUB''')
    print('''
Please enter values for the following settings. To accept the default value
for the settings, shown in brackets, just push Enter.

-------------------------------------------------------------------------------\
''')
    print('''
OpenAccess_EPUB defines a default cache location for the storage of various
data (and the global config.py file), this location is:\n\n{0}
'''.format(cache_loc))

    input('Press Enter to start...')

    #Image Configuration
    print('''
 -- Configure Image Behavior --

When OpenAccess_EPUB is executed using the oaepub script, it can find the
images for the input articles using the following strategies (in order of
preference):

 Input-Relative: a path relative to the input file
 Cached Images: locate the images in a cache
 Fetched Online: attempts to download from the Internet (may fail)

We'll configure some values for each of these, and you\'ll also have the option
to turn them off.''')
    #Input-relative image details
    print('''
Where should OpenAccess_EPUB look for images relative to the input file?
A star "*" may be used as a wildcard to match the name of the input file.
Multiple path values may be specified if separated by commas.''')
    user_prompt(config_dict, 'input-relative-images', 'Input-relative images?:',
                default=defaults['input-relative-images'], validator=list_opts)
    print('''
Should OpenAccess_EPUB look for images relative to the input file by default?\
''')
    user_prompt(config_dict, 'use-input-relative-images',
                'Use input-relative images?: (Y/n)',
                default=defaults['use-input-relative-images'],
                validator=boolean)
    #Image cache details
    print('''
Where should OpenAccess_EPUB place the image cache?''')
    user_prompt(config_dict, 'image-cache', 'Image cache?:',
                default=defaults['image-cache'],
                validator=absolute_path)
    print('''
Should OpenAccess_EPUB use the image cache by default? This feature is intended
for developers and testers without local access to the image files and will
consume extra disk space for storage.''')
    user_prompt(config_dict, 'use-image-cache', 'Use image cache?: (y/N)',
                default=defaults['use-image-cache'],
                validator=boolean)
    #Image fetching online details
    print('''
Should OpenAccess_EPUB attempt to download the images from the Internet? This
is not supported for all publishers and not 100% guaranteed to succeed, you may
need to download them manually if this does not work.''')
    user_prompt(config_dict, 'use-image-fetching', 'Attempt image download?: (Y/n)',
                default=defaults['use-image-fetching'],
                validator=boolean)
    #Output configuration
    print('''
 -- Configure Output Behavior --

OpenAccess_EPUB produces ePub and log files as output. The following options
will determine what is done with these.

Where should OpenAccess_EPUB place the output ePub and log files? If you supply
a relative path, the output path will be relative to the input; if you supply
an absolute path, the output will always be placed there. The default behavior
is to place them in the same directory as the input.''')
    user_prompt(config_dict, 'default-output', 'Output path?:',
                default=defaults['default-output'],
                validator=nonempty)
    print('''
 -- Configure CSS Behavior --

ePub files use CSS for improved styling, and ePub-readers must support a basic
subset of CSS functions. OpenAccess_EPUB provides a default CSS file, but a
manual one may be supplied, relative to the input. Please define an
appropriate input-relative path.''')
    user_prompt(config_dict, 'input-relative-css', 'Input-relative CSS path?:',
                default=defaults['input-relative-css'],
                validator=nonempty)
    print('''
 -- Configure EpubCheck --

EpubCheck is a program written and maintained by the IDPF as a tool to validate
ePub. In order to use it, your system must have Java installed and it is
recommended to use the latest version. Downloads of this program are found here:

https://github.com/IDPF/epubcheck/releases

Once you have downloaded the zip file for the program, unzip the archive and
write a path to the .jar file here.''')
    user_prompt(config_dict, 'epubcheck-jarfile', 'Absolute path to epubcheck?:',
                default=defaults['epubcheck-jarfile'], validator=absolute_path)
    #Write the config.py file
    config = config_formatter(CONFIG_TEXT, config_dict)
    with open(config_loc, 'wb') as conf_out:
        conf_out.write(bytes(config, 'UTF-8'))
    print('''
Done configuring OpenAccess_EPUB!''')


Instruction:
Here you have a function in Python 3, explain what it does
def checkMgtKeyInUse(self, CorpNum, MgtKeyType, MgtKey):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        try:
            result = self._httpget('/Taxinvoice/' + MgtKeyType + "/" + MgtKey, CorpNum)
            return result.itemKey != None and result.itemKey != ""
        except PopbillException as PE:
            if PE.code == -11000005:
                return False
            raise PE

Response: Check if a MgtKey is in the list of items in the CorpNum.


Instruction:
Implement a function in Python 3 to
register a new Taxinvoice.

Response:
def register(self, CorpNum, taxinvoice, writeSpecification=False, UserID=None):
        """ 임시저장
            args
                CorpNum : 회원 사업자 번호
                taxinvoice : 등록할 세금계산서 object. Made with Taxinvoice(...)
                writeSpecification : 등록시 거래명세서 동시 작성 여부
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """
        if taxinvoice == None:
            raise PopbillException(-99999999, "등록할 세금계산서 정보가 입력되지 않았습니다.")
        if writeSpecification:
            taxinvoice.writeSpecification = True

        postData = self._stringtify(taxinvoice)

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


Instruction:
Here you have a function in Python 3, explain what it does
def update(self, CorpNum, MgtKeyType, MgtKey, taxinvoice, writeSpecification=False, UserID=None):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
        if taxinvoice == None:
            raise PopbillException(-99999999, "수정할 세금계산서 정보가 입력되지 않았습니다.")
        if writeSpecification:
            taxinvoice.writeSpecification = True

        postData = self._stringtify(taxinvoice)

        return self._httppost('/Taxinvoice/' + MgtKeyType + '/' + MgtKey, postData, CorpNum, UserID, 'PATCH')

Response: Update a Taxinvoice in the given CorpNum.


Instruction:
Given the following Python 3 function, write the documentation
def getInfo(self, CorpNum, MgtKeyType, MgtKey):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

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

Response: Get information about a particular Tax item.


Instruction:
How would you explain what the following Python 3 function does
def getDetailInfo(self, CorpNum, MgtKeyType, MgtKey):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httpget('/Taxinvoice/' + MgtKeyType + "/" + MgtKey + "?Detail", CorpNum)

Response: Get the details of a particular Tax item.


Instruction:
Given the following Python 3 function, write the documentation
def delete(self, CorpNum, MgtKeyType, MgtKey, UserID=None):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

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

Response: Delete a Tax entry.


Instruction:
Write a Python 3 script for
sending an email to a tax invoice.

Response:
def send(self, CorpNum, MgtKeyType, MgtKey, Memo=None, EmailSubject=None, UserID=None):
        """ 승인요청
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
                Memo : 처리 메모
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        req = {}

        if Memo != None and Memo != '':
            req["memo"] = Memo
        if EmailSubject != None and EmailSubject != '':
            req["emailSubject"] = EmailSubject

        postData = self._stringtify(req)

        return self._httppost('/Taxinvoice/' + MgtKeyType + "/" + MgtKey, postData, CorpNum, UserID, "SEND")


Instruction:
Explain what the following Python 3 code does
def cancelSend(self, CorpNum, MgtKeyType, MgtKey, Memo=None, UserID=None):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        if Memo != None and Memo != '':
            postData = self._stringtify({"memo": Memo})
        else:
            postData = ''

        return self._httppost('/Taxinvoice/' + MgtKeyType + "/" + MgtKey, postData, CorpNum, UserID, "CANCELSEND")

Response:
승인요청 취소
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
                Memo : 처리 메모
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException


Instruction:
Can you write a function in Python 3 where it
issues a new message in the specified MgtKey.

Response:
def issue(self, CorpNum, MgtKeyType, MgtKey, Memo=None, EmailSubject=None, ForceIssue=False, UserID=None):
        """ 발행
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
                Memo : 처리 메모
                EmailSubject : 발행메일 이메일 제목
                ForceIssue : 지연발행 세금계산서 강제발행 여부.
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        req = {"forceIssue": ForceIssue}

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

        if EmailSubject != None and EmailSubject != '':
            req["emailSubject"] = EmailSubject

        postData = self._stringtify(req)

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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sendToNTS(self, CorpNum, MgtKeyType, MgtKey, UserID=None):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        postData = ''

        return self._httppost('/Taxinvoice/' + MgtKeyType + "/" + MgtKey, postData, CorpNum, UserID, "NTS")

Response:
국세청 즉시전송
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException


Instruction:
Explain what the following Python 3 code does
def getFiles(self, CorpNum, MgtKeyType, MgtKey):
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        return self._httpget('/Taxinvoice/' + MgtKeyType + "/" + MgtKey + "/Files", CorpNum)

Response:
첨부파일 목록 확인
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
            return
                첩부파일 정보 목록 as List
            raise
                PopbillException


Instruction:
Write a Python 3 script for
deleting a file from a Taxinvoice.

Response:
def deleteFile(self, CorpNum, MgtKeyType, MgtKey, FileID, UserID=None):
        """ 첨부파일 삭제
            args
                CorpNum : 회원 사업자 번호
                MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
                MgtKey : 파트너 관리번호
                UserID : 팝빌 회원아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """
        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")
        if FileID == None or FileID == "":
            raise PopbillException(-99999999, "파일아이디가 입력되지 않았습니다.")

        postData = ''

        return self._httppost('/Taxinvoice/' + MgtKeyType + "/" + MgtKey + "/Files/" + FileID, postData, CorpNum,
                              UserID, 'DELETE')


Instruction:
Here you have a function in Python 3, explain what it does
def getMassPrintURL(self, CorpNum, MgtKeyType, MgtKeyList, UserID=None):
        if MgtKeyList == None or len(MgtKeyList) < 1:
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        postData = self._stringtify(MgtKeyList)

        Result = self._httppost('/Taxinvoice/' + MgtKeyType + "?Print", postData, CorpNum, UserID)

        return Result.url

Response: Get the URL of a particular Tax item.


Instruction:
Make a summary of the following Python 3 code
def search(self, CorpNum, MgtKeyType, DType, SDate, EDate, State, Type, TaxType, LateOnly, TaxRegIDYN, TaxRegIDType,
               TaxRegID, Page, PerPage, Order, UserID=None, QString=None, InterOPYN=None, IssueType=None):
        """ 목록 조회
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKeyType : 세금계산서유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
                DType : 일자유형, R-등록일시, W-작성일자, I-발행일시 중 택 1
                SDate : 시작일자, 표시형식(yyyyMMdd)
                EDate : 종료일자, 표시형식(yyyyMMdd)
                State : 상태코드, 2,3번째 자리에 와일드카드(*) 사용가능
                Type : 문서형태 배열, N-일반세금계산서, M-수정세금계산서
                TaxType : 과세형태 배열, T-과세, N-면세, Z-영세
                LateOnly : 지연발행, 공백-전체조회, 0-정상발행조회, 1-지연발행 조회
                TaxRegIdYN : 종사업장번호 유무, 공백-전체조회, 0-종사업장번호 없음 1-종사업장번호 있음
                TaxRegIDType : 종사업장번호 사업자유형, S-공급자, B-공급받는자, T-수탁자
                TaxRegID : 종사업장번호, 콤마(,)로 구분하여 구성 ex)'0001,1234'
                Page : 페이지번호
                PerPage : 페이지당 목록개수
                Order : 정렬방향, D-내림차순, A-오름차순
                UserID : 팝빌 회원아이디
                QString : 거래처 정보, 거래처 상호 또는 사업자등록번호 기재, 미기재시 전체조회
                InterOPYN : 연동문서 여부, 공백-전체조회, 0-일반문서 조회, 1-연동문서 조회
                IssueType : 발행형태 배열, N-정발행, R-역발행, T-위수탁
            return
                조회목록 Object
            raise
                PopbillException
        """

        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")

        if DType == None or DType == '':
            raise PopbillException(-99999999, "일자유형이 입력되지 않았습니다.")

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

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

        uri = '/Taxinvoice/' + MgtKeyType
        uri += '?DType=' + DType
        uri += '&SDate=' + SDate
        uri += '&EDate=' + EDate
        uri += '&State=' + ','.join(State)
        uri += '&Type=' + ','.join(Type)
        uri += '&TaxType=' + ','.join(TaxType)
        uri += '&TaxRegIDType=' + TaxRegIDType
        uri += '&TaxRegID=' + TaxRegID
        uri += '&Page=' + str(Page)
        uri += '&PerPage=' + str(PerPage)
        uri += '&Order=' + Order
        uri += '&InterOPYN=' + InterOPYN

        if LateOnly != '':
            uri += '&LateOnly=' + LateOnly
        if TaxRegIDYN != '':
            uri += '&TaxRegIDType=' + TaxRegIDType

        if QString is not None:
            uri += '&QString=' + QString

        if IssueType is not None:
            uri += '&IssueType=' + ','.join(IssueType)

        return self._httpget(uri, CorpNum, UserID)

Response:
목록 조회
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKeyType : 세금계산서유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
                DType : 일자유형, R-등록일시, W-작성일자, I-발행일시 중 택 1
                SDate : 시작일자, 표시형식(yyyyMMdd)
                EDate : 종료일자, 표시형식(yyyyMMdd)
                State : 상태코드, 2,3번째 자리에 와일드카드(*) 사용가능
                Type : 문서형태 배열, N-일반세금계산서, M-수정세금계산서
                TaxType : 과세형태 배열, T-과세, N-면세, Z-영세
                LateOnly : 지연발행, 공백-전체조회, 0-정상발행조회, 1-지연발행 조회
                TaxRegIdYN : 종사업장번호 유무, 공백-전체조회, 0-종사업장번호 없음 1-종사업장번호 있음
                TaxRegIDType : 종사업장번호 사업자유형, S-공급자, B-공급받는자, T-수탁자
                TaxRegID : 종사업장번호, 콤마(,)로 구분하여 구성 ex)'0001,1234'
                Page : 페이지번호
                PerPage : 페이지당 목록개수
                Order : 정렬방향, D-내림차순, A-오름차순
                UserID : 팝빌 회원아이디
                QString : 거래처 정보, 거래처 상호 또는 사업자등록번호 기재, 미기재시 전체조회
                InterOPYN : 연동문서 여부, 공백-전체조회, 0-일반문서 조회, 1-연동문서 조회
                IssueType : 발행형태 배열, N-정발행, R-역발행, T-위수탁
            return
                조회목록 Object
            raise
                PopbillException


Instruction:
Create a Python 3 function for
attaching a statement to a CorpNum.

Response:
def attachStatement(self, CorpNum, MgtKeyType, MgtKey, ItemCode, StmtMgtKey, UserID=None):
        """ 전자명세서 첨부
            args
                CorpNum : 팝빌회원 사업자번호
                MgtKeyType : 세금계산서 유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
                MgtKey : 세금계산서 문서관리번호
                StmtCode : 명세서 종류코드, 121-명세서, 122-청구서, 123-견적서, 124-발주서 125-입금표, 126-영수증
                StmtMgtKey : 전자명세서 문서관리번호
                UserID : 팝빌회원 아이디
            return
                처리결과. consist of code and message
            raise
                PopbillException
        """

        if MgtKeyType not in self.__MgtKeyTypes:
            raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.")
        if MgtKey == None or MgtKey == "":
            raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.")

        uri = '/Taxinvoice/' + MgtKeyType + '/' + MgtKey + '/AttachStmt'

        postData = self._stringtify({"ItemCode": ItemCode, "MgtKey": StmtMgtKey})

        return self._httppost(uri, postData, CorpNum, UserID)


Instruction:
How would you explain what the following Python 3 function does
def assignMgtKey(self, CorpNum, MgtKeyType, ItemKey, MgtKey, UserID=None):
        if MgtKeyType == None or MgtKeyType == '':
            raise PopbillException(-99999999, "세금계산서 발행유형이 입력되지 않았습니다.")

        if ItemKey == None or ItemKey == '':
            raise PopbillException(-99999999, "아이템키가 입력되지 않았습니다.")

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

        postDate = "MgtKey=" + MgtKey
        return self._httppost('/Taxinvoice/' + ItemKey + '/' + MgtKeyType, postDate, CorpNum, UserID, "",
                              "application/x-www-form-urlencoded; charset=utf-8")

Response: Assign a new MgtKey to a CorpNum.


Instruction:
Explain what the following Python 3 code does
def getSealURL(self, CorpNum, UserID):
        result = self._httpget('/?TG=SEAL', CorpNum, UserID)
        return result.url

Response: Get the URL of the Seal.


Instruction:
Create a Python 3 function for
getting Tax Cert URL.

Response:
def getTaxCertURL(self, CorpNum, UserID):
        """ 공인인증서 등록 URL
            args
                CorpNum : 회원 사업자번호
                UserID  : 회원 팝빌아이디
            return
                30초 보안 토큰을 포함한 url
            raise
                PopbillException
        """
        result = self._httpget('/?TG=CERT', CorpNum, UserID)
        return result.url


Instruction:
Can you tell what is the following Python 3 function doing
def encloses(self,
                 location: FileLocation
                 ) -> Optional[FunctionDesc]:
        """
        Returns the function, if any, that encloses a given location.
        """
        for func in self.in_file(location.filename):
            if location in func.location:
                return func
        return None

Response: Returns the function that encloses a given location.


Instruction:
Write a Python 3 function that can
return an iterator over all functions that are contained within a given file.

Response:
def in_file(self, filename: str) -> Iterator[FunctionDesc]:
        """
        Returns an iterator over all of the functions definitions that are
        contained within a given file.
        """
        yield from self.__filename_to_functions.get(filename, [])


Instruction:
Write a Python 3 function for
creating or load pRF model time courses.

Response:
def model_creation_opt(dicCnfg, aryMdlParams, strPathHrf=None, varRat=None,
                       lgcPrint=True):
    """
    Create or load pRF model time courses.

    Parameters
    ----------
    dicCnfg : dict
        Dictionary containing config parameters.
    aryMdlParams : numpy arrays
        x, y and sigma parameters.
    strPathHrf : str or None:
        Path to npy file with custom hrf parameters. If None, default
        parameters will be used.
    varRat : float, default None
        Ratio of size suppressive surround to size of center pRF
    lgcPrint : boolean
        Whether print statements should be executed.

    Returns
    -------
    aryPrfTc : np.array
        4D numpy array with pRF time course models, with following dimensions:
        `aryPrfTc[x-position, y-position, SD, volume]`.
    """
    # *************************************************************************
    # *** Load parameters from config file

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

    if cfg.lgcCrteMdl:

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

        arySptExpInf = np.load(cfg.strSptExpInf)

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

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

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

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

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

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

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

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

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

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

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

        del(arySptExpInf)

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

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

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

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

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

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

    return aryPrfTc


Instruction:
Make a summary of the following Python 3 code
def get_entry(journal_location, date):
    if not isinstance(date, datetime.date):
        return None
    try:
        with open(build_journal_path(journal_location, date), "r") as entry_file:
            return entry_file.read()
    except IOError:
        return None

Response: returns the entry text of the specified date


Instruction:
Can you write a function in Python 3 where it
normalizes SPM HRF function from sum of two gamma PDFs Parameters ---------- t : array-like vector of times at which to sample HRF Returns ------- hrf : array vector length ``len(t)`` of samples from HRF at times `t` Notes ----- [1] This is the canonical HRF function as used in SPM. It has the following defaults: - delay of response (relative to onset) : 6s - delay of undershoot (relative to onset) : 16s - dispersion of response : 1s - dispersion of undershoot : 1s - ratio of response to undershoot : 6s - onset : 0s - length of kernel : 32s References: ----- [1] http://nipy.org/ [2] https://github.com/fabianp/hrf_estimation

Response:
def spmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1,
         p_u_ratio=6):
    """Normalized SPM HRF function from sum of two gamma PDFs

    Parameters
    ----------
    t : array-like
        vector of times at which to sample HRF

    Returns
    -------
    hrf : array
        vector length ``len(t)`` of samples from HRF at times `t`

    Notes
    -----
    [1] This is the canonical HRF function as used in SPM. It
    has the following defaults:
        - delay of response (relative to onset) : 6s
        - delay of undershoot (relative to onset) : 16s
        - dispersion of response : 1s
        - dispersion of undershoot : 1s
        - ratio of response to undershoot : 6s
        - onset : 0s
        - length of kernel : 32s

    References:
    -----
    [1] http://nipy.org/
    [2] https://github.com/fabianp/hrf_estimation
    """
    return spm_hrf_compat(t, peak_delay=peak_delay, under_delay=under_delay,
                          peak_disp=peak_disp, under_disp=under_disp,
                          p_u_ratio=p_u_ratio, normalize=True)


Instruction:
Write a Python 3 function that can
compute the canonical HRF dispersion derivative function for the given time values t.

Response:
def ddspmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1,
           p_u_ratio=6):
    """ SPM canonical HRF dispersion derivative, values for time values `t`

    Parameters
    ----------
    t : array-like
        vector of times at which to sample HRF

    Returns
    -------
    hrf : array
        vector length ``len(t)`` of samples from HRF at times `t`

    Notes
    -----
    [1] This is the canonical HRF dispersion derivative function as used in SPM
    [2] It is the numerical difference between the HRF sampled at time `t`, and
    values at `t` for another HRF shape with a small change in the peak
    dispersion parameter (``peak_disp`` in func:`spm_hrf_compat`).

    References:
    -----
    [1] http://nipy.org/
    [2] https://github.com/fabianp/hrf_estimation
    """

    _spm_dd_func = partial(spmt, peak_delay=peak_delay,
                           under_delay=under_delay,
                           under_disp=under_disp, p_u_ratio=p_u_ratio,
                           peak_disp=1.01)

    return (spmt(t) - _spm_dd_func(t)) / 0.01


Instruction:
Can you tell what is the following Python 3 function doing
def create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol,
                  aryExclCnd=None, varTmpOvsmpl=1000.):
    """
    Creation of condition time courses in temporally upsampled space.

    Parameters
    ----------

    aryCnd : np.array
        1D array with condition identifiers (every condition has its own int)
    aryOns : np.array, same len as aryCnd
        1D array with condition onset times in seconds.
    aryDrt : np.array, same len as aryCnd
        1D array with condition durations of different conditions in seconds.
    varTr : float, positive
        Time to repeat (TR) of the (fMRI) experiment.
    varNumVol : float, positive
        Number of volumes of the (fMRI) data.
    aryExclCnd : array
        1D array containing condition identifiers for conditions to be excluded
    varTmpOvsmpl : float, positive
        Factor by which the time courses should be temporally upsampled.

    Returns
    -------
    aryBxCrOut : np.array, float16
        Condition time courses in temporally upsampled space.

    References:
    -----
    [1] https://github.com/fabianp/hrf_estimation

    """
    if aryExclCnd is not None:
        for cond in aryExclCnd:
            aryOns = aryOns[aryCnd != cond]
            aryDrt = aryDrt[aryCnd != cond]
            aryCnd = aryCnd[aryCnd != cond]

    resolution = varTr / float(varTmpOvsmpl)
    aryCnd = np.asarray(aryCnd)
    aryOns = np.asarray(aryOns, dtype=np.float)
    unique_conditions = np.sort(np.unique(aryCnd))
    boxcar = []

    for c in unique_conditions:
        tmp = np.zeros(int(varNumVol * varTr/resolution))
        onset_c = aryOns[aryCnd == c]
        duration_c = aryDrt[aryCnd == c]
        onset_idx = np.round(onset_c / resolution).astype(np.int)
        duration_idx = np.round(duration_c / resolution).astype(np.int)
        aux = np.arange(int(varNumVol * varTr/resolution))
        for start, dur in zip(onset_idx, duration_idx):
            lgc = np.logical_and(aux >= start, aux < start + dur)
            tmp = tmp + lgc
        assert np.all(np.less(tmp, 2))
        boxcar.append(tmp)
    aryBxCrOut = np.array(boxcar).T
    if aryBxCrOut.shape[1] == 1:
        aryBxCrOut = np.squeeze(aryBxCrOut)
    return aryBxCrOut.astype('float16')

Response: Create a boxcar for the given set of conditions.


Instruction:
Can you generate the documentation for the following Python 3 function
def cnvl_tc(idxPrc, aryPrfTcChunk, lstHrf, varTr, varNumVol, varTmpOvsmpl,
            queOut, varHrfLen=32., dctPrm=None):
    """Convolution of time courses with HRF model.

    Parameters
    ----------
    idxPrc : int, positive
        Process ID of the process calling this function (for CPU
        multi-threading). In GPU version, this parameter is 0 (just one thread
        on CPU).
    aryPrfTcChunk : np.array
        2D array with model time course to be convolved with HRF.
    lstHrf : list
        List containing the different HRF functions.
    varTr : float, positive
        Time to repeat (TR) of the (fMRI) experiment.
    varNumVol : float, positive
        Number of volumes of the (fMRI) data.
    varTmpOvsmpl : float, positive
        Factor by which the time courses should be temporally upsampled.
    queOut : multiprocessing.queues.Queue
        Queue to put the results on.
    varHrfLen : float, positive, default=32
        Length of the HRF time course in seconds.
    dctPrm : dictionary, default None
        Dictionary with customized hrf parameters. If this is None, default
        hrf parameters will be used.

    Returns
    -------
    lstOut : list
        int, positive : Process ID of the process calling this function.
        2D np.array, float16 : Model time course convolved with HRF.

    References:
    -----
    [1] https://github.com/fabianp/hrf_estimation

    """

    # Adjust the input, if necessary, such that input is 2D, with last dim time
    tplInpShp = aryPrfTcChunk.shape
    aryPrfTcChunk = aryPrfTcChunk.reshape((-1, aryPrfTcChunk.shape[-1]))

    # Prepare list to collect hrf basis functions
    lstBse = []
    # Prepare array that contains time intervals
    aryTme = np.linspace(0, varHrfLen, (varHrfLen // varTr) * varTmpOvsmpl)
    for fnHrf in lstHrf:
        # If hrf parameter dictionary is None, run with default parameters
        if dctPrm is None:
            vecTmpBse = fnHrf(aryTme)
        # Otherwise, run with custom parameters
        else:
            vecTmpBse = fnHrf(aryTme, **dctPrm)
        # Normalise HRF so that the sum of values is 1 (see FSL)
        # otherwise, after convolution values for predictors are very high
        vecTmpBse = np.divide(vecTmpBse, np.sum(vecTmpBse))

        lstBse.append(vecTmpBse)

    # Get frame times, i.e. start point of every volume in seconds
    vecFrms = np.arange(0, varTr * varNumVol, varTr)
    # Get supersampled frames times, i.e. start point of every volume in
    # upsampled res, since convolution takes place in temp. upsampled space
    vecFrmTms = np.arange(0, varTr * varNumVol, varTr / varTmpOvsmpl)

    # Prepare an empty array for ouput
    aryConv = np.zeros((aryPrfTcChunk.shape[0], len(lstHrf), varNumVol),
                       dtype=np.float16)
    # Each time course is convolved with the HRF separately, because the
    # numpy convolution function can only be used on one-dimensional data.
    # Thus, we have to loop through time courses:
    for idxTc in range(0, aryConv.shape[0]):

        # Extract the current time course (already in upsampled space):
        vecTcUps = aryPrfTcChunk[idxTc, :]

        # *** convolve
        for indBase, base in enumerate(lstBse):
            # Make sure base and vecTcUps are float64 to avoid overflow
            base = base.astype(np.float64)
            vecTcUps = vecTcUps.astype(np.float64)
            # Perform the convolution (previously: np.convolve)
            col = fftconvolve(base, vecTcUps, mode='full')[:vecTcUps.size]
            # Get function for downsampling
            f = interp1d(vecFrmTms, col)
            # Downsample to original resoltuion to match res of data
            # take the value from the centre of each volume's period (see FSL)
            aryConv[idxTc, indBase, :] = f(vecFrms + varTr/2.
                                           ).astype(np.float16)

    # Determine output shape
    tplOutShp = tplInpShp[:-1] + (len(lstHrf), ) + (varNumVol, )

    if queOut is None:
        # if user is not using multiprocessing, return the array directly
        return aryConv.reshape(tplOutShp)

    else:
        # Create list containing the convolved timecourses, and the process ID:
        lstOut = [idxPrc,
                  aryConv.reshape(tplOutShp)]

        # Put output to queue:
        queOut.put(lstOut)

Response: Convolution of time courses with HRF model.


Instruction:
Here you have a function in Python 3, explain what it does
def create_inputs_to_reference(job_data, input_files, input_directories):

    return {**deepcopy(job_data), **deepcopy(input_files), **deepcopy(input_directories)}

Response: Creates a dictionary with the summarized information in job_data input_files and input_directories.


Instruction:
Write a Python 3 script to
use str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings. :param s: The string to split. :param sep: A separator string. :return: A list of parts split by sep

Response:
def _partition_all_internal(s, sep):
    """
    Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings.

    :param s: The string to split.
    :param sep: A separator string.
    :return: A list of parts split by sep
    """
    parts = list(s.partition(sep))

    # if sep found
    if parts[1] == sep:
        new_parts = partition_all(parts[2], sep)
        parts.pop()
        parts.extend(new_parts)
        return [p for p in parts if p]
    else:
        if parts[0]:
            return [parts[0]]
        else:
            return []


Instruction:
Implement a function in Python 3 to
use str. partition to split every occurrence of sep in s.

Response:
def partition_all(s, sep):
    """
    Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings.
    If sep is a list, all separators are evaluated.

    :param s: The string to split.
    :param sep: A separator string or a list of separator strings.
    :return: A list of parts split by sep
    """
    if isinstance(sep, list):
        parts = _partition_all_internal(s, sep[0])
        sep = sep[1:]

        for s in sep:
            tmp = []
            for p in parts:
                tmp.extend(_partition_all_internal(p, s))
            parts = tmp

        return parts
    else:
        return _partition_all_internal(s, sep)


Instruction:
Create a Python 3 function to
split a string into normal strings and unresolved input references.

Response:
def split_input_references(to_split):
    """
    Returns the given string in normal strings and unresolved input references.
    An input reference is identified as something of the following form $(...).

    Example:
    split_input_reference("a$(b)cde()$(fg)") == ["a", "$(b)", "cde()", "$(fg)"]

    :param to_split: The string to split
    :raise InvalidInputReference: If an input reference is not closed and a new reference starts or the string ends.
    :return: A list of normal strings and unresolved input references.
    """
    parts = partition_all(to_split, [INPUT_REFERENCE_START, INPUT_REFERENCE_END])

    result = []
    part = []
    in_reference = False
    for p in parts:
        if in_reference:
            if p == INPUT_REFERENCE_START:
                raise InvalidInputReference('A new input reference has been started, although the old input reference'
                                            'has not yet been completed.\n{}'.format(to_split))
            elif p == ")":
                part.append(")")
                result.append(''.join(part))
                part = []
                in_reference = False
            else:
                part.append(p)
        else:
            if p == INPUT_REFERENCE_START:
                if part:
                    result.append(''.join(part))
                part = [INPUT_REFERENCE_START]
                in_reference = True
            else:
                part.append(p)

    if in_reference:
        raise InvalidInputReference('Input reference not closed.\n{}'.format(to_split))
    elif part:
        result.append(''.join(part))

    return result


Instruction:
Implement a function in Python 3 to
split a given string at a given separator or list of separators.

Response:
def split_all(reference, sep):
    """
    Splits a given string at a given separator or list of separators.

    :param reference: The reference to split.
    :param sep: Separator string or list of separator strings.
    :return: A list of split strings
    """
    parts = partition_all(reference, sep)
    return [p for p in parts if p not in sep]


Instruction:
Can you implement a function in Python 3 that
resolves the file attributes in demand of the input file.

Response:
def _resolve_file(attributes, input_file, input_identifier, input_reference):
    """
    Returns the attributes in demand of the input file.

    :param attributes: A list of attributes to get from the input_file.
    :param input_file: The file from which to get the attributes.
    :param input_identifier: The input identifier of the given file.
    :param input_reference: The reference string
    :return: The attribute in demand
    """
    if input_file['isArray']:
        raise InvalidInputReference('Input References to Arrays of input files are currently not supported.\n'
                                    '"{}" is an array of files and can not be resolved for input references:'
                                    '\n{}'.format(input_identifier, input_reference))
    single_file = input_file['files'][0]

    try:
        return _get_dict_element(single_file, attributes)
    except KeyError:
        raise InvalidInputReference('Could not get attributes "{}" from input file "{}", needed in input reference:'
                                    '\n{}'.format(attributes, input_identifier, input_reference))


Instruction:
Given the following Python 3 function, write the documentation
def _resolve_directory(attributes, input_directory, input_identifier, input_reference):
    if input_directory['isArray']:
        raise InvalidInputReference('Input References to Arrays of input directories are currently not supported.\n'
                                    'input directory "{}" is an array of directories and can not be resolved for input'
                                    'references:\n{}'.format(input_identifier, input_reference))
    single_directory = input_directory['directories'][0]

    try:
        return _get_dict_element(single_directory, attributes)
    except KeyError:
        raise InvalidInputReference('Could not get attributes "{}" from input directory "{}", needed in input'
                                    'reference:\n{}'.format(attributes, input_identifier, input_reference))

Response: Resolves the attributes in demand of the input directory.


Instruction:
How would you explain what the following Python 3 function does
def resolve_input_reference(reference, inputs_to_reference):
    if not reference.startswith('{}inputs.'.format(INPUT_REFERENCE_START)):
        raise InvalidInputReference('An input reference must have the following form'
                                    '"$(inputs.<input_name>[.<attribute>]".\n'
                                    'The invalid reference is: "{}"'.format(reference))
    # remove "$(inputs." and ")"
    reference = reference[2:-1]
    parts = split_all(reference, ATTRIBUTE_SEPARATOR_SYMBOLS)

    if len(parts) < 2:
        raise InvalidInputReference('InputReference should at least contain "$(inputs.identifier)". The following input'
                                    'reference does not comply with it:\n{}'.format(reference))
    elif parts[0] != "inputs":
        raise InvalidInputReference('InputReference should at least contain "$(inputs.identifier)". The following input'
                                    ' reference does not comply with it:\n$({})'.format(reference))
    else:
        input_identifier = parts[1]
        input_to_reference = inputs_to_reference.get(input_identifier)
        if input_to_reference is None:
            raise InvalidInputReference('Input identifier "{}" not found in inputs, but needed in input reference:\n{}'
                                        .format(input_identifier, reference))
        elif isinstance(input_to_reference, dict):
            if 'files' in input_to_reference:
                return _resolve_file(parts[2:], input_to_reference, input_identifier, reference)
            elif 'directories' in input_to_reference:
                return _resolve_directory(parts[2:], input_to_reference, input_identifier, reference)
            else:
                raise InvalidInputReference('Unknown input type for input identifier "{}"'.format(input_identifier))
        else:
            if len(parts) > 2:
                raise InvalidInputReference('Attribute "{}" of input reference "{}" could not be resolved'
                                            .format(parts[2], reference))
            else:
                return parts[1]

Response: Resolves a given input reference by a string extracted from inputs_to_reference.


Instruction:
Write a Python 3 function that can
resolve input references given in the string to_resolve by using inputs_to_reference.

Response:
def resolve_input_references(to_resolve, inputs_to_reference):
    """
    Resolves input references given in the string to_resolve by using the inputs_to_reference.

    See http://www.commonwl.org/user_guide/06-params/index.html for more information.

    Example:
    "$(inputs.my_file.nameroot).md" -> "filename.md"

    :param to_resolve: The path to match
    :param inputs_to_reference: Inputs which are used to resolve input references like $(inputs.my_input_file.basename).

    :return: A string in which the input references are replaced with actual values.
    """

    splitted = split_input_references(to_resolve)

    result = []

    for part in splitted:
        if is_input_reference(part):
            result.append(str(resolve_input_reference(part, inputs_to_reference)))
        else:
            result.append(part)

    return ''.join(result)


Instruction:
Can you tell what is the following Python 3 function doing
def data(self):
        res = {'error_list': self.error_list}
        res.update(super(ValidationErrors, self).data)
        return res

Response:
Returns a dictionnary containing all the passed data and an item
        which holds the result of validation errors.


Instruction:
Write a Python 3 function that can
calculate the circular difference between two arrays

Response:
def circDiff(length, ary1, ary2):
    """calculate the circular difference between two paired arrays.
    This function will return the difference between pairs of numbers; however
    the difference that is output will be minimal in the sense that if we
    assume an array with length = 4: [0, 1, 2, 3], the difference between
    0 and 3 will not be 3, but 1 (i.e. circular difference)"""
    x = np.arange(length)
    mod = length % 2
    if mod == 0:
        temp = np.ones(length)
        temp[length/2:] = -1
    else:
        x = x - np.floor(length/2)
        temp = np.copy(x)
        temp[np.less(x, 0)] = 1
        temp[np.greater(x, 0)] = -1
    x = np.cumsum(temp)

    diagDiffmat = np.empty((length, length))
    for idx in np.arange(length):
        x = np.roll(x, 1)
        diagDiffmat[idx, :] = x
    # return diagDiffmat[ary1][ary2]
    flat = diagDiffmat.flatten()
    ind = ary1*diagDiffmat.shape[0] + ary2
    ind = ind.astype('int')
    return flat[ind]


Instruction:
Make a summary of the following Python 3 code
def getPartnerURL(self, CorpNum, TOGO):
        try:
            return linkhub.getPartnerURL(self._getToken(CorpNum), TOGO)
        except LinkhubException as LE:
            raise PopbillException(LE.code, LE.message)

Response:
팝빌 회원 잔여포인트 확인
            args
                CorpNum : 팝빌회원 사업자번호
                TOGO : "CHRG"
            return
                URL
            raise
                PopbillException


Instruction:
Given the following Python 3 function, write the documentation
def getAccessURL(self, CorpNum, UserID):
        result = self._httpget('/?TG=LOGIN', CorpNum, UserID)
        return result.url

Response:
팝빌 로그인 URL
            args
                CorpNum : 회원 사업자번호
                UserID  : 회원 팝빌아이디
            return
                30초 보안 토큰을 포함한 url
            raise
                PopbillException


Instruction:
Here you have a function in Python 3, explain what it does
def getChargeURL(self, CorpNum, UserID):
        result = self._httpget('/?TG=CHRG', CorpNum, UserID)
        return result.url

Response:
팝빌 연동회원 포인트 충전 URL
            args
                CorpNum : 회원 사업자번호
                UserID  : 회원 팝빌아이디
            return
                30초 보안 토큰을 포함한 url
            raise
                PopbillException


Instruction:
Given the following Python 3 function, write the documentation
def checkIsMember(self, CorpNum):
        if CorpNum == None or CorpNum == '':
            raise PopbillException(-99999999, "사업자번호가 입력되지 않았습니다.")

        return self._httpget('/Join?CorpNum=' + CorpNum + '&LID=' + self.__linkID, None, None)

Response: Check if a user is a member of the room.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def joinMember(self, JoinInfo):
        JoinInfo.LinkID = self.__linkID
        postData = self._stringtify(JoinInfo)
        return self._httppost('/Join', postData)

Response: 전용 정보 팝빌 회원가입 정보.


Instruction:
Can you tell what is the following Python 3 function doing
def registContact(self, CorpNum, ContactInfo, UserID=None):
        postData = self._stringtify(ContactInfo)
        return self._httppost('/IDs/New', postData, CorpNum, UserID)

Response: registContact - Regist a new contact


Instruction:
Given the following Python 3 function, write the documentation
def TemplateValidator(value):

    try:
        Template(value)
    except Exception as e:
        raise ValidationError(
            _("Cannot compile template (%(exception)s)"),
            params={"exception": e}
        )

Response: Validate a string into a Django template.


Instruction:
Given the following Python 3 function, write the documentation
def merge(
    fname1,
    fname2,
    dfilter1=None,
    dfilter2=None,
    has_header1=True,
    has_header2=True,
    frow1=0,
    frow2=0,
    ofname=None,
    ocols=None,
):
    r"""
    Merge two comma-separated values files.

    Data columns from the second file are appended after data columns from the
    first file. Empty values in columns are used if the files have different
    number of rows

    :param fname1: Name of the first comma-separated values file, the file
                   whose columns appear first in the output file
    :type  fname1: FileNameExists_

    :param fname2: Name of the second comma-separated values file, the file
                   whose columns appear last in the output file
    :type  fname2: FileNameExists_

    :param dfilter1: Row and/or column filter for the first file. If None no
                     data filtering is done on the file
    :type  dfilter1: :ref:`CsvDataFilter` or None

    :param dfilter2: Row and/or column filter for the second file. If None no
                     data filtering is done on the file
    :type  dfilter2: :ref:`CsvDataFilter` or None

    :param has_header1: Flag that indicates whether the first comma-separated
                        values file has column headers in its first line (True)
                        or not (False)
    :type  has_header1: boolean

    :param has_header2: Flag that indicates whether the second comma-separated
                        values file has column headers in its first line (True)
                        or not (False)
    :type  has_header2: boolean

    :param frow1: First comma-separated values file first data row (starting
                  from 1). If 0 the row where data starts is auto-detected as
                  the first row that has a number (integer of float) in at
                  least one of its columns
    :type  frow1: NonNegativeInteger_

    :param frow2: Second comma-separated values file first data row (starting
                  from 1). If 0 the row where data starts is auto-detected as
                  the first row that has a number (integer of float) in at
                  least one of its columns
    :type  frow2: NonNegativeInteger_

    :param ofname: Name of the output comma-separated values file, the file
                   that will contain the data from the first and second files.
                   If None the first file is replaced "in place"
    :type  ofname: FileName_ or None

    :param ocols: Column names of the output comma-separated values file.
                  If None the column names in the first and second files are
                  used if **has_header1** and/or **has_header2** are True. The
                  column labels :code:`'Column [column_number]'` are used when
                  one of the two files does not have a header, where
                  :code:`[column_number]` is an integer representing the column
                  number (column 0 is the leftmost column). No header is used
                  if **has_header1** and **has_header2** are False
    :type  ocols: list or None

    .. [[[cog cog.out(exobj.get_sphinx_autodoc(raised=True)) ]]]
    .. Auto-generated exceptions documentation for pcsv.merge.merge

    :raises:
     * OSError (File *[fname]* could not be found)

     * RuntimeError (Argument \`dfilter1\` is not valid)

     * RuntimeError (Argument \`dfilter2\` is not valid)

     * RuntimeError (Argument \`fname1\` is not valid)

     * RuntimeError (Argument \`fname2\` is not valid)

     * RuntimeError (Argument \`frow1\` is not valid)

     * RuntimeError (Argument \`frow2\` is not valid)

     * RuntimeError (Argument \`ocols\` is not valid)

     * RuntimeError (Argument \`ofname\` is not valid)

     * RuntimeError (Column headers are not unique in file *[fname]*)

     * RuntimeError (Combined columns in data files and output columns are
       different)

     * RuntimeError (File *[fname]* has no valid data)

     * RuntimeError (File *[fname]* is empty)

     * RuntimeError (Invalid column specification)

     * ValueError (Column *[column_identifier]* not found)

    .. [[[end]]]
    """
    # pylint: disable=R0913,R0914
    iomm_ex = pexdoc.exh.addex(
        RuntimeError, "Combined columns in data files and output columns are different"
    )
    # Read and validate file 1
    obj1 = CsvFile(fname=fname1, dfilter=dfilter1, has_header=has_header1, frow=frow1)
    # Read and validate file 2
    obj2 = CsvFile(fname=fname2, dfilter=dfilter2, has_header=has_header2, frow=frow2)
    # Assign output data structure
    ofname = fname1 if ofname is None else ofname
    cfilter1 = obj1.header() if obj1.cfilter is None else obj1.cfilter
    cfilter2 = obj2.header() if obj1.cfilter is None else obj2.cfilter
    # Create new header
    cols1 = len(cfilter1)
    cols2 = len(cfilter2)
    if (ocols is None) and has_header1 and has_header2:
        ocols = [cfilter1 + cfilter2]
    elif (ocols is None) and has_header1 and (not has_header2):
        ocols = [
            cfilter1
            + [
                "Column {0}".format(item)
                for item in range(cols1 + 1, cols1 + cols2 + 1)
            ]
        ]
    elif (ocols is None) and (not has_header1) and has_header2:
        ocols = [["Column {0}".format(item) for item in range(1, cols1 + 1)] + cfilter2]
    elif ocols is None:
        ocols = []
    else:
        iomm_ex(cols1 + cols2 != len(ocols))
        ocols = [ocols]
    # Even out rows
    delta = obj1.rows(filtered=True) - obj2.rows(filtered=True)
    data1 = obj1.data(filtered=True)
    data2 = obj2.data(filtered=True)
    if delta > 0:
        row = [cols2 * [None]]
        data2 += delta * row
    elif delta < 0:
        row = [cols1 * [None]]
        data1 += abs(delta) * row
    data = ocols
    for item1, item2 in zip(data1, data2):
        data.append(item1 + item2)
    write(fname=ofname, data=data, append=False)

Response: r Merge two comma - separated values files into one.