Instruction:
Create a Python 3 function to
parse a block node.

Response:
def parse(self, scope):
        """Parse block node.
        args:
            scope (Scope): Current scope
        raises:
            SyntaxError
        returns:
            self
        """
        if not self.parsed:
            scope.push()
            self.name, inner = self.tokens
            scope.current = self.name
            scope.real.append(self.name)
            if not self.name.parsed:
                self.name.parse(scope)
            if not inner:
                inner = []
            inner = list(utility.flatten([p.parse(scope) for p in inner if p]))
            self.parsed = []
            self.inner = []
            if not hasattr(self, "inner_media_queries"):
                self.inner_media_queries = []
            for p in inner:
                if p is not None:
                    if isinstance(p, Block):
                        if (len(scope) == 2 and p.tokens[1] is not None):
                            p_is_mediaquery = p.name.tokens[0] == '@media'
                            # Inner block @media ... { ... } is a nested media
                            # query. But double-nested media queries have to be
                            # removed and marked as well. While parsing ".foo",
                            # both nested "@media print" and double-nested
                            # "@media all" will be handled as we have to
                            # re-arrange the scope and block layout quite a bit:
                            #
                            #   .foo {
                            #       @media print {
                            #           color: blue;
                            #           @media screen { font-size: 12em; }
                            #       }
                            #   }
                            #
                            # Expected result:
                            #
                            #   @media print {
                            #       .foo { color: blue; }
                            #   }
                            #   @media print and screen {
                            #       .foo { font-size: 12 em; }
                            #   }
                            append_list = []
                            reparse_p = False
                            for child in p.tokens[1]:
                                if isinstance(child, Block) and child.name.raw(
                                ).startswith("@media"):
                                    # Remove child from the nested media query, it will be re-added to
                                    # the parent with 'merged' media query (see above example).
                                    p.tokens[1].remove(child)
                                    if p_is_mediaquery:  # Media query inside a & block
                                        # Double-nested media query found. We remove it from 'p' and add
                                        # it to this block with a new 'name'.
                                        reparse_p = True
                                        part_a = p.name.tokens[2:][0][0][0]
                                        part_b = child.name.tokens[2:][0][0]
                                        new_ident_tokens = [
                                            '@media', ' ', [
                                                part_a, (' ', 'and', ' '),
                                                part_b
                                            ]
                                        ]
                                        # Parse child again with new @media $BLA {} part
                                        child.tokens[0] = Identifier(
                                            new_ident_tokens)
                                        child.parsed = None
                                        child = child.parse(scope)
                                    else:
                                        child.block_name = p.name
                                    append_list.append(child)
                                if reparse_p:
                                    p.parsed = None
                                    p = p.parse(scope)
                            if not p_is_mediaquery and not append_list:
                                self.inner.append(p)
                            else:
                                append_list.insert(
                                    0, p
                                )  # This media query should occur before it's children
                                for media_query in append_list:
                                    self.inner_media_queries.append(
                                        media_query)
                            # NOTE(saschpe): The code is not recursive but we hope that people
                            # wont use triple-nested media queries.
                        else:
                            self.inner.append(p)
                    else:
                        self.parsed.append(p)
            if self.inner_media_queries:
                # Nested media queries, we have to remove self from scope and
                # push all nested @media ... {} blocks.
                scope.remove_block(self, index=-2)
                for mb in self.inner_media_queries:
                    # New inner block with current name and media block contents
                    if hasattr(mb, 'block_name'):
                        cb_name = mb.block_name
                    else:
                        cb_name = self.tokens[0]
                    cb = Block([cb_name, mb.tokens[1]]).parse(scope)
                    # Replace inner block contents with new block
                    new_mb = Block([mb.tokens[0], [cb]]).parse(scope)
                    self.inner.append(new_mb)
                    scope.add_block(new_mb)
            scope.real.pop()
            scope.pop()
        return self


Instruction:
Can you generate the documentation for the following Python 3 function
def fmt(self, fills):
        f = "%(identifier)s%(ws)s{%(nl)s%(proplist)s}%(eb)s"
        out = []
        name = self.name.fmt(fills)
        if self.parsed and any(
                p for p in self.parsed
                if str(type(p)) != "<class 'lesscpy.plib.variable.Variable'>"):
            fills.update({
                'identifier':
                name,
                'proplist':
                ''.join([p.fmt(fills) for p in self.parsed if p]),
            })
            out.append(f % fills)
        if hasattr(self, 'inner'):
            if self.name.subparse and len(self.inner) > 0:  # @media
                inner = ''.join([p.fmt(fills) for p in self.inner])
                inner = inner.replace(fills['nl'],
                                      fills['nl'] + fills['tab']).rstrip(
                                          fills['tab'])
                if not fills['nl']:
                    inner = inner.strip()
                fills.update({
                    'identifier': name,
                    'proplist': fills['tab'] + inner
                })
                out.append(f % fills)
            else:
                out.append(''.join([p.fmt(fills) for p in self.inner]))
        return ''.join(out)

Response: Format a single block of CSS


Instruction:
How would you explain what the following Python 3 function does
def copy(self):
        name, inner = self.tokens
        if inner:
            inner = [u.copy() if u else u for u in inner]
        if name:
            name = name.copy()
        return Block([name, inner], 0)

Response: Return a full copy of self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def copy_inner(self, scope):
        if self.tokens[1]:
            tokens = [u.copy() if u else u for u in self.tokens[1]]
            out = [p for p in tokens if p]
            utility.rename(out, scope, Block)
            return out
        return None

Response: Copy the inner block contents.


Instruction:
How would you code a function in Python 3 to
parse the node s tokens and return a new instance of the node class.

Response:
def parse(self, scope):
        """Parse node
        args:
            scope (Scope): current scope
        raises:
            SyntaxError
        returns:
            self
        """
        self.parsed = list(utility.flatten(self.tokens))
        if self.parsed[0] == '@import':
            if len(self.parsed) > 4:
                # Media @import
                self.parsed.insert(3, ' ')
        return self


Instruction:
Write a Python 3 script to
parse function. We parse the tokens and return the mixed version of the tokens.

Response:
def parse(self, scope, error=False, depth=0):
        """ Parse function. We search for mixins
        first within current scope then fallback
        to global scope. The special scope.deferred
        is used when local scope mixins are called
        within parent mixins.
        If nothing is found we fallback to block-mixin
        as lessc.js allows calls to blocks and mixins to
        be inter-changable.
        clx: This method is a HACK that stems from
        poor design elsewhere. I will fix it
        when I have more time.
        args:
            scope (Scope): Current scope
        returns:
            mixed
        """
        res = False
        ident, args = self.tokens
        ident.parse(scope)
        mixins = scope.mixins(ident.raw())

        if not mixins:
            ident.parse(None)
            mixins = scope.mixins(ident.raw())

        if depth > 64:
            raise SyntaxError('NameError `%s`' % ident.raw(True))

        if not mixins:
            if scope.deferred:
                store = [t for t in scope.deferred.parsed[-1]]
                i = 0
                while scope.deferred.parsed[-1]:
                    scope.current = scope.deferred
                    ident.parse(scope)
                    mixins = scope.mixins(ident.raw())
                    scope.current = None
                    if mixins or i > 64:
                        break
                    scope.deferred.parsed[-1].pop()
                    i += 1
                scope.deferred.parsed[-1] = store

        if not mixins:
            # Fallback to blocks
            block = scope.blocks(ident.raw())
            if not block:
                ident.parse(None)
                block = scope.blocks(ident.raw())
            if block:
                scope.current = scope.real[-1] if scope.real else None
                res = block.copy_inner(scope)
                scope.current = None

        if mixins:
            for mixin in mixins:
                scope.current = scope.real[-1] if scope.real else None
                res = mixin.call(scope, args)
                if res:
                    # Add variables to scope to support
                    # closures
                    [scope.add_variable(v) for v in mixin.vars]
                    scope.deferred = ident
                    break

        if res:
            store = [t for t in scope.deferred.parsed[-1]
                     ] if scope.deferred else False
            tmp_res = []
            for p in res:
                if p:
                    if isinstance(p, Deferred):
                        tmp_res.append(p.parse(scope, depth=depth + 1))
                    else:
                        tmp_res.append(p.parse(scope))
            res = tmp_res
            #res = [p.parse(scope, depth=depth+1) for p in res if p]
            while (any(t for t in res if isinstance(t, Deferred))):
                res = [p.parse(scope) for p in res if p]
            if store:
                scope.deferred.parsed[-1] = store

        if error and not res:
            raise SyntaxError('NameError `%s`' % ident.raw(True))
        return res


Instruction:
Write a Python 3 function for
compiling all. less files in a directory and write them to outpath.

Response:
def ldirectory(inpath, outpath, args, scope):
    """Compile all *.less files in directory
    Args:
        inpath (str): Path to compile
        outpath (str): Output directory
        args (object): Argparse Object
        scope (Scope): Scope object or None
    """
    yacctab = 'yacctab' if args.debug else None
    if not outpath:
        sys.exit("Compile directory option needs -o ...")
    else:
        if not os.path.isdir(outpath):
            if args.verbose:
                print("Creating '%s'" % outpath, file=sys.stderr)
            if not args.dry_run:
                os.mkdir(outpath)
    less = glob.glob(os.path.join(inpath, '*.less'))
    f = formatter.Formatter(args)
    for lf in less:
        outf = os.path.splitext(os.path.basename(lf))
        minx = '.min' if args.min_ending else ''
        outf = "%s/%s%s.css" % (outpath, outf[0], minx)
        if not args.force and os.path.exists(outf):
            recompile = os.path.getmtime(outf) < os.path.getmtime(lf)
        else:
            recompile = True
        if recompile:
            print('%s -> %s' % (lf, outf))
            p = parser.LessParser(
                yacc_debug=(args.debug),
                lex_optimize=True,
                yacc_optimize=(not args.debug),
                scope=scope,
                tabfile=yacctab,
                verbose=args.verbose)
            p.parse(filename=lf, debuglevel=0)
            css = f.format(p)
            if not args.dry_run:
                with open(outf, 'w') as outfile:
                    outfile.write(css)
        elif args.verbose:
            print('skipping %s, not modified' % lf, file=sys.stderr)
        sys.stdout.flush()
    if args.recurse:
        [
            ldirectory(
                os.path.join(inpath, name), os.path.join(outpath, name), args,
                scope) for name in os.listdir(inpath)
            if os.path.isdir(os.path.join(inpath, name))
            and not name.startswith('.') and not name == outpath
        ]


