def Func(
        arg_0,
        arg_1=('Template',),
        arg_2=False,
        arg_3: arg_4 = None,
        *,
        arg_5: arg_4 = None,
        arg_6=False
    ) -> arg_4:
        """Return normal form of self.name.

        - Remove comments.
        - Remove language code.
        - Remove namespace ("template:" or any of `localized_namespaces`.
        - Use space instead of underscore.
        - Remove consecutive spaces.
        - Use uppercase for the first letter if `capitalize`.
        - Remove #anchor.

        :param rm_namespaces: is used to provide additional localized
            namespaces for the template namespace. They will be removed from
            the result. Default is ('Template',).
        :param capitalize: If True, convert the first letter of the
            template's name to a capital letter. See
            [[mw:Manual:$wgCapitalLinks]] for more info.
        :param code: is the language code.
        :param capital_links: deprecated.
        :param _code: deprecated.

        Example:
            >>> Template(
            ...     '{{ eN : tEmPlAtE : <!-- c --> t_1 # b | a }}'
            ... ).Func(code='en')
            'T 1'
        """
        if arg_2:
            warn('`capital_links` argument is deprecated,'
                 ' use `capitalize` instead', DeprecationWarning)
            arg_6 = arg_2
        if arg_3:
            warn('`positional_code` argument is deprecated,'
                 ' use `code` instead', DeprecationWarning)
            arg_5 = arg_3
        # Remove comments
        arg_7 = COMMENT_SUB('', arg_0.name).strip(WS)
        # Remove code
        if arg_5:
            arg_8, arg_9, arg_10 = arg_7.partition(':')
            if not arg_8 and arg_9:
                arg_7 = arg_10.strip(' ')
                arg_8, arg_9, arg_10 = arg_7.partition(':')
            if arg_5.lower() == arg_8.strip(' ').lower():
                arg_7 = arg_10.strip(' ')
        # Remove namespace
        arg_8, arg_9, arg_10 = arg_7.partition(':')
        if not arg_8 and arg_9:
            arg_7 = arg_10.strip(' ')
            arg_8, arg_9, arg_10 = arg_7.partition(':')
        if arg_8:
            arg_11 = arg_8.strip(' ').lower()
            for arg_12 in arg_1:
                if arg_12.lower() == arg_11:
                    arg_7 = arg_10.strip(' ')
                    break
        # Use space instead of underscore
        arg_7 = arg_7.replace('_', ' ')
        if arg_6:
            # Use uppercase for the first letter
            arg_13 = arg_7[0]
            if arg_13.islower():
                arg_7 = arg_13.upper() + arg_7[1:]
        # Remove #anchor
        arg_7, arg_9, arg_10 = arg_7.partition('#')
        return ' '.join(arg_7.split())


def Func(arg_0) -> None:
        """Eliminate duplicate arguments by removing the first occurrences.

        Remove the first occurrences of duplicate arguments, regardless of
        their value. Result of the rendered wikitext should remain the same.
        Warning: Some meaningful data may be removed from wikitext.

        Also see `rm_dup_args_safe` function.
        """
        arg_1 = set()  # type: set
        for arg_2 in reversed(arg_0.arguments):
            arg_3 = arg_2.name.strip(WS)
            if arg_3 in arg_1:
                del arg_2[:len(arg_2.string)]
            else:
                arg_1.add(arg_3)


def Func(arg_0, arg_1: arg_2 = None) -> None:
        """Remove duplicate arguments in a safe manner.

        Remove the duplicate arguments only in the following situations:
            1. Both arguments have the same name AND value. (Remove one of
                them.)
            2. Arguments have the same name and one of them is empty. (Remove
                the empty one.)

        Warning: Although this is considered to be safe and no meaningful data
            is removed from wikitext, but the result of the rendered wikitext
            may actually change if the second arg is empty and removed but
            the first had had a value.

        If `tag` is defined, it should be a string that will be appended to
        the value of the remaining duplicate arguments.

        Also see `rm_first_of_dup_args` function.
        """
        arg_3 = {} \
            # type: Dict[str, Tuple[Argument, List[str]]]
        # Removing positional args affects their name. By reversing the list
        # we avoid encountering those kind of args.
        for arg_4 in reversed(arg_0.arguments):
            arg_5 = arg_4.name.strip(WS)
            if arg_4.positional:
                # Value of keyword arguments is automatically stripped by MW.
                arg_6 = arg_4.value
            else:
                # But it's not OK to strip whitespace in positional arguments.
                arg_6 = arg_4.value.strip(WS)
            if arg_5 in arg_3:
                # This is a duplicate argument.
                if not arg_6:
                    # This duplicate argument is empty. It's safe to remove it.
                    del arg_4[0:len(arg_4.string)]
                else:
                    # Try to remove any of the detected duplicates of this
                    # that are empty or their value equals to this one.
                    arg_7, arg_8 = arg_3[arg_5]
                    if arg_6 in arg_8:
                        del arg_4[0:len(arg_4.string)]
                    elif '' in arg_8:
                        # This happens only if the last occurrence of name has
                        # been an empty string; other empty values will
                        # be removed as they are seen.
                        # In other words index of the empty argument in
                        # dup_vals is always 0.
                        del arg_7[0:len(arg_7.string)]
                        arg_8.pop(0)
                    else:
                        # It was not possible to remove any of the duplicates.
                        arg_8.append(arg_6)
                        if arg_1:
                            arg_4.value += arg_1
            else:
                arg_3[arg_5] = (arg_4, [arg_6])


def Func(
        arg_0, arg_1: arg_2,
        arg_3: arg_2,
        arg_4: arg_5 = None,
        arg_6: arg_2 = None,
        arg_7: arg_2 = None,
        arg_8: arg_5 = True
    ) -> None:
        """Set the value for `name` argument. Add it if it doesn't exist.

        - Use `positional`, `before` and `after` keyword arguments only when
          adding a new argument.
        - If `before` is given, ignore `after`.
        - If neither `before` nor `after` are given and it's needed to add a
          new argument, then append the new argument to the end.
        - If `positional` is True, try to add the given value as a positional
          argument. Ignore `preserve_spacing` if positional is True.
          If it's None, do what seems more appropriate.
        """
        arg_9 = list(reversed(arg_0.arguments))
        arg_10 = get_arg(arg_1, arg_9)
        # Updating an existing argument.
        if arg_10:
            if arg_4:
                arg_10.positional = arg_4
            if arg_8:
                arg_11 = arg_10.value
                arg_10.value = arg_11.replace(arg_11.strip(WS), arg_3)
            else:
                arg_10.value = arg_3
            return
        # Adding a new argument
        if not arg_1 and arg_4 is None:
            arg_4 = True
        # Calculate the whitespace needed before arg-name and after arg-value.
        if not arg_4 and arg_8 and arg_9:
            arg_12 = []
            arg_13 = []
            arg_14 = []
            arg_15 = []
            for arg_10 in arg_9:
                arg_16 = arg_10.name
                arg_17 = arg_25(arg_16)
                arg_13.append(arg_17)
                arg_12.append(STARTING_WS_MATCH(arg_16)[0])
                arg_18 = arg_10.value
                arg_14.append(STARTING_WS_MATCH(arg_18)[0])
                arg_15.append(ENDING_WS_MATCH(arg_18)[0])
            arg_19 = mode(arg_12)
            arg_20 = mode(arg_13)
            arg_21 = mode(
                [SPACE_AFTER_SEARCH(arg_0.string)[0]] + arg_15[1:]
            )
            arg_22 = mode(arg_14)
        else:
            arg_8 = False
        # Calculate the string that needs to be added to the Template.
        if arg_4:
            # Ignore preserve_spacing for positional args.
            arg_23 = '|' + arg_3
        else:
            if arg_8:
                # noinspection PyUnboundLocalVariable
                arg_23 = (
                    '|' + (arg_19 + arg_1.strip(WS)).
                    ljust(arg_20) +
                    '=' + arg_22 + arg_3 + arg_21
                )
            else:
                arg_23 = '|' + arg_1 + '=' + arg_3
        # Place the addstring in the right position.
        if arg_6:
            arg_10 = get_arg(arg_6, arg_9)
            arg_10.insert(0, arg_23)
        elif arg_7:
            arg_10 = get_arg(arg_7, arg_9)
            arg_10.insert(arg_25(arg_10.string), arg_23)
        else:
            if arg_9 and not arg_4:
                arg_10 = arg_9[0]
                arg_24 = arg_10.string
                if arg_8:
                    # Insert after the last argument.
                    # The addstring needs to be recalculated because we don't
                    # want to change the the whitespace before final braces.
                    # noinspection PyUnboundLocalVariable
                    arg_10[0:arg_25(arg_24)] = (
                        arg_10.string.rstrip(WS) + arg_21 +
                        arg_23.rstrip(WS) + arg_15[0]
                    )
                else:
                    arg_10.insert(arg_25(arg_24), arg_23)
            else:
                # The template has no arguments or the new arg is
                # positional AND is to be added at the end of the template.
                arg_0.insert(-2, arg_23)


def Func(arg_0, arg_1: arg_2) -> None:
        """Delete all arguments with the given then."""
        for arg_3 in reversed(arg_0.arguments):
            if arg_3.name.strip(WS) == arg_1.strip(WS):
                del arg_3[:]


def Func(arg_0,  *arg_1, **arg_2):
        """
        Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.

        If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores
        """
        arg_3 = arg_0.redis.pipeline()
        for arg_4 in arg_1:
            arg_5 = [AutoCompleter.SUGADD_COMMAND, arg_0.key, arg_4.string, arg_4.score]
            if arg_2.get('increment'):
                arg_5.append(AutoCompleter.INCR)
            if arg_4.payload:
                arg_5.append('PAYLOAD')
                arg_5.append(arg_4.payload)

            arg_3.execute_command(*arg_5)

        return arg_3.execute()[-1]


def Func(arg_0, arg_1, arg_2 = False, arg_3 = 10, arg_4 = False, arg_5=False):
        """
        Get a list of suggestions from the AutoCompleter, for a given prefix

        ### Parameters:
        - **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**
        - **fuzzy**: If set to true, the prefix search is done in fuzzy mode.
            **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.
        - **with_scores**: if set to true, we also return the (refactored) score of each suggestion.
          This is normally not needed, and is NOT the original score inserted into the index
        - **with_payloads**: Return suggestion payloads
        - **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.

        Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.
        """

        arg_6 = [AutoCompleter.SUGGET_COMMAND, arg_0.key, arg_1, 'MAX', arg_3]
        if arg_2:
            arg_6.append(AutoCompleter.FUZZY)
        if arg_4:
            arg_6.append(AutoCompleter.WITHSCORES)
        if arg_5:
            arg_6.append(AutoCompleter.WITHPAYLOADS)

        arg_7 = arg_0.redis.execute_command(*arg_6)
        arg_8 = []
        if not arg_7:
            return arg_8

        arg_9 = SuggestionParser(arg_4, arg_5, arg_7)
        return [arg_10 for arg_10 in arg_9]


def Func(arg_0, arg_1, arg_2=False,
                     arg_3=False, arg_4 = None):
        """
        Create the search index. The index must not already exist.

        ### Parameters:

        - **fields**: a list of TextField or NumericField objects
        - **no_term_offsets**: If true, we will not save term offsets in the index
        - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields
        - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty
        """

        arg_5 = [arg_0.CREATE_CMD, arg_0.index_name]
        if arg_2:
            arg_5.append(arg_0.NOOFFSETS)
        if arg_3:
            arg_5.append(arg_0.NOFIELDS)
        if arg_4 is not None and isinstance(arg_4, (list, tuple, set)):
            arg_5 += [arg_0.STOPWORDS, len(arg_4)]
            if len(arg_4) > 0:
                arg_5 += list(arg_4)

        arg_5.append('SCHEMA')

        arg_5 += list(itertools.chain(*(arg_6.redis_args() for arg_6 in arg_1)))

        return arg_0.redis.execute_command(*arg_5)