Instruction:
Can you generate the documentation for the following Python 3 function
def parse(self, scope):
        self.keyframe, = [
            e[0] if isinstance(e, tuple) else e for e in self.tokens
            if str(e).strip()
        ]
        self.subparse = False
        return self

Response: Parse the keyframe from the current scope.


Instruction:
Here you have a function in Python 3, explain what it does
def t_mediaquery_t_semicolon(self, t):
        r';'
        # This can happen only as part of a CSS import statement. The
        # "mediaquery" state is reused there. Ordinary media queries always
        # end at '{', i.e. when a block is opened.
        t.lexer.pop_state()  # state mediaquery
        # We have to pop the 'import' state here because we already ate the
        # t_semicolon and won't trigger t_import_t_semicolon.
        t.lexer.pop_state()  # state import
        return t

Response: Parse the next token and return the next token after the semicolon.


Instruction:
Can you tell what is the following Python 3 function doing
def t_css_string(self, t):
        r'"[^"@]*"|\'[^\'@]*\''
        t.lexer.lineno += t.value.count('\n')
        return t

Response: Tokenizer for CSS string.


Instruction:
Can you tell what is the following Python 3 function doing
def t_istringapostrophe_css_string(self, t):
        r'[^\'@]+'
        t.lexer.lineno += t.value.count('\n')
        return t

Response: Tokenizer for string apostrophe css


Instruction:
Can you generate the documentation for the following Python 3 function
def file(self, filename):
        with open(filename) as f:
            self.lexer.input(f.read())
        return self

Response: Reads a file and parses it into the Lex file.


Instruction:
Can you implement a function in Python 3 that
loads lexer with content from file which can be a path or a file object.

Response:
def input(self, file):
        """
        Load lexer with content from `file` which can be a path or a file
        like object.
        """
        if isinstance(file, string_types):
            with open(file) as f:
                self.lexer.input(f.read())
        else:
            self.lexer.input(file.read())


Instruction:
Can you tell what is the following Python 3 function doing
def token(self):
        if self.next_:
            t = self.next_
            self.next_ = None
            return t
        while True:
            t = self.lexer.token()
            if not t:
                return t
            if t.type == 't_ws' and (
                    self.pretok or
                (self.last and self.last.type not in self.significant_ws)):
                continue
            self.pretok = False
            if t.type == 't_bclose' and self.last and self.last.type not in ['t_bopen', 't_bclose'] and self.last.type != 't_semicolon' \
                    and not (hasattr(t, 'lexer') and (t.lexer.lexstate == 'escapequotes' or t.lexer.lexstate == 'escapeapostrophe')):
                self.next_ = t
                tok = lex.LexToken()
                tok.type = 't_semicolon'
                tok.value = ';'
                tok.lineno = t.lineno
                tok.lexpos = t.lexpos
                self.last = tok
                self.lexer.in_property_decl = False
                return tok
            self.last = t
            break
        return t

Response: Returns the next token in the language.


Instruction:
Here you have a function in Python 3, explain what it does
def parse(self, scope):
        names = []
        name = []
        self._subp = ('@media', '@keyframes', '@-moz-keyframes',
                      '@-webkit-keyframes', '@-ms-keyframes')
        if self.tokens and hasattr(self.tokens, 'parse'):
            self.tokens = list(
                utility.flatten([
                    id.split() + [',']
                    for id in self.tokens.parse(scope).split(',')
                ]))
            self.tokens.pop()
        if self.tokens and any(hasattr(t, 'parse') for t in self.tokens):
            tmp_tokens = []
            for t in self.tokens:
                if hasattr(t, 'parse'):
                    tmp_tokens.append(t.parse(scope))
                else:
                    tmp_tokens.append(t)
            self.tokens = list(utility.flatten(tmp_tokens))
        if self.tokens and self.tokens[0] in self._subp:
            name = list(utility.flatten(self.tokens))
            self.subparse = True
        else:
            self.subparse = False
            for n in utility.flatten(self.tokens):
                if n == '*':
                    name.append('* ')
                elif n in '>+~':
                    if name and name[-1] == ' ':
                        name.pop()
                    name.append('?%s?' % n)
                elif n == ',':
                    names.append(name)
                    name = []
                else:
                    name.append(n)
        names.append(name)
        parsed = self.root(scope, names) if scope else names

        # Interpolated selectors need another step, we have to replace variables. Avoid reserved words though
        #
        # Example:  '.@{var}'       results in [['.', '@{var}']]
        # But:      '@media print'  results in [['@media', ' ', 'print']]
        #
        def replace_variables(tokens, scope):
            return [
                scope.swap(t)
                if (utility.is_variable(t) and not t in reserved.tokens) else t
                for t in tokens
            ]

        parsed = [
            list(utility.flatten(replace_variables(part, scope)))
            for part in parsed
        ]

        self.parsed = [[
            i for i, j in utility.pairwise(part)
            if i != ' ' or (j and '?' not in j)
        ] for part in parsed]
        return self

Response:
Parse node. Block identifiers are stored as
        strings with spaces replaced with ?
        args:
            scope (Scope): Current scope
        raises:
            SyntaxError
        returns:
            self


Instruction:
Given the following Python 3 function, write the documentation
def root(self, scope, names):
        parent = scope.scopename
        if parent:
            parent = parent[-1]
            if parent.parsed:
                parsed_names = []
                for name in names:
                    ampersand_count = name.count('&')
                    if ampersand_count:
                        filtered_parts = []
                        for part in parent.parsed:
                            if part and part[0] not in self._subp:
                                filtered_parts.append(part)
                        permutations = list(
                            utility.permutations_with_replacement(
                                filtered_parts, ampersand_count))
                        for permutation in permutations:
                            parsed = []
                            for name_part in name:
                                if name_part == "&":
                                    parent_part = permutation.pop(0)
                                    if parsed and parsed[-1].endswith(']'):
                                        parsed.extend(' ')
                                    if parent_part[-1] == ' ':
                                        parent_part.pop()
                                    parsed.extend(parent_part)
                                else:
                                    parsed.append(name_part)
                            parsed_names.append(parsed)
                    else:
                        # NOTE(saschpe): Maybe this code can be expressed with permutations too?
                        for part in parent.parsed:
                            if part and part[0] not in self._subp:
                                parsed = []
                                if name[0] == "@media":
                                    parsed.extend(name)
                                else:
                                    parsed.extend(part)
                                    if part[-1] != ' ':
                                        parsed.append(' ')
                                    parsed.extend(name)
                                parsed_names.append(parsed)
                            else:
                                parsed_names.append(name)
                return parsed_names
        return names

Response: Find the root of identifier from a list of names.


Instruction:
Can you generate the documentation for the following Python 3 function
def copy(self):
        tokens = ([t for t in self.tokens]
                  if isinstance(self.tokens, list) else self.tokens)
        return Identifier(tokens, 0)

Response:
Return a copy of self
           Identifier


Instruction:
Can you create a Python 3 function that
formats identifier args: fills (dict): replacements returns: str (CSS)

Response:
def fmt(self, fills):
        """Format identifier
        args:
            fills (dict): replacements
        returns:
            str (CSS)
        """
        name = ',$$'.join(''.join(p).strip() for p in self.parsed)
        name = re.sub('\?(.)\?', '%(ws)s\\1%(ws)s', name) % fills
        return name.replace('$$', fills['nl']).replace('  ', ' ')


Instruction:
Create a Python 3 function for
adding a block element to the log

Response:
def add_block(self, block):
        """Add block element to scope
        Args:
            block (Block): Block object
        """
        self[-1]['__blocks__'].append(block)
        self[-1]['__names__'].append(block.raw())


Instruction:
Here you have a function in Python 3, explain what it does
def remove_block(self, block, index="-1"):
        self[index]["__blocks__"].remove(block)
        self[index]["__names__"].remove(block.raw())

Response: Removes a block element from the scope


Instruction:
Implement a Python 3 function for
adding a mixin to the scope of the log.

Response:
def add_mixin(self, mixin):
        """Add mixin to scope
        Args:
            mixin (Mixin): Mixin object
        """
        raw = mixin.tokens[0][0].raw()
        if raw in self._mixins:
            self._mixins[raw].append(mixin)
        else:
            self._mixins[raw] = [mixin]


Instruction:
How would you implement a function in Python 3 that
searches for variable by name. Searches scope top down and returns Variable object OR False

Response:
def variables(self, name):
        """Search for variable by name. Searches scope top down
        Args:
            name (string): Search term
        Returns:
            Variable object OR False
        """
        if isinstance(name, tuple):
            name = name[0]
        if name.startswith('@{'):
            name = '@' + name[2:-1]
        i = len(self)
        while i >= 0:
            i -= 1
            if name in self[i]['__variables__']:
                return self[i]['__variables__'][name]
        return False


Instruction:
Can you create a Python 3 function that
searches mixins for name.

Response:
def mixins(self, name):
        """ Search mixins for name.
        Allow '>' to be ignored. '.a .b()' == '.a > .b()'
        Args:
            name (string): Search term
        Returns:
            Mixin object list OR False
        """
        m = self._smixins(name)
        if m:
            return m
        return self._smixins(name.replace('?>?', ' '))


Instruction:
Write a Python 3 function that can
search for defined blocks recursively.

Response:
def blocks(self, name):
        """
        Search for defined blocks recursively.
        Allow '>' to be ignored. '.a .b' == '.a > .b'
        Args:
            name (string): Search term
        Returns:
            Block object OR False
        """
        b = self._blocks(name)
        if b:
            return b
        return self._blocks(name.replace('?>?', ' '))


Instruction:
Can you tell what is the following Python 3 function doing
def _blocks(self, name):
        i = len(self)
        while i >= 0:
            i -= 1
            if name in self[i]['__names__']:
                for b in self[i]['__blocks__']:
                    r = b.raw()
                    if r and r == name:
                        return b
            else:
                for b in self[i]['__blocks__']:
                    r = b.raw()
                    if r and name.startswith(r):
                        b = utility.blocksearch(b, name)
                        if b:
                            return b
        return False

Response: Search for blocks by name.


Instruction:
Write a Python 3 script for
updating the internal state of the object.

Response:
def update(self, scope, at=0):
        """Update scope. Add another scope to this one.
        Args:
            scope (Scope): Scope object
        Kwargs:
            at (int): Level to update
        """
        if hasattr(scope, '_mixins') and not at:
            self._mixins.update(scope._mixins)
        self[at]['__variables__'].update(scope[at]['__variables__'])
        self[at]['__blocks__'].extend(scope[at]['__blocks__'])
        self[at]['__names__'].extend(scope[at]['__names__'])


Instruction:
Write a Python 3 script for
swapping variable name for variable value

Response:
def swap(self, name):
        """ Swap variable name for variable value
        Args:
            name (str): Variable name
        Returns:
            Variable value (Mixed)
        """
        if name.startswith('@@'):
            var = self.variables(name[1:])
            if var is False:
                raise SyntaxError('Unknown variable %s' % name)
            name = '@' + utility.destring(var.value[0])
            var = self.variables(name)
            if var is False:
                raise SyntaxError('Unknown variable %s' % name)
        elif name.startswith('@{'):
            var = self.variables('@' + name[2:-1])
            if var is False:
                raise SyntaxError('Unknown escaped variable %s' % name)
            if isinstance(var.value[0], string_types):
                var.value[0] = utility.destring(var.value[0])
        else:
            var = self.variables(name)
            if var is False:
                raise SyntaxError('Unknown variable %s' % name)
        return var.value


Instruction:
Create a Python 3 function for
processing tokenslist flattening and parsing it

Response:
def process(self, tokens, scope):
        """ Process tokenslist, flattening and parsing it
        args:
            tokens (list): tokenlist
            scope (Scope): Current scope
        returns:
            list
        """
        while True:
            tokens = list(utility.flatten(tokens))
            done = True
            if any(t for t in tokens if hasattr(t, 'parse')):
                tokens = [
                    t.parse(scope) if hasattr(t, 'parse') else t
                    for t in tokens
                ]
                done = False
            if any(
                    t for t in tokens
                    if (utility.is_variable(t)) or str(type(t)) ==
                    "<class 'lesscpy.plib.variable.Variable'>"):
                tokens = self.replace_variables(tokens, scope)
                done = False
            if done:
                break
        return tokens


Instruction:
Write a Python 3 function that can
replace variables in tokenlist tokens with variables in scope.

Response:
def replace_variables(self, tokens, scope):
        """ Replace variables in tokenlist
        args:
            tokens (list): tokenlist
            scope (Scope): Current scope
        returns:
            list
        """
        list = []
        for t in tokens:
            if utility.is_variable(t):
                list.append(scope.swap(t))
            elif str(type(t)) == "<class 'lesscpy.plib.variable.Variable'>":
                list.append(scope.swap(t.name))
            else:
                list.append(t)
        return list


Instruction:
Explain what the following Python 3 code does
def parse(self, scope):
        if not self.parsed:
            if len(self.tokens) > 2:
                property, style, _ = self.tokens
                self.important = True
            else:
                property, style = self.tokens
                self.important = False
            self.property = ''.join(property)
            self.parsed = []
            if style:
                style = self.preprocess(style)
                self.parsed = self.process(style, scope)
        return self

Response: Parse node - level properties and style.


Instruction:
Explain what the following Python 3 code does
def preprocess(self, style):
        if self.property == 'font':
            style = [
                ''.join(u.expression()) if hasattr(u, 'expression') else u
                for u in style
            ]
        else:
            style = [(u, ' ') if hasattr(u, 'expression') else u
                     for u in style]
        return style

Response: Hackish preprocessing from font shorthand tags.


Instruction:
How would you code a function in Python 3 to
format node with fills

Response:
def fmt(self, fills):
        """ Format node
        args:
            fills (dict): replacements
        returns:
            str
        """
        f = "%(tab)s%(property)s:%(ws)s%(style)s%(important)s;%(nl)s"
        imp = ' !important' if self.important else ''
        if fills['nl']:
            self.parsed = [
                ',%s' % fills['ws'] if p == ',' else p for p in self.parsed
            ]
        style = ''.join([
            p.fmt(fills) if hasattr(p, 'fmt') else str(p) for p in self.parsed
        ])
        # IE cannot handle no space after url()
        style = re.sub("(url\([^\)]*\))([^\s,])", "\\1 \\2", style)
        fills.update({
            'property': self.property,
            'style': style.strip(),
            'important': imp
        })
        return f % fills


Instruction:
Write a Python 3 script to
parse node args and scope.

Response:
def parse(self, scope):
        """Parse node
        args:
            scope (Scope): current scope
        raises:
            SyntaxError
        returns:
            self
        """
        self.name, args, self.guards = self.tokens[0]
        self.args = [a for a in utility.flatten(args) if a]
        self.body = Block([None, self.tokens[1]], 0)
        self.vars = list(
            utility.flatten([
                list(v.values()) for v in [s['__variables__'] for s in scope]
            ]))
        return self


Instruction:
Write a Python 3 script to
parse the arguments to mixin.

Response:
def parse_args(self, args, scope):
        """Parse arguments to mixin. Add them to scope
        as variables. Sets upp special variable @arguments
        as well.
        args:
            args (list): arguments
            scope (Scope): current scope
        raises:
            SyntaxError
        """
        arguments = list(zip(args,
                             [' '] * len(args))) if args and args[0] else None
        zl = itertools.zip_longest if sys.version_info[
            0] == 3 else itertools.izip_longest
        if self.args:
            parsed = [
                v if hasattr(v, 'parse') else v for v in copy.copy(self.args)
            ]
            args = args if isinstance(args, list) else [args]
            vars = [
                self._parse_arg(var, arg, scope)
                for arg, var in zl([a for a in args], parsed)
            ]
            for var in vars:
                if var:
                    var.parse(scope)
            if not arguments:
                arguments = [v.value for v in vars if v]
        if not arguments:
            arguments = ''
        Variable(['@arguments', None, arguments]).parse(scope)


Instruction:
How would you explain what the following Python 3 function does
def _parse_arg(self, var, arg, scope):
        if isinstance(var, Variable):
            # kwarg
            if arg:
                if utility.is_variable(arg[0]):
                    tmp = scope.variables(arg[0])
                    if not tmp:
                        return None
                    val = tmp.value
                else:
                    val = arg
                var = Variable(var.tokens[:-1] + [val])
        else:
            # arg
            if utility.is_variable(var):
                if arg is None:
                    raise SyntaxError('Missing argument to mixin')
                elif utility.is_variable(arg[0]):
                    tmp = scope.variables(arg[0])
                    if not tmp:
                        return None
                    val = tmp.value
                else:
                    val = arg
                var = Variable([var, None, val])
            else:
                return None
        return var

Response: Parse a single argument to mixin.


Instruction:
Can you generate the documentation for the following Python 3 function
def parse_guards(self, scope):
        if self.guards:
            cor = True if ',' in self.guards else False
            for g in self.guards:
                if isinstance(g, list):
                    res = (g[0].parse(scope)
                           if len(g) == 1 else Expression(g).parse(scope))
                    if cor:
                        if res:
                            return True
                    elif not res:
                        return False
        return True

Response: Parse guards on mixin.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def call(self, scope, args=[]):
        ret = False
        if args:
            args = [[
                a.parse(scope) if isinstance(a, Expression) else a for a in arg
            ] if arg else arg for arg in args]
        try:
            self.parse_args(args, scope)
        except SyntaxError:
            pass
        else:
            if self.parse_guards(scope):
                body = self.body.copy()
                ret = body.tokens[1]
                if ret:
                    utility.rename(ret, scope, Block)
        return ret

Response:
Parses a copy of the mixins body
            in the current scope and returns it.


Instruction:
Explain what the following Python 3 code does
def parse(self, scope):
        self.name, _, self.value = self.tokens
        if isinstance(self.name, tuple):
            if len(self.name) > 1:
                self.name, pad = self.name
                self.value.append(pad)
            else:
                self.name = self.name[0]
        scope.add_variable(self)
        return self

Response:
Parse function
        args : Scope object containing the related attributes. Returns self.


Instruction:
Make a summary of the following Python 3 code
def parse(self, scope):
        name = ''.join(self.tokens[0])
        parsed = self.process(self.tokens[1:], scope)

        if name == '%(':
            name = 'sformat'
        elif name in ('~', 'e'):
            name = 'escape'
        color = Color.Color()
        args = [
            t for t in parsed
            if not isinstance(t, string_types) or t not in '(),'
        ]
        if hasattr(self, name):
            try:
                return getattr(self, name)(*args)
            except ValueError:
                pass

        if hasattr(color, name):
            try:
                result = getattr(color, name)(*args)
                try:
                    return result + ' '
                except TypeError:
                    return result
            except ValueError:
                pass
        return name + ''.join([p for p in parsed])

Response: Parse a node within scope.


Instruction:
How would you explain what the following Python 3 function does
def sformat(self, string, *args):
        format = string
        items = []
        m = re.findall('(%[asdA])', format)
        if m and not args:
            raise SyntaxError('Not enough arguments...')
        i = 0
        for n in m:
            v = {
                '%A': urlquote,
                '%s': utility.destring,
            }.get(n, str)(args[i])
            items.append(v)
            i += 1
        format = format.replace('%A', '%s')
        format = format.replace('%d', '%s')
        return format % tuple(items)

Response:
String format.
        args:
            string (str): string to format
            args (list): format options
        returns:
            str


Instruction:
Write a Python 3 script to
am number args: string (str): match returns: bool

Response:
def isnumber(self, string, *args):
        """Is number
        args:
            string (str): match
        returns:
            bool
        """
        try:
            n, u = utility.analyze_number(string)
        except SyntaxError:
            return False
        return True