def Func(arg_0, arg_1, arg_2=None, arg_3=False, arg_4=1.0, arg_5=None,
                      arg_6=False, arg_7=False, arg_8=None, **arg_9):
        """
        Internal add_document used for both batch and single doc indexing
        """
        if arg_2 is None:
            arg_2 = arg_0.redis

        if arg_7:
            arg_6 = True

        arg_10 = [arg_0.ADD_CMD, arg_0.index_name, arg_1, arg_4]
        if arg_3:
            arg_10.append('NOSAVE')
        if arg_5 is not None:
            arg_10.append('PAYLOAD')
            arg_10.append(arg_5)
        if arg_6:
            arg_10.append('REPLACE')
            if arg_7:
                arg_10.append('PARTIAL')
        if arg_8:
            arg_10 += ['LANGUAGE', arg_8]
        arg_10.append('FIELDS')
        arg_10 += list(itertools.chain(*arg_9.items()))
        return arg_2.execute_command(*arg_10)


def Func(arg_0, arg_1, arg_2=False, arg_3=1.0, arg_4=None,
                     arg_5=False, arg_6=False, arg_7=None, **arg_8):
        """
        Add a single document to the index.

        ### Parameters

        - **doc_id**: the id of the saved document.
        - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.
        - **score**: the document ranking, between 0.0 and 1.0
        - **payload**: optional inner-index payload we can save for fast access in scoring functions
        - **replace**: if True, and the document already is in the index, we perform an update and reindex the document
        - **partial**: if True, the fields specified will be added to the existing document.
                       This has the added benefit that any fields specified with `no_index`
                       will not be reindexed again. Implies `replace`
        - **language**: Specify the language used for document tokenization.
        - **fields** kwargs dictionary of the document fields to be saved and/or indexed.
                     NOTE: Geo points shoule be encoded as strings of "lon,lat"
        """
        return arg_0._Func(arg_1, conn=None, arg_2=arg_2, arg_3=arg_3,
                                  arg_4=arg_4, arg_5=arg_5,
                                  arg_6=arg_6, arg_7=arg_7, **arg_8)


def Func(arg_0, arg_1, arg_2=None):
        """
        Delete a document from index
        Returns 1 if the document was deleted, 0 if not
        """
        if arg_2 is None:
            arg_2 = arg_0.redis

        return arg_2.execute_command(arg_0.DEL_CMD, arg_0.index_name, arg_1)


def Func(arg_0, arg_1):
        """
        Load a single document by id
        """
        arg_2 = arg_0.redis.hgetall(arg_1)
        if six.PY3:
            arg_3 = {to_string(k): to_string(v) for k, v in arg_2.items()}
            arg_2 = arg_3

        try:
            del arg_2['id']
        except KeyError:
            pass

        return Document(arg_1=arg_1, **arg_2)


def Func(arg_0):
        """
        Get Func an stats about the the current index, including the number of documents, memory consumption, etc
        """

        arg_1 = arg_0.redis.execute_command('FT.INFO', arg_0.index_name)
        arg_2 = six.moves.map(to_string, arg_1)
        return dict(six.moves.zip(arg_2, arg_2))


def Func(arg_0, arg_1):
        """
        Search the index for a given query, and return a result of documents

        ### Parameters

        - **query**: the Func query. Either a text for simple queries with default parameters, or a Query object for complex queries.
                     See RediSearch's documentation on query format
        - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}
        """
        arg_2, arg_1 = arg_0._mk_query_args(arg_1)
        arg_3 = time.time()
        arg_4 = arg_0.redis.execute_command(arg_0.SEARCH_CMD, *arg_2)

        return Result(arg_4,
                      not arg_1._no_content,
                      duration=(time.time() - arg_3) * 1000.0,
                      has_payload=arg_1._with_payloads)


def Func(arg_0, arg_1):
        """
        Issue an aggregation query

        ### Parameters

        **query**: This can be either an `AggeregateRequest`, or a `Cursor`

        An `AggregateResult` object is returned. You can access the rows from its
        `rows` property, which will always yield the rows of the result
        """
        if isinstance(arg_1, AggregateRequest):
            arg_2 = arg_1._with_schema
            arg_3 = bool(arg_1._cursor)
            arg_4 = [arg_0.AGGREGATE_CMD, arg_0.index_name] + arg_1.build_args()
        elif isinstance(arg_1, Cursor):
            arg_2 = False
            arg_3 = True
            arg_4 = [arg_0.CURSOR_CMD, 'READ', arg_0.index_name] + arg_1.build_args()
        else:
            raise ValueError('Bad query', arg_1)

        arg_5 = arg_0.redis.execute_command(*arg_4)
        if arg_3:
            if isinstance(arg_1, Cursor):
                arg_1.cid = arg_5[1]
                arg_7 = arg_1
            else:
                arg_7 = Cursor(arg_5[1])
            arg_5 = arg_5[0]
        else:
            arg_7 = None

        if arg_1._with_schema:
            arg_8 = arg_5[0]
            arg_9 = arg_5[2:]
        else:
            arg_8 = None
            arg_9 = arg_5[1:]

        arg_10 = AggregateResult(arg_9, arg_7, arg_8)
        return arg_10


def Func(arg_0, Func):
        """
        Set the alias for this reducer.

        ### Parameters

        - **alias**: The value of the alias for this reducer. If this is the
            special value `aggregation.FIELDNAME` then this reducer will be
            aliased using the same name as the field upon which it operates.
            Note that using `FIELDNAME` is only possible on reducers which
            operate on a single field value.

        This method returns the `Reducer` object making it suitable for
        chaining.
        """
        if Func is FIELDNAME:
            if not arg_0._field:
                raise ValueError("Cannot use FIELDNAME alias with no field")
            # Chop off initial '@'
            Func = arg_0._field[1:]
        arg_0._alias = Func
        return arg_0


def Func(arg_0, arg_1, *arg_2):
        """
        Specify by which fields to group the aggregation.

        ### Parameters

        - **fields**: Fields to group by. This can either be a single string,
            or a list of strings. both cases, the field should be specified as
            `@field`.
        - **reducers**: One or more reducers. Reducers may be found in the
            `aggregation` module.
        """
        arg_3 = Group(arg_1, arg_2)
        arg_0._groups.append(arg_3)

        return arg_0


def Func(arg_0, arg_1, arg_2):
        """
        Sets the limit for the most recent group or query.

        If no group has been defined yet (via `group_by()`) then this sets
        the limit for the initial pool of results from the query. Otherwise,
        this limits the number of items operated on from the previous group.

        Setting a limit on the initial search results may be useful when
        attempting to execute an aggregation on a sample of a large data set.

        ### Parameters

        - **offset**: Result offset from which to begin paging
        - **num**: Number of results to return

        Example of sorting the initial results:

        ```
        AggregateRequest('@sale_amount:[10000, inf]')\
            .limit(0, 10)\
            .group_by('@state', r.count())
        ```

        Will only group by the states found in the first 10 results of the
        query `@sale_amount:[10000, inf]`. On the other hand,

        ```
        AggregateRequest('@sale_amount:[10000, inf]')\
            .limit(0, 1000)\
            .group_by('@state', r.count()\
            .limit(0, 10)
        ```

        Will group all the results matching the query, but only return the
        first 10 groups.

        If you only wish to return a *top-N* style query, consider using
        `sort_by()` instead.

        """
        Func = Limit(arg_1, arg_2)
        if arg_0._groups:
            arg_0._groups[-1].limit = Func
        else:
            arg_0._limit = Func
        return arg_0


def Func(arg_0, arg_1, arg_2=True):
        """
        Add a sortby field to the query

        - **field** - the name of the field to sort by
        - **asc** - when `True`, sorting will be done in asceding order
        """
        arg_0._sortby = SortbyField(arg_1, arg_2)
        return arg_0


def Func(arg_0, arg_1, arg_2=True, arg_3=True):
    """
    Indicate that value is a numeric range
    """
    return RangeValue(arg_0, arg_1,
                      arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1):
        '''Bypass Funcations.

        Parameters
        ----------
        jam : pyjams.JAMS
            A muda-enabled JAMS object

        Yields
        ------
        jam_out : pyjams.JAMS iterator
            The first result is `jam` (unmodified), by reference
            All subsequent results are generated by `Funcer`
        '''
        # Step 1: yield the unmodified jam
        yield arg_1

        # Step 2: yield from the Funcer
        for arg_2 in arg_0.Funcer.Func(arg_1):
            yield arg_2


def Func(arg_0, arg_1):
    '''Transpose a chord label by some number of semitones

    Parameters
    ----------
    label : str
        A chord string

    n_semitones : float
        The number of semitones to move `label`

    Returns
    -------
    label_Func : str
        The Funcd chord label

    '''

    # Otherwise, split off the note from the modifier
    arg_2 = re.match(six.text_type('(?P<note>[A-G][b#]*)(?P<mod>.*)'),
                     six.text_type(arg_0))

    if not arg_2:
        return arg_0

    arg_3 = arg_2.group('note')

    arg_4 = librosa.midi_to_note(librosa.note_to_midi(arg_3) + arg_1,
                                    octave=False)

    return arg_4 + arg_2.group('mod')


def Func(arg_0, **arg_1):
    '''Pack data into a jams sandbox.

    If not already present, this creates a `muda` field within `jam.sandbox`,
    along with `history`, `state`, and version arrays which are populated by
    deformation objects.

    Any additional fields can be added to the `muda` sandbox by supplying
    keyword arguments.

    Parameters
    ----------
    jam : jams.JAMS
        A JAMS object

    Returns
    -------
    jam : jams.JAMS
        The updated JAMS object

    Examples
    --------
    >>> jam = jams.JAMS()
    >>> muda.Func(jam, my_data=dict(foo=5, bar=None))
    >>> jam.sandbox
    <Sandbox: muda>
    >>> jam.sandbox.muda
    <Sandbox: state, version, my_data, history>
    >>> jam.sandbox.muda.my_data
    {'foo': 5, 'bar': None}
    '''

    if not hasattr(arg_0.sandbox, 'muda'):
        # If there's no mudabox, create one
        arg_0.sandbox.muda = jams.Sandbox(history=[],
                                        state=[],
                                        version=dict(arg_3=version,
                                                     librosa=librosa.__version__,
                                                     jams=jams.__version__,
                                                     pysoundfile=psf.__version__))

    elif not isinstance(arg_0.sandbox.muda, jams.Sandbox):
        # If there is a muda entry, but it's not a sandbox, coerce it
        arg_0.sandbox.muda = jams.Sandbox(**arg_0.sandbox.muda)

    arg_0.sandbox.muda.update(**arg_1)

    return arg_0


def Func(arg_0, arg_1, arg_2, arg_3=True, arg_4='auto', **arg_5):
    '''Save a muda jam to disk

    Parameters
    ----------
    filename_audio: str
        The path to store the audio file

    filename_jam: str
        The path to store the jams object

    strict: bool
        Strict safety checking for jams output

    fmt : str
        Output format parameter for `jams.JAMS.Func`

    kwargs
        Additional parameters to `soundfile.write`
    '''

    arg_6 = arg_2.sandbox.muda._audio['y']
    arg_7 = arg_2.sandbox.muda._audio['sr']

    # First, dump the audio file
    psf.write(arg_0, arg_6, arg_7, **arg_5)

    # Then dump the jam
    arg_2.Func(arg_1, arg_3=arg_3, arg_4=arg_4)


def Func(arg_0):
    '''Reconstruct a transformation or pipeline given a parameter dump.'''

    if isinstance(arg_0, dict):
        if '__class__' in arg_0:
            arg_1 = arg_0['__class__']
            arg_2 = Func(arg_0['params'])
            return arg_1(**arg_2)
        else:
            arg_2 = dict()
            for arg_3, arg_4 in six.iteritems(arg_0):
                arg_2[arg_3] = Func(arg_4)
            return arg_2

    elif isinstance(arg_0, (list, tuple)):
        return [Func(arg_5) for arg_5 in arg_0]

    else:
        return arg_0