Instruction:
Can you write a function in Python 3 where it
is url args: string (str): match returns: bool

Response:
def isurl(self, string, *args):
        """Is url
        args:
            string (str): match
        returns:
            bool
        """
        arg = utility.destring(string)
        regex = re.compile(
            r'^(?:http|ftp)s?://'  # http:// or https://
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
            r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
            # localhost...
            r'localhost|'
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
            # optional port
            r'(?::\d+)?'
            r'(?:/?|[/?]\S+)$',
            re.IGNORECASE)
        return regex.match(arg)


Instruction:
Can you tell what is the following Python 3 function doing
def isstring(self, string, *args):
        regex = re.compile(r'\'[^\']*\'|"[^"]*"')
        return regex.match(string)

Response: Is string containing a valid tag


Instruction:
Make a summary of the following Python 3 code
def increment(self, value, *args):
        n, u = utility.analyze_number(value)
        return utility.with_unit(n + 1, u)

Response: Increment function for a log entry.


Instruction:
Write a Python 3 script for
adding integers to a set of integers.

Response:
def add(self, *args):
        """ Add integers
        args:
            args (list): target
        returns:
            str
        """
        if (len(args) <= 1):
            return 0
        return sum([int(v) for v in args])


Instruction:
Write a Python 3 function that can
return the number of the log entry in the specified unit.

Response:
def round(self, value, *args):
        """ Round number
        args:
            value (str): target
        returns:
            str
        """
        n, u = utility.analyze_number(value)
        return utility.with_unit(
            int(utility.away_from_zero_round(float(n))), u)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ceil(self, value, *args):
        n, u = utility.analyze_number(value)
        return utility.with_unit(int(math.ceil(n)), u)

Response: ceil - Calculates the ceiling of a number in a set of units


Instruction:
Can you create a Python 3 function that
returns the value in a percentage.

Response:
def percentage(self, value, *args):
        """ Return percentage value
        args:
            value (str): target
        returns:
            str
        """
        n, u = utility.analyze_number(value)
        n = int(n * 100.0)
        u = '%'
        return utility.with_unit(n, u)


Instruction:
How would you code a function in Python 3 to
process color expression returns string

Response:
def process(self, expression):
        """ Process color expression
        args:
            expression (tuple): color expression
        returns:
            str
        """
        a, o, b = expression
        c1 = self._hextorgb(a)
        c2 = self._hextorgb(b)
        r = ['#']
        for i in range(3):
            v = self.operate(c1[i], c2[i], o)
            if v > 0xff:
                v = 0xff
            if v < 0:
                v = 0
            r.append("%02x" % int(v))
        return ''.join(r)


Instruction:
Write a Python 3 script for
doing a operation on colors

Response:
def operate(self, left, right, operation):
        """ Do operation on colors
        args:
            left (str): left side
            right (str): right side
            operation (str): Operation
        returns:
            str
        """
        operation = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv
        }.get(operation)
        return operation(left, right)


Instruction:
Can you write a function in Python 3 where it
translates rgb to color string

Response:
def rgb(self, *args):
        """ Translate rgb(...) to color string
        raises:
            ValueError
        returns:
            str
        """
        if len(args) == 4:
            args = args[:3]
        if len(args) == 3:
            try:
                return self._rgbatohex(list(map(int, args)))
            except ValueError:
                if all((a for a in args
                        if a[-1] == '%' and 100 >= int(a[:-1]) >= 0)):
                    return self._rgbatohex(
                        [int(a[:-1]) * 255 / 100.0 for a in args])
        raise ValueError('Illegal color values')


Instruction:
How would you explain what the following Python 3 function does
def rgba(self, *args):
        if len(args) == 4:
            try:
                falpha = float(list(args)[3])
                if falpha > 1:
                    args = args[:3]
                if falpha == 0:
                    values = self._rgbatohex_raw(list(map(int, args)))
                    return "rgba(%s)" % ','.join([str(a) for a in values])
                return self._rgbatohex(list(map(int, args)))
            except ValueError:
                if all((a for a in args
                        if a[-1] == '%' and 100 >= int(a[:-1]) >= 0)):
                    alpha = list(args)[3]
                    if alpha[-1] == '%' and float(alpha[:-1]) == 0:
                        values = self._rgbatohex_raw(
                            [int(a[:-1]) * 255 / 100.0 for a in args])
                        return "rgba(%s)" % ','.join([str(a) for a in values])
                    return self._rgbatohex(
                        [int(a[:-1]) * 255 / 100.0 for a in args])
        raise ValueError('Illegal color values')

Response: Translate rgba to color string


Instruction:
Can you generate a brief explanation for the following Python 3 code
def argb(self, *args):
        if len(args) == 1 and type(args[0]) is str:
            match = re.match(r'rgba\((.*)\)', args[0])
            if match:
                # NOTE(saschpe): Evil hack to cope with rgba(.., .., .., 0.5) passed through untransformed
                rgb = re.sub(r'\s+', '', match.group(1)).split(',')
            else:
                rgb = list(self._hextorgb(args[0]))
        else:
            rgb = list(args)
        if len(rgb) == 3:
            return self._rgbatohex([255] + list(map(int, rgb)))
        elif len(rgb) == 4:
            rgb = [rgb.pop()] + rgb  # Move Alpha to front
            try:
                fval = float(list(rgb)[0])
                if fval > 1:
                    rgb = [255] + rgb[1:]  # Clip invalid integer/float values
                elif 1 >= fval >= 0:
                    rgb = [
                        fval * 256
                    ] + rgb[1:]  # Convert 0-1 to 0-255 range for _rgbatohex
                else:
                    rgb = [0] + rgb[1:]  # Clip lower bound
                return self._rgbatohex(list(map(int, rgb)))
            except ValueError:
                if all((a for a in rgb
                        if a[-1] == '%' and 100 >= int(a[:-1]) >= 0)):
                    return self._rgbatohex(
                        [int(a[:-1]) * 255 / 100.0 for a in rgb])
        raise ValueError('Illegal color values')

Response: Translate argb to color string


Instruction:
Create a Python 3 function for
translating hsl to color string raises ValueError ValueError

Response:
def hsl(self, *args):
        """ Translate hsl(...) to color string
        raises:
            ValueError
        returns:
            str
        """
        if len(args) == 4:
            return self.hsla(*args)
        elif len(args) == 3:
            h, s, l = args
            rgb = colorsys.hls_to_rgb(
                int(h) / 360.0, utility.pc_or_float(l), utility.pc_or_float(s))
            color = (utility.convergent_round(c * 255) for c in rgb)
            return self._rgbatohex(color)
        raise ValueError('Illegal color values')


Instruction:
Can you generate the documentation for the following Python 3 function
def hsla(self, *args):
        if len(args) == 4:
            h, s, l, a = args
            rgb = colorsys.hls_to_rgb(
                int(h) / 360.0, utility.pc_or_float(l), utility.pc_or_float(s))
            color = [float(utility.convergent_round(c * 255)) for c in rgb]
            color.append(utility.pc_or_float(a))
            return "rgba(%s,%s,%s,%s)" % tuple(color)
        raise ValueError('Illegal color values')

Response: Translate hsla to color string raises ValueError ValueError


Instruction:
Can you implement a function in Python 3 that
returns the hue value of a color in a nutl.

Response:
def hue(self, color, *args):
        """ Return the hue value of a color
        args:
            color (str): color
        raises:
            ValueError
        returns:
            float
        """
        if color:
            h, l, s = self._hextohls(color)
            return utility.convergent_round(h * 360.0, 3)
        raise ValueError('Illegal color values')


Instruction:
Can you implement a function in Python 3 that
returns the saturation value of a color in a nutime.

Response:
def saturation(self, color, *args):
        """ Return the saturation value of a color
        args:
            color (str): color
        raises:
            ValueError
        returns:
            float
        """
        if color:
            h, l, s = self._hextohls(color)
            return s * 100.0
        raise ValueError('Illegal color values')


Instruction:
How would you implement a function in Python 3 that
lightens a color args: color (str): color diff (str): percentage returns: str

Response:
def lighten(self, color, diff, *args):
        """ Lighten a color
        args:
            color (str): color
            diff (str): percentage
        returns:
            str
        """
        if color and diff:
            return self._ophsl(color, diff, 1, operator.add)
        raise ValueError('Illegal color values')


Instruction:
Write a Python 3 function for
darkening a color args: color (str): color diff (str): percentage returns: str

Response:
def darken(self, color, diff, *args):
        """ Darken a color
        args:
            color (str): color
            diff (str): percentage
        returns:
            str
        """
        if color and diff:
            return self._ophsl(color, diff, 1, operator.sub)
        raise ValueError('Illegal color values')


Instruction:
Can you implement a function in Python 3 that
spins color by degree.

Response:
def spin(self, color, degree, *args):
        """ Spin color by degree. (Increase / decrease hue)
        args:
            color (str): color
            degree (str): percentage
        raises:
            ValueError
        returns:
            str
        """
        if color and degree:
            if isinstance(degree, string_types):
                degree = float(degree.strip('%'))
            h, l, s = self._hextohls(color)
            h = ((h * 360.0) + degree) % 360.0
            h = 360.0 + h if h < 0 else h
            rgb = colorsys.hls_to_rgb(h / 360.0, l, s)
            color = (utility.convergent_round(c * 255) for c in rgb)
            return self._rgbatohex(color)
        raise ValueError('Illegal color values')


Instruction:
Write a Python 3 function that can
format CSS Hex color code.

Response:
def fmt(self, color):
        """ Format CSS Hex color code.
        uppercase becomes lowercase, 3 digit codes expand to 6 digit.
        args:
            color (str): color
        raises:
            ValueError
        returns:
            str
        """
        if utility.is_color(color):
            color = color.lower().strip('#')
            if len(color) in [3, 4]:
                color = ''.join([c * 2 for c in color])
            return '#%s' % color
        raise ValueError('Cannot format non-color')


Instruction:
Create a Python 3 function for
flattening a list of items into a single element

Response:
def flatten(lst):
    """Flatten list.
    Args:
        lst (list): List to flatten
    Returns:
        generator
    """
    for elm in lst:
        if isinstance(elm, collections.Iterable) and not isinstance(
                elm, string_types):
            for sub in flatten(elm):
                yield sub
        else:
            yield elm


Instruction:
Make a summary of the following Python 3 code
def pairwise(lst):
    if not lst:
        return
    length = len(lst)
    for i in range(length - 1):
        yield lst[i], lst[i + 1]
    yield lst[-1], None

Response: Yields items i and i + 1 in lst. e. g. item i and item i + 1 in lst. e. g. item i and item i + 1 in lst. e. g. item i and item i + 1 in lst. e. g. item i + 1 is None is returned.


Instruction:
Implement a function in Python 3 to
rename all sub - blocks moved under another block.

Response:
def rename(blocks, scope, stype):
    """ Rename all sub-blocks moved under another
        block. (mixins)
    Args:
        lst (list): block list
        scope (object): Scope object
    """
    for p in blocks:
        if isinstance(p, stype):
            p.tokens[0].parse(scope)
            if p.tokens[1]:
                scope.push()
                scope.current = p.tokens[0]
                rename(p.tokens[1], scope, stype)
                scope.pop()


Instruction:
How would you explain what the following Python 3 function does
def blocksearch(block, name):
    if hasattr(block, 'tokens'):
        for b in block.tokens[1]:
            b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch(
                b, name))
            if b:
                return b
    return False

Response: Recursive search for name in block


Instruction:
Can you create a Python 3 function that
reverses guard expression. not (@a > 5) -> (@a =< 5) Args: lst (list): Expression returns: list

Response:
def reverse_guard(lst):
    """ Reverse guard expression. not
        (@a > 5) ->  (@a =< 5)
    Args:
        lst (list): Expression
    returns:
        list
    """
    rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'}
    return [rev[l] if l in rev else l for l in lst]


Instruction:
Explain what the following Python 3 code does
def debug_print(lst, lvl=0):
    pad = ''.join(['\t.'] * lvl)
    t = type(lst)
    if t is list:
        for p in lst:
            debug_print(p, lvl)
    elif hasattr(lst, 'tokens'):
        print(pad, t)
        debug_print(list(flatten(lst.tokens)), lvl + 1)

Response: Print scope tree with nesting level lvl.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def analyze_number(var, err=''):
    n, u = split_unit(var)
    if not isinstance(var, string_types):
        return (var, u)
    if is_color(var):
        return (var, 'color')
    if is_int(n):
        n = int(n)
    elif is_float(n):
        n = float(n)
    else:
        raise SyntaxError('%s ´%s´' % (err, var))
    return (n, u)

Response:
Analyse number for type and split from unit
    1px -> ( q px )


Instruction:
How would you code a function in Python 3 to
return number with unit

Response:
def with_unit(number, unit=None):
    """ Return number with unit
    args:
        number (mixed): Number
        unit (str): Unit
    returns:
        str
    """
    if isinstance(number, tuple):
        number, unit = number
    if number == 0:
        return '0'
    if unit:
        number = str(number)
        if number.startswith('.'):
            number = '0' + number
        return "%s%s" % (number, unit)
    return number if isinstance(number, string_types) else str(number)


Instruction:
How would you code a function in Python 3 to
am string CSS color

Response:
def is_color(value):
    """ Is string CSS color
    args:
        value (str): string
    returns:
        bool
    """
    if not value or not isinstance(value, string_types):
        return False
    if value[0] == '#' and len(value) in [4, 5, 7, 9]:
        try:
            int(value[1:], 16)
            return True
        except ValueError:
            pass
    return False


Instruction:
Explain what the following Python 3 code does
def is_variable(value):
    if isinstance(value, string_types):
        return (value.startswith('@') or value.startswith('-@'))
    elif isinstance(value, tuple):
        value = ''.join(value)
        return (value.startswith('@') or value.startswith('-@'))
    return False

Response: Check if string is LESS variable


Instruction:
How would you code a function in Python 3 to
am value float args: value (str): string returns: bool

Response:
def is_float(value):
    """ Is value float
    args:
        value (str): string
    returns:
        bool
    """
    if not is_int(value):
        try:
            float(str(value))
            return True
        except (ValueError, TypeError):
            pass
    return False


Instruction:
Create a Python 3 function for
splitting a number from its unit 1px -> q px

Response:
def split_unit(value):
    """ Split a number from its unit
        1px -> (q, 'px')
    Args:
        value (str): input
    returns:
        tuple
    """
    r = re.search('^(\-?[\d\.]+)(.*)$', str(value))
    return r.groups() if r else ('', '')


Instruction:
Can you write a function in Python 3 where it
rounds half - way away from zero.

Response:
def away_from_zero_round(value, ndigits=0):
    """Round half-way away from zero.

    Python2's round() method.
    """
    if sys.version_info[0] >= 3:
        p = 10**ndigits
        return float(math.floor((value * p) + math.copysign(0.5, value))) / p
    else:
        return round(value, ndigits)


Instruction:
Here you have a function in Python 3, explain what it does
def pc_or_float(s):
    if isinstance(s, string_types) and '%' in s:
        return float(s.strip('%')) / 100.0
    return float(s)

Response: Utility function to process strings that contain either percentiles or floats


Instruction:
Explain what the following Python 3 code does
def permutations_with_replacement(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in itertools.product(range(n), repeat=r):
        yield list(pool[i] for i in indices)

Response: Returns successive r length permutations of elements in the iterable.


Instruction:
Create a Python 3 function to
parse a node name and return the node name.

Response:
def parse(self, scope):
        """ Parse Node
        args:
            scope (Scope): Scope object
        raises:
            SyntaxError
        returns:
            str
        """
        assert (len(self.tokens) == 3)
        expr = self.process(self.tokens, scope)
        A, O, B = [
            e[0] if isinstance(e, tuple) else e for e in expr
            if str(e).strip()
        ]
        try:
            a, ua = utility.analyze_number(A, 'Illegal element in expression')
            b, ub = utility.analyze_number(B, 'Illegal element in expression')
        except SyntaxError:
            return ' '.join([str(A), str(O), str(B)])
        if (a is False or b is False):
            return ' '.join([str(A), str(O), str(B)])
        if ua == 'color' or ub == 'color':
            return color.Color().process((A, O, B))
        if a == 0 and O == '/':
            # NOTE(saschpe): The ugliest but valid CSS since sliced bread: 'font: 0/1 a;'
            return ''.join([str(A), str(O), str(B), ' '])
        out = self.operate(a, b, O)
        if isinstance(out, bool):
            return out
        return self.with_units(out, ua, ub)


Instruction:
Implement a function in Python 3 to
return value with unit.

Response:
def with_units(self, val, ua, ub):
        """Return value with unit.
        args:
            val (mixed): result
            ua (str): 1st unit
            ub (str): 2nd unit
        raises:
            SyntaxError
        returns:
            str
        """
        if not val:
            return str(val)
        if ua or ub:
            if ua and ub:
                if ua == ub:
                    return str(val) + ua
                else:
                    # Nodejs version does not seem to mind mismatched
                    # units within expressions. So we choose the first
                    # as they do
                    # raise SyntaxError("Error in expression %s != %s" % (ua, ub))
                    return str(val) + ua
            elif ua:
                return str(val) + ua
            elif ub:
                return str(val) + ub
        return repr(val)


Instruction:
How would you explain what the following Python 3 function does
def operate(self, vala, valb, oper):
        operation = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv,
            '=': operator.eq,
            '>': operator.gt,
            '<': operator.lt,
            '>=': operator.ge,
            '=<': operator.le,
        }.get(oper)
        if operation is None:
            raise SyntaxError("Unknown operation %s" % oper)
        ret = operation(vala, valb)
        if oper in '+-*/' and int(ret) == ret:
            ret = int(ret)
        return ret

Response: Perform an operation on the key - value pair.


Instruction:
Write a Python 3 script for
parsing a file into a set of unique identifiers.

Response:
def parse(self, filename=None, file=None, debuglevel=0):
        """ Parse file.
        kwargs:
            filename (str): File to parse
            debuglevel (int): Parser debuglevel
        """
        self.scope.push()

        if not file:
            # We use a path.
            file = filename
        else:
            # We use a stream and try to extract the name from the stream.
            if hasattr(file, 'name'):
                if filename is not None:
                    raise AssertionError(
                        'names of file and filename are in conflict')
                filename = file.name
            else:
                filename = '(stream)'

        self.target = filename
        if self.verbose and not self.fail_with_exc:
            print('Compiling target: %s' % filename, file=sys.stderr)
        self.result = self.parser.parse(file, lexer=self.lex, debug=debuglevel)

        self.post_parse()
        self.register.close()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def post_parse(self):
        if self.result:
            out = []
            for pu in self.result:
                try:
                    out.append(pu.parse(self.scope))
                except SyntaxError as e:
                    self.handle_error(e, 0)
            self.result = list(utility.flatten(out))

Response:
Post parse cycle. nodejs version allows calls to mixins
        not yet defined or known to the parser. We defer all calls
        to mixins until after first cycle when all names are known.


Instruction:
Can you tell what is the following Python 3 function doing
def p_unit_list(self, p):
        if isinstance(p[1], list):
            if len(p) >= 3:
                if isinstance(p[2], list):
                    p[1].extend(p[2])
                else:
                    p[1].append(p[2])
        else:
            p[1] = [p[1]]
        p[0] = p[1]

Response: unit_list - list of all units


Instruction:
Can you generate the documentation for the following Python 3 function
def p_statement_namespace(self, p):
        p[0] = Statement(list(p)[1:], p.lineno(1))
        p[0].parse(None)

Response: Parse a statement in the form of a namespace.


Instruction:
Can you tell what is the following Python 3 function doing
def p_block(self, p):
        p[0] = Block(list(p)[1:-1], p.lineno(3))
        self.scope.pop()
        self.scope.add_block(p[0])

Response: block_decl               : block_open declaration_list brace_close


Instruction:
How would you implement a function in Python 3 that
replaces block with new one.