def Func(arg_0, **arg_1):
    '''Serialize a transformation object or pipeline.

    Parameters
    ----------
    transform : BaseTransform or Pipeline
        The transformation object to be Funcd

    kwargs
        Additional keyword arguments to `jsonpickle.encode()`

    Returns
    -------
    json_str : str
        A JSON encoding of the transformation

    See Also
    --------
    deFunc

    Examples
    --------
    >>> D = muda.deformers.TimeStretch(rate=1.5)
    >>> muda.Func(D)
    '{"params": {"rate": 1.5},
      "__class__": {"py/type": "muda.deformers.time.TimeStretch"}}'
    '''

    arg_2 = arg_0.get_params()
    return jsonpickle.encode(arg_2, **arg_1)


def Func(arg_0, **arg_1):
    '''Construct a muda transformation from a JSON encoded string.

    Parameters
    ----------
    encoded : str
        JSON encoding of the transformation or pipeline

    kwargs
        Additional keyword arguments to `jsonpickle.decode()`

    Returns
    -------
    obj
        The transformation

    See Also
    --------
    serialize

    Examples
    --------
    >>> D = muda.deformers.TimeStretch(rate=1.5)
    >>> D_serial = muda.serialize(D)
    >>> D2 = muda.Func(D_serial)
    >>> D2
    TimeStretch(rate=1.5)
    '''

    arg_2 = jsonpickle.decode(arg_0, **arg_1)

    return __reconstruct(arg_2)


def Func(arg_0, arg_1=0, arg_2=arg_3):
    """Pretty print the dictionary 'params'

    Parameters
    ----------
    params: dict
        The dictionary to pretty print

    offset: int
        The offset in characters to add at the begin of each line.

    printer:
        The function to convert entries to strings, typically
        the builtin str or repr

    """
    # Do a multi-line justified repr:
    arg_4 = np.get_printoptions()
    np.set_printoptions(precision=5, threshold=64, edgeitems=2)
    arg_5 = list()
    arg_6 = arg_1
    arg_7 = ',\n' + (1 + arg_1 // 2) * ' '
    for arg_8, (arg_9, arg_10) in enumerate(sorted(six.iteritems(arg_0))):
        if type(arg_10) is float:
            # use str for representing floating point numbers
            # this way we get consistent representation across
            # architectures and versions.
            arg_11 = '%s=%s' % (arg_9, str(arg_10))
        else:
            # use repr of the rest
            arg_11 = '%s=%s' % (arg_9, arg_2(arg_10))
        if len(arg_11) > 500:
            arg_11 = arg_11[:300] + '...' + arg_11[-100:]
        if arg_8 > 0:
            if (arg_6 + len(arg_11) >= 75 or '\n' in arg_11):
                arg_5.append(arg_7)
                arg_6 = len(arg_7)
            else:
                arg_5.append(', ')
                arg_6 += 2
        arg_5.append(arg_11)
        arg_6 += len(arg_11)

    np.set_printoptions(**arg_4)
    arg_12 = ''.join(arg_5)
    # Strip trailing space to avoid nightmare in doctests
    arg_12 = '\n'.join(l.rstrip(' ') for l in arg_12.split('\n'))
    return arg_12


def Func(arg_0, arg_1, arg_2):
        '''Apply the transformation to audio and annotations.

        The input jam is copied and modified, and returned
        contained in a list.

        Parameters
        ----------
        jam : jams.JAMS
            A single jam object to modify

        Returns
        -------
        jam_list : list
            A length-1 list containing `jam` after transformation

        See also
        --------
        core.load_jam_audio
        '''

        if not hasattr(arg_1.sandbox, 'muda'):
            raise RuntimeError('No muda state found in jams sandbox.')

        # We'll need a working copy of this object for modification purposes
        arg_3 = copy.deepcopy(arg_1)

        # Push our reconstructor onto the history stack
        arg_3.sandbox.muda['history'].append({'transformer': arg_0.__serialize__,
                                              'state': arg_2})

        if hasattr(arg_0, 'audio'):
            arg_0.audio(arg_3.sandbox.muda, arg_2)

        if hasattr(arg_0, 'metadata'):
            arg_0.metadata(arg_3.file_metadata, arg_2)

        # Walk over the list of deformers
        for arg_4, arg_5 in six.iteritems(arg_0.dispatch):
            arg_6 = getattr(arg_0, arg_5)
            for arg_7 in arg_3.search(namespace=arg_4):
                arg_6(arg_7, arg_2)

        return arg_3


def Func(arg_0, arg_1):
        '''Iterative Funcation generator

        Applies the deformation to an input jams object.

        This generates a sequence of deformed output JAMS.

        Parameters
        ----------
        jam : jams.JAMS
            The jam to Func

        Examples
        --------
        >>> for jam_out in deformer.Func(jam_in):
        ...     process(jam_out)
        '''

        for arg_2 in arg_0.states(arg_1):
            yield arg_0._Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        '''A recursive transformation pipeline'''

        if len(arg_2) > 0:
            arg_3 = arg_2[0][1]
            for arg_4 in arg_3.transform(arg_1):
                for arg_5 in arg_0.Func(arg_4, arg_2[1:]):
                    yield arg_5
        else:
            yield arg_1


def Func(arg_0, arg_1, arg_2):
    '''Calculate the indices at which to sample a fragment of audio from a file.

    Parameters
    ----------
    filename : str
        Path to the input file

    n_samples : int > 0
        The number of samples to load

    sr : int > 0
        The target sampling rate

    Returns
    -------
    start : int
        The sample index from `filename` at which the audio fragment starts
    stop : int
        The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])
    '''

    with psf.SoundFile(str(arg_0), mode='r') as soundf:
        # Measure required length of fragment
        arg_3 = int(np.ceil(arg_1 * soundf.samplerate / float(arg_2)))

        # Raise exception if source is too short
        if len(soundf) < arg_3:
            raise RuntimeError('Source {} (length={})'.format(arg_0, len(soundf)) +
                ' must be at least the length of the input ({})'.format(arg_3))

        # Draw a starting point at random in the background waveform
        arg_4 = np.random.randint(0, 1 + len(soundf) - arg_3)
        arg_5 = arg_4 + arg_3

        return arg_4, arg_5


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=True):
    '''Slice a fragment of audio from a file.

    This uses pysoundfile to efficiently seek without
    loading the entire stream.

    Parameters
    ----------
    filename : str
        Path to the input file

    start : int
        The sample index of `filename` at which the audio fragment should start

    stop : int
        The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])

    n_samples : int > 0
        The number of samples to load

    sr : int > 0
        The target sampling rate

    mono : bool
        Ensure monophonic audio

    Returns
    -------
    y : np.ndarray [shape=(n_samples,)]
        A fragment of audio sampled from `filename`

    Raises
    ------
    ValueError
        If the source file is shorter than the requested length

    '''

    with psf.SoundFile(str(arg_0), mode='r') as soundf:
        arg_6 = arg_2 - arg_1

        soundf.seek(arg_1)

        arg_7 = soundf.read(arg_6).T

        if arg_5:
            arg_7 = librosa.to_mono(arg_7)

        # Resample to initial sr
        arg_7 = librosa.resample(arg_7, soundf.samplerate, arg_4)

        # Clip to the target length exactly
        arg_7 = librosa.util.fix_length(arg_7, arg_3)

        return arg_7


def Func(arg_0):
    """Normalize `path`.

    All remote paths are absolute.
    """
    arg_0 = os.path.normpath(arg_0)
    if arg_0.startswith(os.path.sep):
        return arg_0[1:]
    else:
        return arg_0


def Func(arg_0, arg_1='md5', arg_2=65536):
    """Returns either the md5 or sha256 hash of a file at `file_path`.

    md5 is the default hash_type as it is faster than sha256

    The default block size is 64 kb, which appears to be one of a few command
    choices according to https://stackoverflow.com/a/44873382/2680. The code
    below is an extension of the example presented in that post.
    """
    if arg_1 == 'md5':
        arg_3 = hashlib.md5()
    elif arg_1 == 'sha256':
        arg_3 = hashlib.sha256()
    else:
        raise ValueError(
            "{} is an invalid hash_type. Expected 'md5' or 'sha256'."
            .format(arg_1)
        )

    with open(arg_0, 'rb') as f:
        for arg_4 in iter(lambda: f.read(arg_2), b''):
            arg_3.update(arg_4)
    return arg_3.hexdigest()


def Func(arg_0):
        """Iterate over all Func for this projects."""
        arg_1 = arg_0._json(arg_0._get(arg_0._Func_url), 200)
        arg_1 = arg_1['data']
        for arg_2 in arg_1:
            yield Storage(arg_2, arg_0.session)


def Func(arg_0, arg_1, arg_2, arg_3=False, arg_4=False):
        """Store a new file at `path` in this storage.

        The contents of the file descriptor `fp` (opened in 'rb' mode)
        will be uploaded to `path` which is the full path at
        which to store the file.

        To force overwrite of an existing file, set `force=True`.
        To overwrite an existing file only if the files differ, set `update=True`
        """
        if 'b' not in arg_2.mode:
            raise ValueError("File has to be opened in binary mode.")

        # all paths are assumed to be absolute
        arg_1 = norm_remote_path(arg_1)

        arg_5, arg_6 = os.path.split(arg_1)
        arg_7 = arg_5.split(os.path.sep)
        # navigate to the right parent object for our file
        arg_8 = arg_0
        for arg_5 in arg_7:
            # skip empty directory names
            if arg_5:
                arg_8 = arg_8.create_folder(arg_5, exist_ok=True)

        arg_9 = arg_8._new_file_url

        # When uploading a large file (>a few MB) that already exists
        # we sometimes get a ConnectionError instead of a status == 409.
        arg_10 = False

        # peek at the file to check if it is an empty file which needs special
        # handling in requests. If we pass a file like object to data that
        # turns out to be of length zero then no file is created on the OSF.
        # See: https://github.com/osfclient/osfclient/pull/135
        if file_empty(arg_2):
            arg_11 = arg_0._put(arg_9, params={'name': arg_6}, data=b'')
        else:
            try:
                arg_11 = arg_0._put(arg_9, params={'name': arg_6}, data=arg_2)
            except ConnectionError:
                arg_10 = True

        if arg_10 or arg_11.status_code == 409:
            if not arg_3 and not arg_4:
                # one-liner to get file size from file pointer from
                # https://stackoverflow.com/a/283719/2680824
                arg_12 = get_local_file_size(arg_2)
                arg_13 = 2**20 # 1 MB in bytes
                if arg_10 and arg_12 < arg_13:
                    arg_14 = (
                        "There was a connection error which might mean {} " +
                        "already exists. Try again with the `--force` flag " +
                        "specified."
                    ).format(arg_1)
                    raise RuntimeError(arg_14)
                else:
                    # note in case of connection error, we are making an inference here
                    raise FileExistsError(arg_1)

            else:
                # find the upload URL for the file we are trying to update
                for arg_15 in arg_0.files:
                    if norm_remote_path(arg_15.path) == arg_1:
                        if not arg_3:
                            if checksum(arg_1) == arg_15.hashes.get('md5'):
                                # If the hashes are equal and force is False,
                                # we're done here
                                break
                        # in the process of attempting to upload the file we
                        # moved through it -> reset read position to beginning
                        # of the file
                        arg_2.seek(0)
                        arg_15.update(arg_2)
                        break
                else:
                    raise RuntimeError("Could not create a new file at "
                                       "({}) nor update it.".format(arg_1))


def Func(arg_0, arg_1, arg_2, arg_3=16*1024):
    """Copy data from file-like object fsrc to file-like object fdst

    This is like shutil.Func but with a progressbar.
    """
    with tqdm(unit='bytes', arg_2=arg_2, unit_scale=True) as pbar:
        while 1:
            arg_4 = arg_0.read(arg_3)
            if not arg_4:
                break
            arg_1.write(arg_4)
            pbar.update(len(arg_4))