Response:
def p_block_replace(self, p):
        """ block_decl               : identifier t_semicolon
        """
        m = p[1].parse(None)
        block = self.scope.blocks(m.raw())
        if block:
            p[0] = block.copy_inner(self.scope)
        else:
            # fallback to mixin. Allow calls to mixins without parens
            p[0] = Deferred(p[1], None, p.lineno(2))


Instruction:
Here you have a function in Python 3, explain what it does
def p_font_face_open(self, p):
        p[0] = Identifier([p[1], p[2]]).parse(self.scope)

Response: P font face open section


Instruction:
How would you explain what the following Python 3 function does
def p_open_mixin(self, p):
        p[1].parse(self.scope)
        self.scope.current = p[1]
        p[0] = [p[1], p[3]]
        if len(p) > 6:
            p[0].append(p[5])
        else:
            p[0].append(None)

Response: open_mixin - Handles the mixin - level open - mixin command.


Instruction:
Given the following Python 3 function, write the documentation
def p_mixin_guard_cond_list_aux(self, p):
        p[1].append(p[2])
        p[1].append(p[3])
        p[0] = p[1]

Response: A mixin guard condition list auxiliary function.


Instruction:
Explain what the following Python 3 code does
def p_call_mixin(self, p):
        p[1].parse(None)
        p[0] = Deferred(p[1], p[3], p.lineno(4))

Response: \ x1b [ 1mNAME \ x1b [ 0m mixin - Augment the mixin with a Deferred object.


Instruction:
Given the following Python 3 function, write the documentation
def p_declaration_list(self, p):
        if len(p) > 2:
            p[1].extend(p[2])
        p[0] = p[1]

Response: A function to add the declaration_list to the given parameter list.


Instruction:
Can you tell what is the following Python 3 function doing
def p_variable_decl(self, p):
        p[0] = Variable(list(p)[1:-1], p.lineno(4))
        p[0].parse(self.scope)

Response: variable_decl            : variable t_colon style_list t_semicolon


Instruction:
How would you code a function in Python 3 to
parse the property declaration.

Response:
def p_property_decl(self, p):
        """ property_decl           : prop_open style_list t_semicolon
                                    | prop_open style_list css_important t_semicolon
                                    | prop_open empty t_semicolon
        """
        l = len(p)
        p[0] = Property(list(p)[1:-1], p.lineno(l - 1))


Instruction:
Here you have a function in Python 3, explain what it does
def p_identifier_list_aux(self, p):
        p[1].extend([p[2]])
        p[1].extend(p[3])
        p[0] = p[1]

Response: A version of the identifier_list_aux method.


Instruction:
Here you have a function in Python 3, explain what it does
def p_identifier_group_op(self, p):
        p[1].extend([p[2]])
        if len(p) > 3:
            p[1].extend(p[3])
        p[0] = p[1]

Response: A function to handle the identifier_group operation.


Instruction:
Can you tell what is the following Python 3 function doing
def p_ident_parts_aux(self, p):
        if isinstance(p[2], list):
            p[1].extend(p[2])
        else:
            p[1].append(p[2])
        p[0] = p[1]

Response: A version of p_ident_parts_aux that adds the new version to the list of the set of available ident_parts.


Instruction:
Can you generate the documentation for the following Python 3 function
def p_ident_parts(self, p):
        if not isinstance(p[1], list):
            p[1] = [p[1]]
        p[0] = p[1]

Response: A helper function to set the ident_parts               property in a dict.


Instruction:
Here you have a function in Python 3, explain what it does
def p_media_query_value(self, p):
        if utility.is_variable(p[1]):
            var = self.scope.variables(''.join(p[1]))
            if var:
                value = var.value[0]
                if hasattr(value, 'parse'):
                    p[1] = value.parse(self.scope)
                else:
                    p[1] = value
        if isinstance(p[1], Expression):
            p[0] = p[1].parse(self.scope)
        else:
            p[0] = p[1]

Response:
media_query_value           : number
                                        | variable
                                        | word
                                        | color
                                        | expression


Instruction:
Can you tell what is the following Python 3 function doing
def p_color(self, p):
        try:
            p[0] = Color().fmt(p[1])
            if len(p) > 2:
                p[0] = [p[0], p[2]]
        except ValueError:
            self.handle_error('Illegal color value `%s`' % p[1], p.lineno(1),
                              'W')
            p[0] = p[1]

Response:
color                   : css_color
                                    | css_color t_ws


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_error(self, t):
        if t:
            error_msg = "E: %s line: %d, Syntax Error, token: `%s`, `%s`" % \
                      (self.target, t.lineno, t.type, t.value)
            self.register.register(error_msg)
        while True:
            t = self.lex.token()
            if not t or t.value == '}':
                if len(self.scope) > 1:
                    self.scope.pop()
                break
        self.parser.restart()
        return t

Response: Internal error handler for the internal error handler.


Instruction:
Can you tell what is the following Python 3 function doing
def handle_error(self, e, line, t='E'):
        self.register.register("%s: line: %d: %s\n" % (t, line, e))

Response:
Custom error handler for the
            class.


Instruction:
Create a Python 3 function for
parsing node s tokens and return a list of parsed tokens.

Response:
def parse(self, scope):
        """Parse node
        args:
            scope (Scope): current scope
        raises:
            SyntaxError
        returns:
            parsed
        """
        if not self.parsed:
            self.parsed = ''.join(self.process(self.tokens, scope))
        return self.parsed


Instruction:
Explain what the following Python 3 code does
def NextPage(gh):
    header = dict(gh.getheaders())
    if 'Link' in header:
        parts = header['Link'].split(',')
        for part in parts:
            subparts = part.split(';')
            sub = subparts[1].split('=')
            if sub[0].strip() == 'rel':
                if sub[1] == '"next"':
                    page = int(
                        re.match(
                            r'.*page=(\d+).*', subparts[0],
                            re.IGNORECASE | re.DOTALL | re.UNICODE
                        ).groups()[0]
                    )
                    return page
    return 0

Response: Checks if a GitHub call returned multiple pages of data.


Instruction:
Write a Python 3 function that can
fetch GitHub token from git config and last CHANGELOG_GITHUB_TOKEN env variable.

Response:
def fetch_github_token(self):
        """
        Fetch GitHub token. First try to use variable provided
        by --token option, otherwise try to fetch it from git config
        and last CHANGELOG_GITHUB_TOKEN env variable.

        :returns: Nothing
        """

        if not self.options.token:
            try:
                for v in GH_CFG_VARS:
                    cmd = ['git', 'config', '--get', '{0}'.format(v)]
                    self.options.token = subprocess.Popen(
                        cmd, stdout=subprocess.PIPE).communicate()[0].strip()
                    if self.options.token:
                        break
            except (subprocess.CalledProcessError, WindowsError):
                pass
        if not self.options.token:
            self.options.token = os.environ.get(CHANGELOG_GITHUB_TOKEN)
        if not self.options.token:
            print(NO_TOKEN_PROVIDED)


Instruction:
Can you create a Python 3 function that
fetches all tags for a repository from Github.

Response:
def get_all_tags(self):
        """
        Fetch all tags for repository from Github.

        :return: tags in repository
        :rtype: list
        """

        verbose = self.options.verbose
        gh = self.github
        user = self.options.user
        repo = self.options.project
        if verbose:
            print("Fetching tags...")

        tags = []
        page = 1
        while page > 0:
            if verbose > 2:
                print(".", end="")
            rc, data = gh.repos[user][repo].tags.get(
                page=page, per_page=PER_PAGE_NUMBER)
            if rc == 200:
                tags.extend(data)
            else:
                self.raise_GitHubError(rc, data, gh.getheaders())
            page = NextPage(gh)
        if verbose > 2:
            print(".")

        if len(tags) == 0:
            if not self.options.quiet:
                print("Warning: Can't find any tags in repo. Make sure, that "
                      "you push tags to remote repo via 'git push --tags'")
                exit()
        if verbose > 1:
            print("Found {} tag(s)".format(len(tags)))
        return tags


Instruction:
Can you generate the documentation for the following Python 3 function
def fetch_closed_issues_and_pr(self):

        verbose = self.options.verbose
        gh = self.github
        user = self.options.user
        repo = self.options.project
        if verbose:
            print("Fetching closed issues and pull requests...")

        data = []
        issues = []
        data = []
        page = 1
        while page > 0:
            if verbose > 2:
                print(".", end="")
            rc, data = gh.repos[user][repo].issues.get(
                page=page, per_page=PER_PAGE_NUMBER,
                state='closed', filter='all'
            )
            if rc == 200:
                issues.extend(data)
            else:
                self.raise_GitHubError(rc, data, gh.getheaders())
            if len(issues) >= self.options.max_issues:
                break
            page = NextPage(gh)
        self.first_issue = data[-1] if len(data) > 0 else []
        if verbose > 2:
            print(".")

        # separate arrays of issues and pull requests:
        prs = []
        iss = []
        for i in issues:
            if "pull_request" in i:
                prs.append(i)
            else:
                iss.append(i)
        if verbose > 1:
            print("\treceived {} issues and  {} pull requests.".format(
                len(iss), len(prs))
            )
        return iss, prs

Response: This method fetches all closed issues and pull requests and pure issues and pure issues.


Instruction:
Can you implement a function in Python 3 that
fetches all closed pull requests. We need them to detect merged_at

Response:
def fetch_closed_pull_requests(self):
        """
        Fetch all pull requests. We need them to detect "merged_at" parameter

        :rtype: list
        :return: all pull requests
        """

        pull_requests = []
        verbose = self.options.verbose
        gh = self.github
        user = self.options.user
        repo = self.options.project
        if verbose:
            print("Fetching closed pull requests...")
        page = 1
        while page > 0:
            if verbose > 2:
                print(".", end="")

            if self.options.release_branch:
                rc, data = gh.repos[user][repo].pulls.get(
                    page=page, per_page=PER_PAGE_NUMBER, state='closed',
                    base=self.options.release_branch
                )
            else:
                rc, data = gh.repos[user][repo].pulls.get(
                    page=page, per_page=PER_PAGE_NUMBER, state='closed',
                )

            if rc == 200:
                pull_requests.extend(data)
            else:
                self.raise_GitHubError(rc, data, gh.getheaders())
            page = NextPage(gh)
        if verbose > 2:
            print(".")
        if verbose > 1:
            print("\tfetched {} closed pull requests.".format(
                len(pull_requests))
            )
        return pull_requests


Instruction:
Explain what the following Python 3 code does
def fetch_repo_creation_date(self):
        gh = self.github
        user = self.options.user
        repo = self.options.project
        rc, data = gh.repos[user][repo].get()
        if rc == 200:
            return REPO_CREATED_TAG_NAME, data["created_at"]
        else:
            self.raise_GitHubError(rc, data, gh.getheaders())
        return None, None

Response: Fetch the creation date of the repository from GitHub.


Instruction:
How would you code a function in Python 3 to
fetch events for all issues and add them to self. events

Response:
def fetch_events_async(self, issues, tag_name):
        """
        Fetch events for all issues and add them to self.events

        :param list issues: all issues
        :param str tag_name: name of the tag to fetch events for
        :returns: Nothing
        """

        if not issues:
            return issues

        max_simultaneous_requests = self.options.max_simultaneous_requests
        verbose = self.options.verbose
        gh = self.github
        user = self.options.user
        repo = self.options.project
        self.events_cnt = 0
        if verbose:
            print("fetching events for {} {}... ".format(
                len(issues), tag_name)
            )

        def worker(issue):
            page = 1
            issue['events'] = []
            while page > 0:
                rc, data = gh.repos[user][repo].issues[
                    issue['number']].events.get(
                    page=page, per_page=PER_PAGE_NUMBER)
                if rc == 200:
                    issue['events'].extend(data)
                    self.events_cnt += len(data)
                else:
                    self.raise_GitHubError(rc, data, gh.getheaders())
                page = NextPage(gh)

        threads = []
        cnt = len(issues)
        for i in range(0, (cnt // max_simultaneous_requests) + 1):
            for j in range(max_simultaneous_requests):
                idx = i * max_simultaneous_requests + j
                if idx == cnt:
                    break
                t = threading.Thread(target=worker, args=(issues[idx],))
                threads.append(t)
                t.start()
                if verbose > 2:
                    print(".", end="")
                    if not idx % PER_PAGE_NUMBER:
                        print("")
            for t in threads:
                t.join()
        if verbose > 2:
            print(".")


Instruction:
Write a Python 3 script to
fetch time of specified tag from repository.

Response:
def fetch_date_of_tag(self, tag):
        """
        Fetch time for tag from repository.

        :param dict tag: dictionary with tag information
        :rtype: str
        :return: time of specified tag as ISO date string
        """

        if self.options.verbose > 1:
            print("\tFetching date for tag {}".format(tag["name"]))
        gh = self.github
        user = self.options.user
        repo = self.options.project

        rc, data = gh.repos[user][repo].git.commits[
            tag["commit"]["sha"]].get()
        if rc == 200:
            return data["committer"]["date"]
        self.raise_GitHubError(rc, data, gh.getheaders())


Instruction:
Given the following Python 3 function, write the documentation
def fetch_commit(self, event):

        gh = self.github
        user = self.options.user
        repo = self.options.project

        rc, data = gh.repos[user][repo].git.commits[
            event["commit_id"]].get()
        if rc == 200:
            return data
        self.raise_GitHubError(rc, data, gh.getheaders())

Response: Fetch the commit data for the specified event.


Instruction:
Here you have a function in Python 3, explain what it does
def run(self):
        if not self.options.project or not self.options.user:
            print("Project and/or user missing. "
                  "For help run:\n  pygcgen --help")
            return

        if not self.options.quiet:
            print("Generating changelog...")

        log = None
        try:
            log = self.generator.compound_changelog()
        except ChangelogGeneratorError as err:
            print("\n\033[91m\033[1m{}\x1b[0m".format(err.args[0]))
            exit(1)
        if not log:
            if not self.options.quiet:
                print("Empty changelog generated. {} not written.".format(
                    self.options.output)
                )
            return

        if self.options.no_overwrite:
            out = checkname(self.options.output)
        else:
            out = self.options.output

        with codecs.open(out, "w", "utf-8") as fh:
            fh.write(log)

        if not self.options.quiet:
            print("Done!")
            print("Generated changelog written to {}".format(out))

Response: Generate a new entry point for one of the tags in the list of tags.


Instruction:
How would you explain what the following Python 3 function does
def parse_heading(heading):

    heading_structures = [
        r"^## \[(?P<version>.+?)\]\((?P<url>.+?)\)( \((?P<date>.+?)\))?$",
        r"^## (?P<version>.+?)( \((?P<date>.+?)\))?$",
        ]
    captures = {"version": None, "url": None, "date": None}

    for regexp in heading_structures:
        matches = re.match(regexp, heading)
        if matches:
            captures.update(matches.groupdict())
            break
    return captures

Response: Parse a single heading and return a Hash containing version url and date.


Instruction:
Make a summary of the following Python 3 code
def parse(data):

    sections = re.compile("^## .+$", re.MULTILINE).split(data)
    headings = re.findall("^## .+?$", data, re.MULTILINE)
    sections.pop(0)
    parsed = []

    def func(h, s):
        p = parse_heading(h)
        p["content"] = s
        parsed.append(p)

    list(map(func, headings, sections))
    return parsed

Response: Parse the given ChangeLog data into a list of Hashes.


Instruction:
Write a Python 3 script to
create the signal handler map based on self. signal_map

Response:
def _signal_handler_map(self):
        """ Create the signal handler map

        create a dictionary with signal:handler mapping based on
        self.signal_map

        :return: dict
        """
        result = {}
        for signum, handler in self.signal_map.items():
            result[signum] = self._get_signal_handler(handler)
        return result


Instruction:
Can you generate the documentation for the following Python 3 function
def open(self):
        if self.is_open:
            return
        try:
            os.chdir(self.working_directory)
            if self.chroot_directory:
                os.chroot(self.chroot_directory)
            os.setgid(self.gid)
            os.setuid(self.uid)
            os.umask(self.umask)
        except OSError as err:
            raise DaemonError('Setting up Environment failed: {0}'
                              .format(err))

        if self.prevent_core:
            try:
                resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
            except Exception as err:
                raise DaemonError('Could not disable core files: {0}'
                                  .format(err))

        if self.detach_process:
            try:
                if os.fork() > 0:
                    os._exit(0)
            except OSError as err:
                raise DaemonError('First fork failed: {0}'.format(err))
            os.setsid()
            try:
                if os.fork() > 0:
                    os._exit(0)
            except OSError as err:
                raise DaemonError('Second fork failed: {0}'.format(err))

        for (signal_number, handler) in self._signal_handler_map.items():
            signal.signal(signal_number, handler)

        close_filenos(self._files_preserve)

        redirect_stream(sys.stdin, self.stdin)
        redirect_stream(sys.stdout, self.stdout)
        redirect_stream(sys.stderr, self.stderr)

        if self.pidfile:
            self.pidfile.acquire()

        self._is_open = True

Response: Open the process and return the unique identifier.


Instruction:
Here you have a function in Python 3, explain what it does
def user_and_project_from_git(self, options, arg0=None, arg1=None):
        user, project = self.user_project_from_option(options, arg0, arg1)
        if user and project:
            return user, project

        try:
            remote = subprocess.check_output(
                [
                    'git', 'config', '--get',
                    'remote.{0}.url'.format(options.git_remote)
                ]
            )
        except subprocess.CalledProcessError:
            return None, None
        except WindowsError:
            print("git binary not found.")
            exit(1)
        else:
            return self.user_project_from_remote(remote)

Response: Detects user and project from git.


Instruction:
Write a Python 3 script to
try to find user and project name from git remote command MimeType

Response:
def user_project_from_option(options, arg0, arg1):
        """
        Try to find user and project name from git remote output

        @param [String] output of git remote command
        @return [Array] user and project
        """

        site = options.github_site
        if arg0 and not arg1:
            # this match should parse strings such as
            #   "https://github.com/skywinder/Github-Changelog-Generator"
            # or
            #   "skywinder/Github-Changelog-Generator"
            #  to user and project
            match = re.match(
                "(?:.+{site}/)?(.+)/(.+)".format(site=site),
                arg0
            )
            if not match:
                print("Can't detect user and name from first "
                      "parameter: '{arg0}' -> exit'".format(arg0=arg0))
                exit(1)
            return match.groups()
        return None, None


Instruction:
Can you tell what is the following Python 3 function doing
def user_project_from_remote(remote):

        # try to find repo in format:
        # origin	git@github.com:skywinder/Github-Changelog-Generator.git (fetch)
        # git@github.com:skywinder/Github-Changelog-Generator.git
        regex1 = br".*(?:[:/])(?P<user>(-|\w|\.)*)/" \
                 br"(?P<project>(-|\w|\.)*)(\.git).*"
        match = re.match(regex1, remote)
        if match:
            return match.group("user"), match.group("project")

        # try to find repo in format:
        # origin	https://github.com/skywinder/ChangelogMerger (fetch)
        # https://github.com/skywinder/ChangelogMerger
        regex2 = r".*/((?:-|\w|\.)*)/((?:-|\w|\.)*).*"
        match = re.match(regex2, remote)
        if match:
            return match.group("user"), match.group("project")

        return None, None

Response: Try to find user and project name from git remote output


Instruction:
Here you have a function in Python 3, explain what it does
def timestring_to_datetime(timestring):
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=UnicodeWarning)
        result = dateutil_parser(timestring)

    return result

Response: Convert an ISO formated date and time string to a datetime object.


Instruction:
Create a Python 3 function for
fetching event for issues and pull requests

Response:
def fetch_events_for_issues_and_pr(self):
        """
        Fetch event for issues and pull requests

        @return [Array] array of fetched issues
        """

        # Async fetching events:
        self.fetcher.fetch_events_async(self.issues, "issues")
        self.fetcher.fetch_events_async(self.pull_requests, "pull requests")


Instruction:
Make a summary of the following Python 3 code
def detect_actual_closed_dates(self, issues, kind):

        if self.options.verbose:
            print("Fetching closed dates for {} {}...".format(
                len(issues), kind)
            )
        all_issues = copy.deepcopy(issues)
        for issue in all_issues:
            if self.options.verbose > 2:
                print(".", end="")
                if not issues.index(issue) % 30:
                    print("")
            self.find_closed_date_by_commit(issue)

            if not issue.get('actual_date', False):
                if issue.get('closed_at', False):
                    print("Skipping closed non-merged issue: #{0} {1}".format(
                        issue["number"], issue["title"]))

                all_issues.remove(issue)

        if self.options.verbose > 2:
            print(".")
        return all_issues

Response: Detects correct closed dates for issues that were closed by commits.


Instruction:
Given the following Python 3 function, write the documentation
def find_closed_date_by_commit(self, issue):

        if not issue.get('events'):
            return
        # if it's PR -> then find "merged event", in case
        # of usual issue -> find closed date
        compare_string = "merged" if 'merged_at' in issue else "closed"
        # reverse! - to find latest closed event. (event goes in date order)
        # if it were reopened and closed again.
        issue['events'].reverse()
        found_date = False
        for event in issue['events']:
            if event["event"] == compare_string:
                self.set_date_from_event(event, issue)
                found_date = True
                break
        if not found_date:
            # TODO: assert issues, that remain without
            #       'actual_date' hash for some reason.
            print("\nWARNING: Issue without 'actual_date':"
                  " #{0} {1}".format(issue["number"], issue["title"]))

Response: Find the closed date of a given issue by the commit.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_date_from_event(self, event, issue):

        if not event.get('commit_id', None):
            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])
            return
        try:
            commit = self.fetcher.fetch_commit(event)
            issue['actual_date'] = timestring_to_datetime(
                commit['author']['date']
            )
        except ValueError:
            print("WARNING: Can't fetch commit {0}. "
                  "It is probably referenced from another repo.".
                  format(event['commit_id']))
            issue['actual_date'] = timestring_to_datetime(issue['closed_at'])

Response: Set the actual date from this issue.


Instruction:
Can you implement a function in Python 3 that
encapsulates characters to make markdown look as expected.

Response:
def encapsulate_string(raw_string):
        """
        Encapsulate characters to make markdown look as expected.

        :param str raw_string: string to encapsulate
        :rtype: str
        :return: encapsulated input string
        """

        raw_string.replace('\\', '\\\\')
        enc_string = re.sub("([<>*_()\[\]#])", r"\\\1", raw_string)
        return enc_string


Instruction:
Given the following Python 3 function, write the documentation
def compound_changelog(self):

        self.fetch_and_filter_tags()
        tags_sorted = self.sort_tags_by_date(self.filtered_tags)
        self.filtered_tags = tags_sorted
        self.fetch_and_filter_issues_and_pr()

        log = str(self.options.frontmatter) \
            if self.options.frontmatter else u""
        log += u"{0}\n\n".format(self.options.header)

        if self.options.unreleased_only:
            log += self.generate_unreleased_section()
        else:
            log += self.generate_log_for_all_tags()

        try:
            with open(self.options.base) as fh:
                log += fh.read()
        except (TypeError, IOError):
            pass
        return log

Response: Generates a compound change log file for the current locale.


Instruction:
Can you write a function in Python 3 where it
generates formated list of issues for changelog.

Response:
def generate_sub_section(self, issues, prefix):
        """
        Generate formated list of issues for changelog.

        :param list issues: Issues to put in sub-section.
        :param str prefix: Title of sub-section.
        :rtype: str
        :return: Generated ready-to-add sub-section.
        """

        log = ""
        if issues:
            if not self.options.simple_list:
                log += u"{0}\n\n".format(prefix)
            for issue in issues:
                merge_string = self.get_string_for_issue(issue)
                log += u"- {0}\n".format(merge_string)
            log += "\n"
        return log


Instruction:
Implement a function in Python 3 to
generate a header for a tag section.

Response:
def generate_header(self, newer_tag_name, newer_tag_link,
                        newer_tag_time,
                        older_tag_link, project_url):
        """
        Generate a header for a tag section with specific parameters.

        :param str newer_tag_name: Name (title) of newer tag.
        :param str newer_tag_link: Tag name of newer tag, used for links.
                               Could be same as **newer_tag_name** or some
                               specific value, like `HEAD`.
        :param datetime newer_tag_time: Date and time when
                                        newer tag was created.
        :param str older_tag_link: Tag name of older tag, used for links.
        :param str project_url: URL for current project.
        :rtype: str
        :return: Generated ready-to-add tag section.
        """

        log = ""
        # Generate date string:
        # noinspection PyUnresolvedReferences
        time_string = newer_tag_time.strftime(self.options.date_format)

        # Generate tag name and link
        if self.options.release_url:
            release_url = self.options.release_url.format(newer_tag_link)
        else:
            release_url = u"{project_url}/tree/{newer_tag_link}".format(
                project_url=project_url, newer_tag_link=newer_tag_link)

        if not self.options.unreleased_with_date and \
                newer_tag_name == self.options.unreleased_label:
            log += u"## [{newer_tag_name}]({release_url})\n\n".format(
                newer_tag_name=newer_tag_name, release_url=release_url)
        else:
            log += u"## [{newer_tag_name}]({release_url}) " \
                   u"({time_string})\n".format(
                        newer_tag_name=newer_tag_name,
                        release_url=release_url,
                        time_string=time_string
                   )

        if self.options.compare_link \
            and older_tag_link != REPO_CREATED_TAG_NAME:
            # Generate compare link
            log += u"[Full Changelog]"
            log += u"({project_url}/compare/{older_tag_link}".format(
                project_url=project_url,
                older_tag_link=older_tag_link,
            )
            log += u"...{newer_tag_link})\n\n".format(
                newer_tag_link=newer_tag_link
            )
        return log


Instruction:
How would you implement a function in Python 3 that
generates log between two tags.

Response:
def generate_log_between_tags(self, older_tag, newer_tag):
        """
        Generate log between 2 specified tags.

        :param dict older_tag: All issues before this tag's date will be
                               excluded. May be special value, if new tag is
                               the first tag. (Means **older_tag** is when
                               the repo was created.)
        :param dict newer_tag: All issues after this tag's date  will be
                               excluded. May be title of unreleased section.
        :rtype: str
        :return: Generated ready-to-add tag section for newer tag.
        """

        filtered_issues, filtered_pull_requests = \
            self.filter_issues_for_tags(newer_tag, older_tag)

        older_tag_name = older_tag["name"] if older_tag \
            else self.detect_since_tag()

        if not filtered_issues and not filtered_pull_requests:
            # do not generate an unreleased section if it would be empty
            return ""
        return self.generate_log_for_tag(
            filtered_pull_requests, filtered_issues,
            newer_tag, older_tag_name)


Instruction:
Create a Python 3 function for
applying all filters to issues and pull requests.

Response:
def filter_issues_for_tags(self, newer_tag, older_tag):
        """
        Apply all filters to issues and pull requests.

        :param dict older_tag: All issues before this tag's date will be
                               excluded. May be special value, if new tag is
                               the first tag. (Means **older_tag** is when
                               the repo  was created.)
        :param dict newer_tag: All issues after this tag's date  will be
                               excluded. May be title of unreleased section.
        :rtype: list(dict), list(dict)
        :return: Filtered issues and pull requests.
        """

        filtered_pull_requests = self.delete_by_time(self.pull_requests,
                                                     older_tag, newer_tag)
        filtered_issues = self.delete_by_time(self.issues, older_tag,
                                              newer_tag)

        newer_tag_name = newer_tag["name"] if newer_tag else None

        if self.options.filter_issues_by_milestone:
            # delete excess irrelevant issues (according milestones).Issue #22.
            filtered_issues = self.filter_by_milestone(
                filtered_issues, newer_tag_name, self.issues
            )
            filtered_pull_requests = self.filter_by_milestone(
                filtered_pull_requests, newer_tag_name, self.pull_requests
            )
        return filtered_issues, filtered_pull_requests


Instruction:
Implement a Python 3 function for
generating a complete change log for all tags.

Response:
def generate_log_for_all_tags(self):
        """
        The full cycle of generation for whole project.

        :rtype: str
        :return: The complete change log for released tags.
        """

        if self.options.verbose:
            print("Generating log...")
        self.issues2 = copy.deepcopy(self.issues)

        log1 = ""
        if self.options.with_unreleased:
            log1 = self.generate_unreleased_section()

        log = ""
        for index in range(len(self.filtered_tags) - 1):
            log += self.do_generate_log_for_all_tags_part1(log, index)

        if self.options.tag_separator and log1:
            log = log1 + self.options.tag_separator + log
        else:
            log = log1 + log

        if len(self.filtered_tags) != 0:
            log += self.do_generate_log_for_all_tags_part2(log)

        return log


Instruction:
Can you create a Python 3 function that
generates log for unreleased closed issues.

Response:
def generate_unreleased_section(self):
        """
        Generate log for unreleased closed issues.

        :rtype: str
        :return: Generated ready-to-add unreleased section.
        """
        if not self.filtered_tags:
            return ""
        now = datetime.datetime.utcnow()
        now = now.replace(tzinfo=dateutil.tz.tzutc())
        head_tag = {"name": self.options.unreleased_label}
        self.tag_times_dict[head_tag["name"]] = now
        unreleased_log = self.generate_log_between_tags(
            self.filtered_tags[0], head_tag)
        return unreleased_log


Instruction:
Make a summary of the following Python 3 code
def get_string_for_issue(self, issue):

        encapsulated_title = self.encapsulate_string(issue['title'])
        try:
            title_with_number = u"{0} [\\#{1}]({2})".format(
                encapsulated_title, issue["number"], issue["html_url"]
            )
        except UnicodeEncodeError:
            # TODO: why did i add this? Is it needed?
            title_with_number = "ERROR ERROR ERROR: #{0} {1}".format(
                issue["number"], issue['title']
            )
            print(title_with_number, '\n', issue["html_url"])
        return self.issue_line_with_user(title_with_number, issue)

Response: Parse issue and generate single line formatted issue line.