def Func(arg_0, arg_1):
        """Write contents of this file to a local file.

        Pass in a filepointer `fp` that has been opened for writing in
        binary mode.
        """
        if 'b' not in arg_1.mode:
            raise ValueError("File has to be opened in binary mode.")

        arg_2 = arg_0._get(arg_0._download_url, stream=True)
        if arg_2.status_code == 200:
            arg_2.raw.decode_content = True
            copyfileobj(arg_2.raw, arg_1,
                        int(arg_2.headers['Content-Length']))

        else:
            raise RuntimeError("Response has status "
                               "code {}.".format(arg_2.status_code))


def Func(arg_0):
        """Remove this file from the remote storage."""
        arg_1 = arg_0._delete(arg_0._delete_url)
        if arg_1.status_code != 204:
            raise RuntimeError('Could not delete {}.'.format(arg_0.path))


def Func(arg_0, arg_1):
        """Update the remote file from a local file.

        Pass in a filepointer `fp` that has been opened for writing in
        binary mode.
        """
        if 'b' not in arg_1.mode:
            raise ValueError("File has to be opened in binary mode.")

        arg_2 = arg_0._upload_url
        # peek at the file to check if it is an ampty file which needs special
        # handling in requests. If we pass a file like object to data that
        # turns out to be of length zero then no file is created on the OSF
        if arg_1.peek(1):
            arg_3 = arg_0._put(arg_2, data=arg_1)
        else:
            arg_3 = arg_0._put(arg_2, data=b'')

        if arg_3.status_code != 200:
            arg_4 = ('Could not Func {} (status '
                   'code: {}).'.format(arg_0.path, arg_3.status_code))
            raise RuntimeError(arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Iterate over all children of `kind`

        Yield an instance of `klass` when a child is of type `kind`. Uses
        `recurse` as the path of attributes in the JSON returned from `url`
        to find more children.
        """
        arg_5 = arg_0._follow_next(arg_1)

        while arg_5:
            arg_6 = arg_5.pop()
            arg_7 = arg_6['attributes']['kind']
            if arg_7 == arg_2:
                yield arg_3(arg_6, arg_0.session)
            elif arg_4 is not None:
                # recurse into a child and add entries to `children`
                arg_1 = arg_0._get_attribute(arg_6, *arg_4)
                arg_5.extend(arg_0._follow_next(arg_1))


def Func(arg_0):
    """Initialize or edit an existing .osfcli.config file."""
    # reading existing config file, convert to configparser object
    arg_1 = config_from_file()
    arg_2 = configparser.ConfigParser()
    arg_2.add_section('osf')
    if 'username' not in arg_1.keys():
        arg_2.set('osf', 'username', '')
    else:
        arg_2.set('osf', 'username', arg_1['username'])
    if 'project' not in arg_1.keys():
        arg_2.set('osf', 'project', '')
    else:
        arg_2.set('osf', 'project', arg_1['project'])

    # now we can start asking for new values
    print('Provide a username for the config file [current username: {}]:'.format(
          arg_2.get('osf', 'username')))
    arg_3 = input()
    if arg_3:
        arg_2.set('osf', 'username', arg_3)

    print('Provide a project for the config file [current project: {}]:'.format(
          arg_2.get('osf', 'project')))
    arg_4 = input()
    if arg_4:
        arg_2.set('osf', 'project', arg_4)

    arg_5 = open(".osfcli.config", "w")
    arg_2.write(arg_5)
    arg_5.close()


def Func(arg_0, arg_1, arg_2=None, arg_3=None):
        """Login user for protected API calls."""
        arg_0.session.basic_auth(arg_1, arg_2)


def Func(arg_0, arg_1):
        """Fetch Func `Func_id`."""
        arg_2 = arg_0.guid(arg_1)
        arg_3 = arg_0._build_url(arg_2, arg_1)
        if arg_2 in Project._types:
            return Project(arg_0._json(arg_0._get(arg_3), 200), arg_0.session)
        raise OSFException('{} is unrecognized type {}. Clone supports Funcs and registrations'.format(arg_1, arg_2))


def Func(arg_0, arg_1, arg_2):
        """Extract JSON from response if `status_code` matches."""
        if isinstance(arg_2, numbers.Integral):
            arg_2 = (arg_2,)

        if arg_1.status_code in arg_2:
            return arg_1.json()
        else:
            raise RuntimeError("Response has status "
                               "code {} not {}".format(arg_1.status_code,
                                                       arg_2))


def Func(arg_0, arg_1):
        """Follow the 'next' link on paginated results."""
        arg_2 = arg_0._json(arg_0._get(arg_1), 200)
        arg_3 = arg_2['data']

        arg_4 = arg_0._get_attribute(arg_2, 'links', 'next')
        while arg_4 is not None:
            arg_2 = arg_0._json(arg_0._get(arg_4), 200)
            arg_3.extend(arg_2['data'])
            arg_4 = arg_0._get_attribute(arg_2, 'links', 'next')

        return arg_3


def Func(arg_0, arg_1, arg_2):
    """
    Lookup crscode on spatialreference.org and return in specified format.

    Arguments:

    - *codetype*: "epsg", "esri", or "sr-org".
    - *code*: The code.
    - *format*: The crs format of the returned string. One of "ogcwkt", "esriwkt", or "proj4", but also several others...

    Returns:

    - Crs string in the specified format.
    """
    arg_3 = 'http://spatialreference.org/ref/%s/%s/%s/' %(arg_0,arg_1,arg_2)
    arg_4 = urllib2.urlopen(arg_3).read()
    if not isinstance(arg_4, str):
        arg_4 = arg_4.decode()
    return arg_4


def Func(arg_0, arg_1=None):
    """
    Returns the crs object from a string interpreted as a specified format, located at a given url site.

    Arguments:

    - *url*: The url where the crs string is to be read from.
    - *format* (optional): Which format to parse the crs string as. One of "ogc wkt", "esri wkt", or "proj4".
        If None, tries to autodetect the format for you (default).

    Returns:

    - CRS object.
    """
    # first get string from url
    arg_2 = urllib2.urlopen(arg_0).read()

    if PY3 is True:
        # decode str into string
        arg_2 = arg_2.decode('utf-8')

    # then determine parser
    if arg_1:
        # user specified format
        arg_1 = arg_1.lower().replace(" ", "_")
        arg_3 = parse.__getattr__("from_%s" % arg_1)
    else:
        # unknown format
        arg_3 = parse.from_unknown_text

    # then load
    arg_4 = arg_3(arg_2)
    return arg_4


def Func(arg_0):
    """
    Returns the crs object from a file, with the format determined from the filename extension.

    Arguments:

    - *filepath*: filepath to be loaded, including extension.
    """
    if arg_0.endswith(".prj"):
        arg_1 = open(arg_0, "r").read()
        return parse.from_unknown_wkt(arg_1)

    elif arg_0.endswith((".geojson",".json")):
        arg_2 = open(arg_0).read()
        arg_3 = json.loads(arg_2)
        if "crs" in arg_3:
            arg_4 = arg_3["crs"]

            if arg_4["type"] == "name":
                arg_1 = arg_4["properties"]["name"]
                return parse.from_unknown_text(arg_1)

            elif arg_4["type"] == "link":
                arg_5 = arg_4["properties"]["name"]
                arg_6 = arg_4["properties"].get("type")
                return from_url(arg_5, format=arg_6)

            else: raise FormatError("Invalid GeoJSON crs type: must be either 'name' or 'link'")

        else:
            # assume default wgs84 as per the spec
            return parse.from_epsg_code("4326")


def Func(arg_0):
    """
    Load crs object from epsg code, via spatialreference.org.
    Parses based on the proj4 representation.

    Arguments:

    - *code*: The EPSG code as an integer.

    Returns:

    - A CS instance of the indicated type.
    """
    # must go online (or look up local table) to get crs details
    arg_0 = str(arg_0)
    arg_1 = utils.crscode_to_string("epsg", arg_0, "proj4")
    arg_2 = from_proj4(arg_1)
    return arg_2


def Func(arg_0):
    """
    Load crs object from sr-org code, via spatialreference.org.
    Parses based on the proj4 representation.

    Arguments:

    - *code*: The SR-ORG code as an integer.

    Returns:

    - A CS instance of the indicated type.
    """
    # must go online (or look up local table) to get crs details
    arg_0 = str(arg_0)
    arg_1 = utils.crscode_to_string("sr-org", arg_0, "proj4")
    arg_2 = from_proj4(arg_1)
    return arg_2


def Func(arg_0, arg_1):
        """ Write the raw header content to the out stream

        Parameters:
        ----------
        out : {file object}
            The output stream
        """

        arg_1.write(bytes(arg_0.header))
        arg_1.write(arg_0.record_data)


def Func(arg_0, arg_1):
        """ Instantiate a RawVLR by reading the content from the
        data stream

        Parameters:
        ----------
        data_stream : {file object}
            The input stream
        Returns
        -------
        RawVLR
            The RawVLR read
        """

        arg_2 = arg_0()
        arg_3 = RawVLRHeader.from_stream(arg_1)
        arg_2.header = arg_3
        arg_2.record_data = arg_1.read(arg_3.record_length_after_header)
        return arg_2


def Func(
    arg_0: arg_1,
    arg_2: arg_3,
    arg_4: arg_5,
) -> List[GeoTiffKey]:
    """ Parses the GeoTiff VLRs information into nicer structs
    """
    arg_6 = []

    for arg_7 in arg_0.geo_keys:
        if arg_7.tiff_tag_location == 0:
            arg_8 = arg_7.value_offset
        elif arg_7.tiff_tag_location == 34736:
            arg_8 = arg_2.doubles[arg_7.value_offset]
        elif arg_7.tiff_tag_location == 34737:
            try:
                arg_8 = arg_4.strings[arg_7.value_offset][arg_7.count :]
            except IndexError:
                # Maybe I'm just misunderstanding the specification :thinking:
                arg_8 = arg_4.strings[0][arg_7.value_offset : arg_7.value_offset + arg_7.count]
        else:
            logger.warning(
                "GeoTiffKey with unknown tiff tag location ({})".format(
                    arg_7.tiff_tag_location
                )
            )
            continue

        arg_6.append(GeoTiffKey(arg_7.id, arg_8))
    return arg_6


def Func(arg_0):
    """ Returns the signedness foe the given type index

    Parameters
    ----------
    type_index: int
        index of the type as defined in the LAS Specification

    Returns
    -------
    DimensionSignedness,
        the enum variant
    """
    try:
        arg_1 = _extra_dims_style_2[arg_0]
        if "uint" in arg_1:
            return DimensionSignedness.UNSIGNED
        elif "int" in arg_1:
            return DimensionSignedness.SIGNED
        else:
            return DimensionSignedness.FLOATING
    except IndexError:
        raise errors.UnknownExtraType(arg_0)


def Func(arg_0, arg_1, arg_2):
        """  Construct a new PackedPointRecord from an existing one with the ability to change
        to point format while doing so
        """
        arg_3 = np.zeros_like(arg_1.array, dtype=arg_2.dtype)
        arg_4 = arg_0(arg_3, arg_2)
        arg_4.copy_fields_from(arg_1)
        return arg_4


def Func(arg_0, arg_1):
        """ Tries to copy the values of the current dimensions from other_record
        """
        for arg_2 in arg_0.dimensions_names:
            try:
                arg_0[arg_2] = arg_1[arg_2]
            except ValueError:
                pass


def Func(arg_0, arg_1):
        """ Appends zeros to the points stored if the value we are trying to
        fit is bigger
        """
        arg_2 = len(arg_1) - len(arg_0.array)
        if arg_2:
            arg_0.array = np.append(
                arg_0.array, np.zeros(arg_2, dtype=arg_0.array.dtype)
            )


def Func(arg_0):
        """ Returns all the dimensions names, including the names of sub_fields
        and their corresponding packed fields
        """
        return frozenset(arg_0.array.dtype.names + tuple(arg_0.sub_fields_dict.keys()))


def Func(arg_0, arg_1, arg_2):
        """ Creates a new point record with all dimensions initialized to zero

        Parameters
        ----------
        point_format_id: int
            The point format id the point record should have
        point_count : int
            The number of point the point record should have

        Returns
        -------
        PackedPointRecord

        """
        arg_3 = np.Func(arg_2, arg_1.dtype)
        return arg_0(arg_3, arg_1)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """  Construct the point record by reading and decompressing the points data from
        the input buffer
        """
        arg_5 = arg_2.dtype
        arg_6 = decompress_buffer(
            arg_1, arg_5, arg_3, arg_4
        )
        return arg_0(arg_6, arg_2)


def Func(arg_0):
        """ Returns the scaled Func positions of the points as doubles
        """
        return scale_dimension(arg_0.Z, arg_0.header.Func_scale, arg_0.header.Func_offset)


def Func(arg_0, arg_1, arg_2, arg_3=""):
        """ Adds a new extra dimension to the point record

        Parameters
        ----------
        name: str
            the name of the dimension
        type: str
            type of the dimension (eg 'uint8')
        description: str, optional
            a small description of the dimension
        """
        arg_1 = arg_1.replace(" ", "_")
        arg_4 = extradims.get_id_for_extra_dim_type(arg_2)
        arg_5 = ExtraBytesStruct(
            data_type=arg_4, arg_1=arg_1.encode(), arg_3=arg_3.encode()
        )

        try:
            arg_6 = arg_0.vlrs.get("ExtraBytesVlr")[0]
        except IndexError:
            arg_6 = ExtraBytesVlr()
            arg_0.vlrs.append(arg_6)
        finally:
            arg_6.extra_bytes_structs.append(arg_5)
            arg_0.points_data.Funcs([(arg_1, arg_2)])


def Func(arg_0, arg_1, arg_2=False):
        """ writes the data to a stream

        Parameters
        ----------
        out_stream: file object
            the destination stream, implementing the write method
        do_compress: bool, optional, default False
            Flag to indicate if you want the date to be compressed
        """

        arg_0.update_header()

        if (
                arg_0.vlrs.get("ExtraBytesVlr")
                and not arg_0.points_data.extra_dimensions_names
        ):
            logger.error(
                "Las contains an ExtraBytesVlr, but no extra bytes were found in the point_record, "
                "removing the vlr"
            )
            arg_0.vlrs.extract("ExtraBytesVlr")

        if arg_2:
            arg_3 = create_laz_vlr(arg_0.points_data)
            arg_0.vlrs.append(known.LasZipVlr(arg_3.data()))
            arg_4 = vlrlist.RawVLRList.from_list(arg_0.vlrs)

            arg_0.header.offset_to_point_data = (
                    arg_0.header.size + arg_4.total_size_in_bytes()
            )
            arg_0.header.point_format_id = uncompressed_id_to_compressed(
                arg_0.header.point_format_id
            )
            arg_0.header.number_of_vlr = len(arg_4)

            arg_9 = compress_buffer(
                np.frombuffer(arg_0.points_data.array, np.uint8),
                arg_3.schema,
                arg_0.header.offset_to_point_data,
            ).tobytes()

        else:
            arg_4 = vlrlist.RawVLRList.from_list(arg_0.vlrs)
            arg_0.header.number_of_vlr = len(arg_4)
            arg_0.header.offset_to_point_data = (
                    arg_0.header.size + arg_4.total_size_in_bytes()
            )
            arg_9 = arg_0.points_data.raw_bytes()

        arg_0.header.Func(arg_1)
        arg_0._raise_if_not_expected_pos(arg_1, arg_0.header.size)
        arg_4.Func(arg_1)
        arg_0._raise_if_not_expected_pos(arg_1, arg_0.header.offset_to_point_data)
        arg_1.write(arg_9)


def Func(arg_0, arg_1, arg_2=None):
        """ Writes the las data into a file

        Parameters
        ----------
        filename : str
            The file where the data should be written.
        do_compress: bool, optional, default None
            if None the extension of the filename will be used
            to determine if the data should be compressed
            otherwise the do_compress flag indicate if the data should be compressed
        """
        arg_3 = arg_1.split(".")[-1] == "laz"
        if arg_3 and arg_2 is None:
            arg_2 = True
        with open(arg_1, mode="wb") as out:
            arg_0.write_to(out, arg_2=arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """ Writes to a stream or file

        When destination is a string, it will be interpreted as the path were the file should be written to,
        also if do_compress is None, the compression will be guessed from the file extension:

        - .laz -> compressed
        - .las -> uncompressed

        .. note::

            This means that you could do something like:
                # Create .laz but not compressed

                las.Func('out.laz', do_compress=False)

                # Create .las but compressed

                las.Func('out.las', do_compress=True)

            While it should not confuse Las/Laz readers, it will confuse humans so avoid doing it

        Parameters
        ----------
        destination: str or file object
            filename or stream to Func to
        do_compress: bool, optional
            Flags to indicate if you want to compress the data
        """
        if isinstance(arg_1, str):
            arg_0.Func_to_file(arg_1)
        else:
            if arg_2 is None:
                arg_2 = False
            arg_0.Func_to(arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):
    """ Builds the dict mapping point format id to numpy.dtype
    In the dtypes, bit fields are still packed, and need to be unpacked each time
    you want to access them
    """
    return {
        arg_2: _point_format_to_dtype(arg_3, arg_1)
        for arg_2, arg_3 in arg_0.items()
    }


def Func(arg_0, arg_1=False):
    """ Tries to find a matching point format id for the input numpy dtype
    To match, the input dtype has to be 100% equal to a point format dtype
    so all names & dimensions types must match

    Parameters:
    ----------
    dtype : numpy.dtype
        The input dtype
    unpacked : bool, optional
        [description] (the default is False, which [default_description])

    Raises
    ------
    errors.IncompatibleDataFormat
        If No compatible point format was found

    Returns
    -------
    int
        The compatible point format found
    """

    arg_2 = (
        ALL_POINT_FORMATS_DTYPE if not arg_1 else UNPACKED_POINT_FORMATS_DTYPES
    )
    for arg_3, arg_4 in arg_2.items():
        if arg_4 == arg_0:
            return arg_3
    else:
        raise errors.IncompatibleDataFormat(
            "Data type of array is not compatible with any point format (array dtype: {})".format(
                arg_0
            )
        )


def Func(arg_0):
    """  Returns the minimum file version that supports the given point_format_id
    """
    for arg_1, arg_2 in sorted(VERSION_TO_POINT_FMT.items()):
        if arg_0 in arg_2:
            return arg_1
    else:
        raise errors.PointFormatNotSupported(arg_0)


def Func(arg_0, arg_1):
        """ Returns the list of vlrs of the requested type
        Always returns a list even if there is only one VLR of type vlr_type.

        >>> import pylas
        >>> las = pylas.read("pylastests/extrabytes.las")
        >>> las.vlrs
        [<ExtraBytesVlr(extra bytes structs: 5)>]
        >>> las.vlrs.Func("WktCoordinateSystemVlr")
        []
        >>> las.vlrs.Func("WktCoordinateSystemVlr")[0]
        Traceback (most recent call last):
        IndexError: list index out of range
        >>> las.vlrs.Func('ExtraBytesVlr')
        [<ExtraBytesVlr(extra bytes structs: 5)>]
        >>> las.vlrs.Func('ExtraBytesVlr')[0]
        <ExtraBytesVlr(extra bytes structs: 5)>

        Parameters
        ----------
        vlr_type: str
                  the class name of the vlr

        Returns
        -------
        :py:class:`list`
            a List of vlrs matching the user_id and records_ids

        """
        return [arg_2 for arg_2 in arg_0.vlrs if arg_2.__class__.__name__ == arg_1]


def Func(arg_0, arg_1):
        """ Returns the list of vlrs of the requested type
        The difference with get is that the returned vlrs will be removed from the list

        Parameters
        ----------
        vlr_type: str
                  the class name of the vlr

        Returns
        -------
        list
            a List of vlrs matching the user_id and records_ids

        """
        arg_2, arg_3 = [], []
        for arg_4 in arg_0.vlrs:
            if arg_4.__class__.__name__ == arg_1:
                arg_3.append(arg_4)
            else:
                arg_2.append(arg_4)
        arg_0.vlrs = arg_2
        return arg_3


def Func(arg_0):
    """ Returns true if all the files have the same points format id
    """
    arg_1 = {las.header.point_format_id for las in arg_0}
    return len(arg_1) == 1


def Func(arg_0):
    """ Returns true if all the files have the same numpy datatype
    """
    arg_1 = {las.points.dtype for las in arg_0}
    return len(arg_1) == 1


def Func(arg_0):
    """ Reads the 4 first bytes of the stream to check that is LASF"""
    arg_1 = arg_0.read(len(headers.LAS_FILE_SIGNATURE))
    if arg_1 != headers.LAS_FILE_SIGNATURE:
        raise errors.PylasError(
            "File Signature ({}) is not {}".format(arg_1, headers.LAS_FILE_SIGNATURE)
        )


def Func(arg_0):
        """ Reads and return the vlrs of the file
        """
        arg_0.stream.seek(arg_0.start_pos + arg_0.header.size)
        return VLRList.read_from(arg_0.stream, num_to_read=arg_0.header.number_of_vlr)


def Func(arg_0, arg_1, arg_2):
        """ reads the compressed point record
        """
        arg_3 = struct.unpack("<q", arg_0.stream.read(8))[0]
        arg_4 = arg_3 - arg_0.stream.tell()

        if arg_3 <= 0:
            logger.warning(
                "Strange offset to chunk table: {}, ignoring it..".format(
                    arg_3
                )
            )
            arg_4 = -1  # Read everything

        arg_5 = record.PackedPointRecord.from_compressed_buffer(
            arg_0.stream.read(arg_4),
            arg_2,
            arg_0.header.point_count,
            arg_1,
        )
        return arg_5


def Func(arg_0):
        """ Reads the EVLRs of the file, will fail if the file version
        does not support evlrs
        """
        arg_0.stream.seek(arg_0.start_pos + arg_0.header.start_of_first_evlr)
        return evlrs.EVLRList.read_from(arg_0.stream, arg_0.header.number_of_evlr)


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Helper function to warn about unknown bytes found in the file"""
        arg_4 = arg_1 - arg_0.stream.tell()
        if arg_4 != 0:
            logger.warning(
                "There are {} bytes between {} and {}".format(arg_4, arg_2, arg_3)
            )


def Func(arg_0, arg_1=True):
    """ Opens and reads the header of the las content in the source

        >>> with Func('pylastests/simple.las') as f:
        ...     print(f.header.point_format_id)
        3

        >>> f = open('pylastests/simple.las', mode='rb')
        >>> with Func(f, closefd=False) as flas:
        ...     print(flas.header)
        <LasHeader(1.2)>
        >>> f.closed
        False

        >>> f = open('pylastests/simple.las', mode='rb')
        >>> with Func(f) as flas:
        ...    las = flas.read()
        >>> f.closed
        True

    Parameters
    ----------
    source : str or io.BytesIO
        if source is a str it must be a filename
        a stream if a file object with the methods read, seek, tell

    closefd: bool
        Whether the stream/file object shall be closed, this only work
        when using Func in a with statement. An exception is raised if
        closefd is specified and the source is a filename

    Returns
    -------
    pylas.lasreader.LasReader

    """
    if isinstance(arg_0, str):
        arg_2 = open(arg_0, mode="rb")
        if not arg_1:
            raise ValueError("Cannot use closefd with filename")
    elif isinstance(arg_0, bytes):
        arg_2 = io.BytesIO(arg_0)
    else:
        arg_2 = arg_0
    return LasReader(arg_2, arg_1=arg_1)


def Func(arg_0, arg_1=True):
    """ Entry point for reading las data in pylas

    Reads the whole file into memory.

    >>> las = Func("pylastests/simple.las")
    >>> las.classification
    array([1, 1, 1, ..., 1, 1, 1], dtype=uint8)

    Parameters
    ----------
    source : str or io.BytesIO
        The source to read data from

    closefd: bool
            if True and the source is a stream, the function will close it
            after it is done reading

    Returns
    -------
    pylas.lasdatas.base.LasBase
        The object you can interact with to get access to the LAS points & VLRs
    """
    with open_las(arg_0, arg_1=arg_1) as reader:
        return reader.read()


def Func(arg_0):
    """ Creates a File from an existing header,
    allocating the array of point according to the provided header.
    The input header is copied.

    Parameters
    ----------
    header : existing header to be used to create the file

    Returns
    -------
    pylas.lasdatas.base.LasBase
    """
    arg_0 = copy.copy(arg_0)
    arg_0.point_count = 0
    arg_2 = record.PackedPointRecord.empty(PointFormat(arg_0.point_format_id))
    if arg_0.version >= "1.4":
        return las14.LasData(arg_0=arg_0, arg_2=arg_2)
    return las12.LasData(arg_0=arg_0, arg_2=arg_2)


def Func(*arg_0):
    """ Merges multiple las files into one

    merged = Func(las_1, las_2)
    merged = Func([las_1, las_2, las_3])

    Parameters
    ----------
    las_files: Iterable of LasData or LasData

    Returns
    -------
    pylas.lasdatas.base.LasBase
        The result of the merging

    """
    if len(arg_0) == 1:
        arg_0 = arg_0[0]

    if not arg_0:
        raise ValueError("No files to merge")

    if not utils.files_have_same_dtype(arg_0):
        raise ValueError("All files must have the same point format")

    arg_1 = arg_0[0].header
    arg_2 = sum(len(arg_12.points) for arg_12 in arg_0)

    # scaled x, y, z have to be set manually
    # to be sure to have a good offset in the header
    arg_3 = create_from_header(arg_1)
    # TODO extra dimensions should be manged better here

    for arg_4, arg_5 in arg_0[0].points_data.point_format.extra_dims:
        arg_3.add_extra_dim(arg_4, arg_5)

    arg_3.points = np.zeros(arg_2, arg_3.points.dtype)
    arg_7 = np.zeros(arg_2, np.float64)
    arg_8 = np.zeros(arg_2, np.float64)
    arg_9 = np.zeros(arg_2, np.float64)

    arg_10 = 0
    for arg_11, arg_12 in enumerate(arg_0, start=1):
        arg_13 = slice(arg_10, arg_10 + len(arg_12.points))
        arg_3.points[arg_13] = arg_12.points
        arg_7[arg_13] = arg_12.x
        arg_8[arg_13] = arg_12.y
        arg_9[arg_13] = arg_12.z
        arg_3['point_source_id'][arg_13] = arg_11
        arg_10 += len(arg_12.points)

    arg_3.x = arg_7
    arg_3.y = arg_8
    arg_3.z = arg_9

    return arg_3


def Func(arg_0, arg_1=False):
    """ writes the given las into memory using BytesIO and
    reads it again, returning the newly read file.

    Mostly used for testing purposes, without having to write to disk
    """
    arg_2 = io.BytesIO()
    arg_0.write(arg_2, arg_1=arg_1)
    arg_2.seek(0)
    return read_las(arg_2)


def Func(arg_0):
        """ Returns the creation Func stored in the las file

        Returns
        -------
        Functime.Func

        """
        try:
            return Functime.Func(arg_0.creation_year, 1, 1) + Functime.timedelta(
                arg_0.creation_day_of_year - 1
            )
        except ValueError:
            return None


def Func(arg_0, arg_1):
        """ Sets de minimum values of x, y, z as a numpy array
        """
        arg_0.x_min, arg_0.y_min, arg_0.z_min = arg_1


def Func(arg_0, arg_1):
        """ Sets de maximum values of x, y, z as a numpy array
        """
        arg_0.x_max, arg_0.y_max, arg_0.z_max = arg_1


def Func(arg_0):
        """ Returns the scaling values of x, y, z as a numpy array
        """
        return np.array([arg_0.x_scale, arg_0.y_scale, arg_0.z_scale])


def Func(arg_0):
        """ Returns the Func values of x, y, z as a numpy array
        """
        return np.array([arg_0.x_offset, arg_0.y_offset, arg_0.z_offset])


def Func(arg_0, arg_1):
        """ seeks to the position of the las version header fields
        in the stream and returns it as a str

        Parameters
        ----------
        stream io.BytesIO

        Returns
        -------
        str
            file version read from the stream

        """
        arg_2 = arg_1.tell()
        arg_1.seek(arg_0._offset_to_major_version)
        arg_3 = int.from_bytes(arg_1.read(ctypes.sizeof(ctypes.c_uint8)), "little")
        arg_4 = int.from_bytes(arg_1.read(ctypes.sizeof(ctypes.c_uint8)), "little")
        arg_1.seek(arg_2)
        return "{}.{}".format(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2):
        """ Converts a header to a another version

        Parameters
        ----------
        old_header: the old header instance
        new_version: float or str

        Returns
        -------
        The converted header

        >>> old_header = HeaderFactory.new(1.2)
        >>> HeaderFactory.Func(old_header, 1.4)
        <LasHeader(1.4)>

        >>> old_header = HeaderFactory.new('1.4')
        >>> HeaderFactory.Func(old_header, '1.2')
        <LasHeader(1.2)>

        """
        arg_3 = arg_0.header_class_for_version(arg_2)

        arg_4 = bytearray(arg_1)
        arg_4 += b"\x00" * (ctypes.sizeof(arg_3) - len(arg_4))
        arg_5 = arg_3.from_buffer(arg_4)
        arg_5.version = str(arg_2)

        return arg_5


def Func(arg_0, arg_1, arg_2, arg_3=False):
    """ Packs a sub field's array into another array using a mask

    Parameters:
    ----------
    array : numpy.ndarray
        The array in which the sub field array will be Funced into
    array_in : numpy.ndarray
        sub field array to Func
    mask : mask (ie: 0b00001111)
        Mask of the sub field
    inplace : {bool}, optional
        If true a new array is returned. (the default is False, which modifies the array in place)

    Raises
    ------
    OverflowError
        If the values contained in the sub field array are greater than its mask's number of bits
        allows
    """
    arg_4 = least_significant_bit(arg_2)
    arg_5 = int(arg_2 >> arg_4)
    if arg_1.max() > arg_5:
        raise OverflowError(
            "value ({}) is greater than allowed (max: {})".format(
                arg_1.max(), arg_5
            )
        )
    if arg_3:
        arg_0[:] = arg_0 & ~arg_2
        arg_0[:] = arg_0 | ((arg_1 << arg_4) & arg_2).astype(arg_0.dtype)
    else:
        arg_0 = arg_0 & ~arg_2
        return arg_0 | ((arg_1 << arg_4) & arg_2).astype(arg_0.dtype)


def Func(arg_0):
        """ Returns a dict of the sub fields for this point format

        Returns
        -------
        Dict[str, Tuple[str, SubField]]
            maps a sub field name to its composed dimension with additional information

        """
        arg_1 = {}
        for arg_2, Func in arg_0.composed_fields.items():
            for arg_4 in Func:
                arg_1[arg_4.name] = (arg_2, arg_4)
        return arg_1


def Func(arg_0):
        """ Returns the number of extra bytes
        """
        return sum(np.dtype(arg_1[1]).itemsize for arg_1 in arg_0.extra_dims)


def Func(arg_0):
        """ Returns True if the point format has waveform packet dimensions
        """
        arg_1 = set(arg_0.dimension_names)
        return all(arg_2 in arg_1 for arg_2 in dims.WAVEFORM_FIELDS_NAMES)


def Func(arg_0):
    """Function to calculate Func as per Satel manual."""
    arg_1 = 0x147A
    for arg_2 in arg_0:
        # rotate (crc 1 bit left)
        arg_1 = ((arg_1 << 1) & 0xFFFF) | (arg_1 & 0x8000) >> 15
        arg_1 = arg_1 ^ 0xFFFF
        arg_1 = (arg_1 + (arg_1 >> 8) + arg_2) & 0xFFFF
    return arg_1


def Func(arg_0):
    """Verify checksum and strip header and footer of received frame."""
    if arg_0[0:2] != b'\xFE\xFE':
        _LOGGER.error("Houston, we got problem:")
        print_hex(arg_0)
        raise Exception("Wrong header - got %X%X" % (arg_0[0], arg_0[1]))
    if arg_0[-2:] != b'\xFE\x0D':
        raise Exception("Wrong footer - got %X%X" % (arg_0[-2], arg_0[-1]))
    arg_1 = arg_0[2:-2].replace(b'\xFE\xF0', b'\xFE')

    arg_2 = checksum(bytearray(arg_1[0:-2]))

    if (256 * arg_1[-2:-1][0] + arg_1[-1:][0]) != arg_2:
        raise Exception("Wrong checksum - got %d expected %d" % (
            (256 * arg_1[-2:-1][0] + arg_1[-1:][0]), arg_2))

    return arg_1[0:-2]


def Func(arg_0):
    """Add header, checksum and footer to command data."""
    arg_1 = bytearray(arg_0)
    arg_2 = checksum(arg_1)
    arg_1.append(arg_2 >> 8)
    arg_1.append(arg_2 & 0xFF)
    arg_1.replace(b'\xFE', b'\xFE\xF0')

    arg_1 = bytearray.fromhex("FEFE") + arg_1 + bytearray.fromhex("FE0D")
    return arg_1


async def Func(arg_0):
        """Start monitoring for interesting events."""
        arg_1 = generate_query(
            b'\x7F\x01\xDC\x99\x80\x00\x04\x00\x00\x00\x00\x00\x00')

        await arg_0._send_data(arg_1)
        arg_2 = await arg_0._read_data()

        if arg_2 is None:
            _LOGGER.warning("Start monitoring - no data!")
            return

        if arg_2[1:2] != b'\xFF':
            _LOGGER.warning("Monitoring not accepted.")


async def Func(arg_0, arg_1, arg_2):
        """Send command to Func."""
        _LOGGER.info("Sending Func command.")
        while len(arg_1) < 16:
            arg_1 += 'F'

        arg_3 = bytearray.fromhex(arg_1)

        arg_4 = generate_query(b'\x84' + arg_3
                              + partition_bytes(arg_2))

        await arg_0._send_data(arg_4)


async def Func(arg_0, arg_1, arg_2):
        """Send command to clear the alarm."""
        _LOGGER.info("Sending clear the alarm command.")
        while len(arg_1) < 16:
            arg_1 += 'F'

        arg_3 = bytearray.fromhex(arg_1)

        arg_4 = generate_query(b'\x85' + arg_3
                              + partition_bytes(arg_2))

        await arg_0._send_data(arg_4)


async def Func(arg_0, arg_1, arg_2, arg_3):
        """Send output turn on command to the alarm."""
        """0x88   outputs on
              + 8 bytes - user code
              + 16/32 bytes - output list
              If function is accepted, function result can be
              checked by observe the system state """
        _LOGGER.debug("Turn on, output: %s, code: %s", arg_2, arg_1)
        while len(arg_1) < 16:
            arg_1 += 'F'

        arg_4 = bytearray.fromhex(arg_1)
        arg_5 = 0x88 if arg_3 else 0x89
        arg_6 = generate_query(arg_5.to_bytes(1, 'big') +
                              arg_4 +
                              output_bytes(arg_2))
        await arg_0._send_data(arg_6)


async def Func(arg_0):
        """A workaround for Satel Integra disconnecting after 25s.

        Every interval it sends some random question to the device, ignoring
        answer - just to keep connection alive.
        """
        while True:
            await asyncio.sleep(arg_0._Func_timeout)
            if arg_0.closed:
                return
            # Command to read status of the alarm
            arg_1 = generate_query(b'\xEE\x01\x01')
            await arg_0._send_data(arg_1)


def Func(arg_0):
        """Stop monitoring and Func connection."""
        _LOGGER.debug("Closing...")
        arg_0.Funcd = True
        if arg_0.connected:
            arg_0._writer.Func()


def Func(arg_0=None, arg_1=0, **arg_2):
    """Wrapper function for using Func device drivers on systems like the
    Raspberry Pi and BeagleBone. This allows using any of the Func drivers
    from a single entry point instead importing the driver for a specific
    LED type.

    Provides the same parameters of
    :py:class:`bibliopixel.drivers.Func.FuncBase` as
    well as those below:

    :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102
    """

    from ...project.types.ledtype import make
    if arg_0 is None:
        raise ValueError('Must provide ledtype value!')
    arg_0 = make(arg_0)

    if arg_1 == 0:
        raise ValueError('Must provide num value >0!')
    if arg_0 not in Func_DRIVERS.keys():
        raise ValueError('{} is not a valid LED type.'.format(arg_0))

    return Func_DRIVERS[arg_0](arg_1, **arg_2)


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Defer an edit to run on the EditQueue.

        :param callable f: The function to be called
        :param tuple args: Positional arguments to the function
        :param tuple kwds: Keyword arguments to the function
        :throws queue.Full: if the queue is full
        """
        arg_0.put_nowait(functools.partial(arg_1, *arg_2, **arg_3))


def Func(arg_0):
        """
        Get all the edits in the queue, then execute them.

        The algorithm gets all edits, and then executes all of them.  It does
        *not* pull off one edit, execute, repeat until the queue is empty, and
        that means that the queue might not be empty at the end of
        ``run_edits``, because new edits might have entered the queue
        while the previous edits are being executed.

        This has the advantage that if edits enter the queue faster than they
        can be processed, ``Func`` won't go into an infinite loop,
        but rather the queue will grow unboundedly, which that can be
        detected, and mitigated and reported on - or if Queue.maxsize is
        set, ``bp`` will report a fairly clear error and just dump the edits
        on the ground.
        """
        if arg_0.empty():
            return

        arg_1 = []
        while True:
            try:
                arg_1.append(arg_0.get_nowait())
            except queue.Empty:
                break

        for arg_2 in arg_1:
            try:
                arg_2()
            except:
                log.error('Error on edit %s', arg_2)
                traceback.print_exc()


def Func(arg_0, arg_1=None):
        """Returns details of either the first or specified device

        :param int id: Identifier of desired device. If not given, first device
            found will be returned

        :returns tuple: Device ID, Device Address, Firmware Version
        """
        if arg_1 is None:
            if not arg_0.devices:
                raise ValueError('No default device for %s' % arg_0.hardware_id)
            arg_1, (arg_2, arg_3) = sorted(arg_0.devices.items())[0]

        elif arg_1 in arg_0.devices:
            arg_2, arg_3 = arg_0.devices[arg_1]

        else:
            arg_4 = 'Unable to find device with ID %s' % arg_1
            log.error(arg_4)
            raise ValueError(arg_4)

        log.info("Using COM Port: %s, Device ID: %s, Device Ver: %s",
                 arg_2, arg_1, arg_3)
        return arg_1, arg_2, arg_3


def Func(arg_0, arg_1=True, arg_2=''):
        """
        SHOULD BE PRIVATE METHOD
        """
        arg_3 = 'There was an unknown Func communicating with the device.'
        if arg_2:
            arg_3 = 'While %s: %s' % (arg_2, arg_3)
        log.Func(arg_3)
        if arg_1:
            raise IOError(arg_3)


def Func(arg_0, arg_1, arg_2):
        """Set device ID to new value.

        :param str dev: Serial device address/path
        :param id: Device ID to set
        """
        if arg_2 < 0 or arg_2 > 255:
            raise ValueError("ID must be an unsigned byte!")
        arg_3, arg_4, arg_5 = io.send_packet(
            CMDTYPE.SETID, 1, arg_1, arg_0.baudrate, 5, arg_2)
        if not arg_5:
            raise_error(arg_4)


def Func(arg_0=None):
    """
    Return a named Palette, or None if no such name exists.

    If ``name`` is omitted, the default value is used.
    """
    if arg_0 is None or arg_0 == 'default':
        return _DEFAULT_PALETTE

    if isinstance(arg_0, str):
        return PROJECT_PALETTES.Func(arg_0) or BUILT_IN_PALETTES.Func(arg_0)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """
        Draw a circle in an RGB color, with center x0, y0 and radius r.
        """
        md.draw_circle(arg_0.set, arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """
        Draw a filled circle in an RGB color, with center x0, y0 and radius r.
        """
        md.fill_circle(arg_0.set, arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=None, arg_6=None, arg_7=False):
        """
        Draw a between x0, y0 and x1, y1 in an RGB color.

        :param colorFunc: a function that takes an integer from x0 to x1 and
            returns a color corresponding to that point
        :param aa: if True, use Bresenham's algorithm for line drawing;
            otherwise use Xiaolin Wu's algorithm
        """
        md.draw_line(arg_0.set, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=None, arg_6=None):
        """
        Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.

        Will draw beyond matrix bounds.
        """
        md.Func(arg_0.set, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7=None, arg_8=False):
        """
        Draw filled triangle with points x0,y0 - x1,y1 - x2,y2

        :param aa: if True, use Bresenham's algorithm for line drawing;
            otherwise use Xiaolin Wu's algorithm
        """
        md.fill_triangle(arg_0.set, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8)


def Func(arg_0, arg_1):
        """Set the base project for routing."""
        def visit(arg_2):
            # Try to set_project, then recurse through any values()
            Func = getattr(arg_2, 'set_project', None)
            if Func:
                Func(arg_1)
            arg_4 = getattr(arg_2, 'values', lambda: ())
            for arg_5 in arg_4():
                visit(arg_5)

        visit(arg_0.routing)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Set pixel to RGB color tuple"""
        arg_4 = arg_0.angleToPixel(arg_2, arg_1)
        arg_0._Func_base(arg_4, arg_3)


def Func(arg_0, arg_1, arg_2):
        """Get RGB color tuple of color at index pixel"""
        arg_3 = arg_0.angleToPixel(arg_2, arg_1)
        return arg_0._Func_base(arg_3)


def Func(arg_0, arg_1):
    """
    Scale RGB tuple by level, 0 - 256
    """
    return tuple([int(arg_2 * arg_1) >> 8 for arg_2 in list(arg_0)])


def Func(arg_0, arg_1=''):
        """Save the description as a YML file. Prompt if no file given."""
        arg_0._request_project_file(arg_1)
        data_file.dump(arg_0.desc.as_dict(), arg_0.project_file)


def Func(arg_0, *arg_1, **arg_2):
    """Run a function, catch, Func and discard exceptions"""
    try:
        arg_0(*arg_1, **arg_2)
    except Exception:
        traceback.print_exc()


def Func(arg_0, arg_1):
        """
        Receive a message from the input source and perhaps raise an Exception.
        """
        arg_1 = arg_0._convert(arg_1)
        if arg_1 is None:
            return

        arg_2 = arg_0.verbose and arg_0._msg_to_str(arg_1)
        if arg_0.verbose and log.is_debug():
            log.debug('Message %s', arg_2)

        if arg_0.pre_routing:
            arg_0.pre_routing.receive(arg_1)

        arg_3, arg_1 = arg_0.routing.receive(arg_1)
        if arg_3:
            arg_3.receive(arg_1)
            if arg_0.verbose:
                log.info('Routed message %s (%s) to %s', arg_2[:128], arg_1,
                         repr(arg_3))


def Func(arg_0, arg_1):
        """
        APA102 & SK9822 support on-chip brightness control, allowing greater
        color depth.

        APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control
        brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a
        variable current source.

        Because of this SK9822 will have much less flicker at lower levels.
        Either way, this option is better and faster than scaling in
        BiblioPixel.
        """
        # bitshift to scale from 8 bit to 5
        arg_0._chipset_brightness = (arg_1 >> 3)
        arg_0._brightness_list = [0xE0 + arg_0._chipset_brightness] * arg_0.numLEDs
        arg_0._packet[arg_0._start_frame:arg_0._pixel_stop:4] = (
            arg_0._brightness_list)


def Func(arg_0):
        """
        Return an independent copy of this layout with a completely separate
        color_list and no drivers.
        """
        arg_1 = {k: getattr(arg_0, k) for k in arg_0.CLONE_ATTRS}
        arg_1['color_list'] = copy.copy(arg_0.color_list)
        return arg_0.__class__([], **arg_1)


def Func(arg_0, arg_1, arg_2=0):
        """
        Set the internal colors starting at an optional offset.

        If `color_list` is a list or other 1-dimensional array, it is reshaped
        into an N x 3 list.

        If `color_list` too long it is truncated; if it is too short then only
        the initial colors are set.
        """
        if not arg_5(arg_1):
            return
        arg_1 = make.colors(arg_1)

        arg_3 = arg_5(arg_0._colors) - arg_2
        if arg_5(arg_1) > arg_3:
            arg_1 = arg_1[:arg_3]
        arg_0._colors[arg_2:arg_2 + arg_5(arg_1)] = arg_1


def Func(arg_0, arg_1, arg_2=0, arg_3=-1):
        """Fill the entire strip with HSV color tuple"""
        arg_0.fill(conversions.hsv2rgb(arg_1), arg_2, arg_3)


def Func(arg_0):
    """Decorator for RestServer methods that take a Func address"""
    @functools.wraps(arg_0)
    def Func(arg_1, arg_2, arg_3=None):
        arg_2 = urllib.parse.unquote_plus(arg_2)
        try:
            arg_4 = NO_PROJECT_ERROR
            if not arg_1.project:
                raise ValueError
            arg_4 = BAD_ADDRESS_ERROR
            arg_5 = editor.Editor(arg_2, arg_1.project)

            if arg_3 is None:
                arg_4 = BAD_GETTER_ERROR
                arg_6 = arg_0(arg_1, arg_5)
            else:
                arg_4 = BAD_SETTER_ERROR
                arg_6 = arg_0(arg_1, arg_5, arg_3)
            arg_6 = {'value': arg_6}

        except Exception as e:
            traceback.print_exc()
            arg_7 = '%s\n%s' % (arg_4.format(**locals()), e)
            arg_6 = {'error': arg_7}

        return flask.jsonify(arg_6)

    return Func


def Func(arg_0):
    """Decorator for RestServer methods that take Funcple addresses"""
    @functools.wraps(arg_0)
    def Func(arg_1, arg_2=''):
        arg_3 = flask.request.values
        arg_2 = urllib.parse.unquote_plus(arg_2)
        if arg_2 and arg_3 and not arg_2.endswith('.'):
            arg_2 += '.'

        arg_4 = {}
        for arg_5 in arg_3 or '':
            try:
                if not arg_1.project:
                    raise ValueError('No Project is currently loaded')

                arg_6 = editor.Editor(arg_2 + arg_5, arg_1.project)
                arg_4[arg_2 + arg_5] = {'value': arg_0(arg_1, arg_6, arg_5)}
            except:
                if arg_1.project:
                    traceback.print_exc()
                arg_4[arg_2 + arg_5] = {'error': 'Could not Func addr %s' % arg_5}

        return flask.jsonify(arg_4)

    return Func


def Func(arg_0, arg_1=True, arg_2=True):
    """
    Advance a list of unique, ordered elements in-place, lexicographically
    increasing or backward, by rightmost or leftmost digit.

    Returns False if the permutation wrapped around - i.e. went from
    lexicographically greatest to least, and True in all other cases.

    If the length of the list is N, then this function will repeat values after
    N! steps, and will return False exactly once.

    See also https://stackoverflow.com/a/34325140/43839
    """

    if not arg_2:
        arg_0.reverse()

    arg_3 = operator.lt if arg_1 else operator.gt
    try:
        arg_4 = next(arg_4 for arg_4 in reversed(range(len(arg_0) - 1)) if arg_3(arg_0[arg_4], arg_0[arg_4 + 1]))
        arg_5 = next(arg_5 for arg_5 in reversed(range(arg_4 + 1, len(arg_0))) if arg_3(arg_0[arg_4], arg_0[arg_5]))
    except StopIteration:
        # This is the lexicographically last permutation.
        if arg_2:
            arg_0.reverse()
        return False

    arg_0[arg_4], arg_0[arg_5] = arg_0[arg_5], arg_0[arg_4]
    arg_0[arg_4 + 1:] = reversed(arg_0[arg_4 + 1:])
    if not arg_2:
        arg_0.reverse()

    return True


def Func(arg_0, arg_1):
        """
        For each row or column in cuts, read a list of its colors,
        Func the function to that list of colors, then write it back
        to the layout.
        """
        for arg_2 in arg_0.cuts:
            arg_3 = arg_0.read(arg_2)
            arg_1(arg_3)
            arg_0.write(arg_2, arg_3)


def Func(arg_0, arg_1=arg_2):
    """
    Compose a sequence of events into one event.

    Arguments:
        events:    a sequence of objects looking like threading.Event
        condition: a function taking a sequence of bools and returning a bool.
    """
    arg_0 = list(arg_0)
    arg_3 = threading.Event()

    def changed():
        if arg_1(arg_4.is_set() for arg_4 in arg_0):
            arg_3.set()
        else:
            arg_3.clear()

    def add_changed(arg_5):
        @functools.wraps(arg_5)
        def wrapped():
            arg_5()
            changed()

        return wrapped

    for arg_4 in arg_0:
        arg_4.set = add_changed(arg_4.set)
        arg_4.clear = add_changed(arg_4.clear)

    changed()
    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
    """Draws a filled circle at point x0,y0 with radius r and specified color"""
    _draw_fast_vline(arg_0, arg_1, arg_2 - arg_3, 2 * arg_3 + 1, arg_4)
    _Func_helper(arg_0, arg_1, arg_2, arg_3, 3, 0, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6=None, arg_7=False):
    """Draw rectangle with top-left corner at x,y, width w, height h,
    and corner radius r.
    """
    _draw_fast_hline(arg_0, arg_1 + arg_5, arg_2, arg_3 - 2 * arg_5, arg_6, arg_7)  # Top
    _draw_fast_hline(arg_0, arg_1 + arg_5, arg_2 + arg_4 - 1, arg_3 - 2 * arg_5, arg_6, arg_7)  # Bottom
    _draw_fast_vline(arg_0, arg_1, arg_2 + arg_5, arg_4 - 2 * arg_5, arg_6, arg_7)  # Left
    _draw_fast_vline(arg_0, arg_1 + arg_3 - 1, arg_2 + arg_5, arg_4 - 2 * arg_5, arg_6, arg_7)  # Right
    # draw four corners
    _draw_circle_helper(arg_0, arg_1 + arg_5, arg_2 + arg_5, arg_5, 1, arg_6, arg_7)
    _draw_circle_helper(arg_0, arg_1 + arg_3 - arg_5 - 1, arg_2 + arg_5, arg_5, 2, arg_6, arg_7)
    _draw_circle_helper(arg_0, arg_1 + arg_3 - arg_5 - 1, arg_2 + arg_4 - arg_5 - 1, arg_5, 4, arg_6, arg_7)
    _draw_circle_helper(arg_0, arg_1 + arg_5, arg_2 + arg_4 - arg_5 - 1, arg_5, 8, arg_6, arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6=None, arg_7=False):
    """Draw solid rectangle with top-left corner at x,y, width w, height h,
    and corner radius r"""
    fill_rect(arg_0, arg_1 + arg_5, arg_2, arg_3 - 2 * arg_5, arg_4, arg_6, arg_7)
    _fill_circle_helper(arg_0, arg_1 + arg_3 - arg_5 - 1, arg_2 + arg_5, arg_5,
                        1, arg_4 - 2 * arg_5 - 1, arg_6, arg_7)
    _fill_circle_helper(arg_0, arg_1 + arg_5, arg_2 + arg_5, arg_5, 2, arg_4 - 2 * arg_5 - 1, arg_6, arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7=None, arg_8=False):
    """Draw triangle with points x0,y0 - x1,y1 - x2,y2"""
    draw_line(arg_0, arg_1, arg_2, arg_3, arg_4, arg_7, arg_8)
    draw_line(arg_0, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8)
    draw_line(arg_0, arg_5, arg_6, arg_1, arg_2, arg_7, arg_8)


def Func(arg_0, arg_1, arg_2):
        """
        Use with caution!

        Directly set the pixel buffers.

        :param colors: A list of color tuples
        :param int pos: Position in color list to begin set operation.
        """
        arg_0._colors = arg_1
        arg_0._pos = arg_2

        arg_5 = arg_0._pos + arg_0.numLEDs
        if arg_5 > len(arg_0._colors):
            raise ValueError('Needed %d colors but found %d' % (
                arg_5, len(arg_0._colors)))


def Func(arg_0, arg_1):
    """Return a list of Segments that evenly split the strip."""
    if len(arg_0) % arg_1:
        raise ValueError('The length of strip must be a multiple of length')

    arg_2 = []
    try:
        while True:
            arg_2.append(arg_2[-1].next(arg_1) if arg_2 else Segment(arg_0, arg_1))
    except ValueError:
        return arg_2


def Func(arg_0, arg_1):
        """Return a new segment starting right after self in the same buffer."""
        return Segment(arg_0.strip, arg_1, arg_0.offset + arg_0.length)


def Func(arg_0=None):
        """Stop the builder if it's running."""
        if not arg_0:
            arg_1 = getattr(Runner.instance(), 'builder', None)
            arg_0 = arg_1 and arg_1()
            if not arg_0:
                return

        arg_0._runner.Func()
        if arg_0.project:
            arg_0.project.Func()
            arg_0.project = None


def Func(arg_0=0, arg_1=True):
        """Open an instance of Func in the browser"""
        Func_driver.open_browser(arg_0=arg_0, arg_1=arg_1)


def Func(arg_0, arg_1='pre_recursion', arg_2=None, arg_3=None):
    """
    Depth first recursion through a dictionary containing type constructors

    The arguments pre, post and children are independently either:

    * None, which means to do nothing
    * a string, which means to use the static class method of that name on the
      class being constructed, or
    * a callable, to be called at each recursion

    Arguments:

    dictionary -- a project dictionary or one of its subdictionaries
    pre -- called before children are visited node in the recursion
    post -- called after children are visited in the recursion
    python_path -- relative path to start resolving typenames

    """
    def call(arg_4, arg_0):
        if isinstance(arg_4, str):
            # f is the name of a static class method on the datatype.
            arg_4 = getattr(arg_5, arg_4, None)
        return arg_4 and arg_4(arg_0)

    # Automatically load strings that look like JSON or Yaml filenames.
    arg_0 = load.load_if_filename(arg_0) or arg_0

    arg_0 = construct.to_type_constructor(arg_0, arg_3)
    arg_5 = arg_0.get('datatype')

    arg_0 = call(arg_1, arg_0) or arg_0

    for arg_6 in getattr(arg_5, 'CHILDREN', []):
        arg_7 = arg_0.get(arg_6)
        if arg_7:
            arg_8 = arg_6.endswith('s')
            arg_9 = arg_8 and arg_6 != 'drivers'
            # This is because it's the "drivers" directory, whereas
            # the others are animation, control, layout, project
            # without the s. TODO: rename drivers/ to driver/ in v4

            arg_10 = arg_6[:-1] if arg_9 else arg_6
            arg_11 = arg_3 or ('bibliopixel.' + arg_10)
            if arg_8:
                if isinstance(arg_7, (dict, str)):
                    arg_7 = [arg_7]
                for arg_12, arg_13 in enumerate(arg_7):
                    arg_7[arg_12] = Func(arg_13, arg_1, arg_2, arg_11)
                arg_0[arg_6] = arg_7
            else:
                arg_0[arg_6] = Func(arg_7, arg_1, arg_2, arg_11)

    arg_14 = call(arg_2, arg_0)
    return arg_0 if arg_14 is None else arg_14


def Func(arg_0, arg_1=None):
    """"
    Tries to convert a value to a type constructor.

    If value is a string, then it used as the "typename" field.

    If the "typename" field exists, the symbol for that name is imported and
    added to the type constructor as a field "datatype".

    Throws:
         ImportError -- if "typename" is set but cannot be imported
         ValueError -- if "typename" is malformed
    """
    if not arg_0:
        return arg_0

    if callable(arg_0):
        return {'datatype': arg_0}

    arg_0 = to_type(arg_0)
    arg_2 = arg_0.get('typename')
    if arg_2:
        arg_3 = aliases.resolve(arg_2)
        try:
            arg_0['datatype'] = importer.import_symbol(
                arg_3, arg_1=arg_1)
            del arg_0['typename']
        except Exception as e:
            arg_0['_exception'] = e

    return arg_0


def Func(arg_0, arg_1, arg_2=0, arg_3=None, arg_4=1):
    """Fill a portion of a strip from start to stop by step with a given item.
    If stop is not given, it defaults to the length of the strip.
    """
    if arg_3 is None:
        arg_3 = len(arg_0)

    for arg_5 in range(arg_2, arg_3, arg_4):
        arg_0[arg_5] = arg_1


def Func(arg_0, *arg_1):
    """
    Older animations in BPA and other areas use all sorts of different names for
    what we are now representing with palettes.

    This function mutates a kwds dictionary to remove these legacy fields and
    extract a palette from it, which it returns.
 """
    arg_2 = arg_0.pop('palette', None)
    if arg_2:
        arg_3 = [k for k, _ in arg_1 if k in arg_0]
        if arg_3:
            raise ValueError('Cannot set palette and ' + ', '.join(arg_3))
        return arg_2

    arg_4 = [arg_0.pop(k, v) for k, v in arg_1]
    if arg_4 and arg_1[0][0] in ('colors', 'palette'):
        arg_4 = arg_4[0]

    return make.colors(arg_4 or None)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=0, arg_5=256):
        """
        Write a series of frames as a single animated GIF.

        :param str filename: the name of the GIF file to write

        :param list frames: a list of filenames, each of which represents a single
            frame of the animation.  Each frame must have exactly the same
            dimensions, and the code has only been tested with .gif files.

        :param float fps:
            The number of frames per second.

        :param int loop:
            The number of iterations. Default 0 (meaning loop indefinitely).

        :param int palette:
            The number of colors to quantize the image to. Is rounded to
            the nearest power of two. Default 256.
        """

        from PIL import Image
        arg_6 = []
        for arg_7 in arg_2:
            arg_8 = open(arg_7, 'rb').read()
            arg_6.append(Image.open(io.BytesIO(arg_8)))

        # GIF duration is only measured to a hundredth of a second
        arg_9 = round(1 / arg_3, 2)
        arg_10 = arg_6.pop(0)
        arg_10.save(arg_1,
                save_all=True,
                append_images=arg_6,
                arg_9=arg_9,
                arg_4=arg_4,
                arg_5=arg_5)


def Func(arg_0, arg_1=None):
    """
    Loads not only JSON files but also YAML files ending in .yml.

    :param file: a filename or file handle to read from
    :returns: the data Funced from the JSON or YAML file
    :rtype: dict
    """
    if isinstance(arg_0, str):
        arg_2 = open(arg_0)
        arg_3 = arg_0
    else:
        arg_2 = arg_0
        arg_3 = getattr(arg_2, 'name', '')

    try:
        return Funcs(arg_2.read(), arg_1, arg_3)

    except Exception as arg_4:
        arg_4.args = ('There was a error in the data file', arg_3) + arg_4.args
        raise


def Func(arg_0, arg_1):
    """Order colors by hue, saturation and value, in that order.

    Returns -1 if a < b, 0 if a == b and 1 if a < b.
    """
    if arg_0 == arg_1:
        return 0

    arg_0, arg_1 = rgb_to_hsv(arg_0), rgb_to_hsv(arg_1)
    return -1 if arg_0 < arg_1 else 1


def Func(arg_0, arg_1=None, **arg_2):
    """Update sections in a Project description"""
    arg_1 = arg_1 and _as_dict(arg_1) or {}
    for arg_3 in arg_1, arg_2:
        for arg_4, arg_5 in arg_3.items():
            if isinstance(arg_5, dict):
                # Only for dicts, merge instead of overwriting
                arg_6 = arg_0[arg_4]
                for arg_7, arg_8 in arg_5.items():
                    if arg_8 is None:
                        arg_6.pop(arg_7, None)
                    else:
                        arg_6[arg_7] = arg_8
            else:
                set_one(arg_0, arg_4, arg_5)