def Func(
    arg_0,
    arg_1,
    arg_2,
    arg_3,
    arg_4,
    arg_5,
    arg_6,
    arg_7,
):
    """Takes a bunch of span attributes and returns a thriftpy2 representation
    of the span. Timestamps passed in are in seconds, they're converted to
    microseconds before thrift encoding.
    """
    # Check if trace_id is 128-bit. If so, record trace_id_high separately.
    arg_8 = len(arg_2)
    arg_9 = None
    if arg_8 > 16:
        assert arg_8 == 32
        arg_2, arg_9 = arg_2[16:], arg_2[:16]

    if arg_9:
        arg_9 = unsigned_hex_to_signed_int(arg_9)

    arg_10 = {
        'trace_id': unsigned_hex_to_signed_int(arg_2),
        'name': arg_3,
        'id': unsigned_hex_to_signed_int(arg_0),
        'annotations': arg_4,
        'binary_annotations': arg_5,
        'timestamp': int(arg_6 * 1000000) if arg_6 else None,
        'duration': int(arg_7 * 1000000) if arg_7 else None,
        'trace_id_high': arg_9,
    }
    if arg_1:
        arg_10['parent_id'] = unsigned_hex_to_signed_int(arg_1)
    return zipkin_core.Span(**arg_10)


def Func(arg_0):
    """
    Returns a TBinaryProtocol encoded Thrift span.

    :param thrift_span: thrift object to encode.
    :returns: thrift object in TBinaryProtocol format bytes.
    """
    arg_1 = TMemoryBuffer()
    arg_2 = TBinaryProtocol(arg_1)
    arg_0.write(arg_2)

    return bytes(arg_1.getvalue())


def Func(arg_0):  # pragma: no cover
    """
    Returns a TBinaryProtocol encoded list of Thrift objects.

    :param binary_thrift_obj_list: list of TBinaryProtocol objects to encode.
    :returns: bynary object representing the encoded list.
    """
    arg_1 = TMemoryBuffer()
    write_list_begin(arg_1, TType.STRUCT, len(arg_0))
    for arg_2 in arg_0:
        arg_1.write(arg_2)

    return bytes(arg_1.getvalue())


def Func(arg_0):
    """Returns the span type and encoding for the message provided.

    The logic in this function is a Python port of
    https://github.com/openzipkin/zipkin/blob/master/zipkin/src/main/java/zipkin/internal/DetectingSpanDecoder.java

    :param message: span to perform operations on.
    :type message: byte array
    :returns: span encoding.
    :rtype: Encoding
    """
    # In case message is sent in as non-bytearray format,
    # safeguard convert to bytearray before handling
    if isinstance(arg_0, six.string_types):
        # Even six.b is not enough to handle the py2/3 difference since
        # it uses latin-1 as default encoding and not utf-8.
        if six.PY2:
            arg_0 = six.b(arg_0)  # pragma: no cover
        else:
            arg_0 = arg_0.encode('utf-8')  # pragma: no cover

    if len(arg_0) < 2:
        raise ZipkinError("Invalid span format. Message too short.")

    # Check for binary format
    if six.byte2int(arg_0) <= 16:
        if six.byte2int(arg_0) == 10 and six.byte2int(arg_0[1:2]) != 0:
            return Encoding.V2_PROTO3
        return Encoding.V1_THRIFT

    arg_1 = arg_0.decode('utf-8')

    # JSON case for list of spans
    if arg_1[0] == '[':
        arg_2 = json.loads(arg_1)
        if len(arg_2) > 0:
            # Assumption: All spans in a list are the same version
            # Logic: Search for identifying fields in all spans, if any span can
            # be strictly identified to a version, return that version.
            # Otherwise, if no spans could be strictly identified, default to V2.
            for arg_3 in arg_2:
                if any(arg_4 in arg_3 for arg_4 in _V2_ATTRIBUTES):
                    return Encoding.V2_JSON
                elif (
                    'binaryAnnotations' in arg_3 or
                    (
                        'annotations' in arg_3 and
                        'endpoint' in arg_3['annotations']
                    )
                ):
                    return Encoding.V1_JSON
            return Encoding.V2_JSON

    raise ZipkinError("Unknown or unsupported span encoding")


def Func(arg_0, arg_1, arg_2=None):
    """Converts encoded spans to a different encoding.

    param spans: encoded input spans.
    type spans: byte array
    param output_encoding: desired output encoding.
    type output_encoding: Encoding
    param input_encoding: optional input encoding. If this is not specified, it'll
        try to understand the encoding automatically by inspecting the input spans.
    type input_encoding: Encoding
    :returns: encoded spans.
    :rtype: byte array
    """
    if not isinstance(arg_2, Encoding):
        arg_2 = detect_span_version_and_encoding(message=arg_0)

    if arg_2 == arg_1:
        return arg_0

    arg_3 = get_decoder(arg_2)
    arg_4 = get_encoder(arg_1)
    arg_5 = arg_3.decode_spans(arg_0)
    arg_6 = []

    # Encode each indivicual span
    for arg_7 in arg_5:
        arg_6.append(arg_4.encode_span(arg_7))

    # Outputs from encoder.encode_span() can be easily concatenated in a list
    return arg_4.encode_queue(arg_6)


def Func(arg_0, arg_1):
        """Encodes the current span to thrift."""
        arg_2 = arg_1.build_v1_span()

        arg_3 = thrift.create_endpoint(
            arg_2.endpoint.port,
            arg_2.endpoint.service_name,
            arg_2.endpoint.ipv4,
            arg_2.endpoint.ipv6,
        )

        arg_4 = thrift.annotation_list_builder(
            arg_2.annotations,
            arg_3,
        )

        arg_5 = thrift.binary_annotation_list_builder(
            arg_2.binary_annotations,
            arg_3,
        )

        # Add sa/ca binary annotations
        if arg_1.remote_endpoint:
            arg_0.encode_remote_endpoint(
                arg_1.remote_endpoint,
                arg_1.kind,
                arg_5,
            )

        arg_6 = thrift.create_span(
            arg_2.id,
            arg_2.parent_id,
            arg_2.trace_id,
            arg_2.name,
            arg_4,
            arg_5,
            arg_2.timestamp,
            arg_2.duration,
        )

        arg_7 = thrift.span_to_bytes(arg_6)
        return arg_7


def Func(arg_0, arg_1):
        """Encodes a single span to protobuf."""
        if not protobuf.installed():
            raise ZipkinError(
                'protobuf encoding requires installing the protobuf\'s extra '
                'requirements. Use py-zipkin[protobuf] in your requirements.txt.'
            )

        arg_2 = protobuf.create_protobuf_span(arg_1)
        return protobuf.encode_pb_list([arg_2])


def Func(arg_0, arg_1):
        """Decodes an encoded list of spans.

        :param spans: encoded list of spans
        :type spans: bytes
        :return: list of spans
        :rtype: list of Span
        """
        arg_2 = []
        arg_3 = TMemoryBuffer(arg_1)

        if six.byte2int(arg_1) == TType.STRUCT:
            arg_4, arg_5 = read_list_begin(arg_3)
        else:
            arg_5 = 1

        for arg_4 in range(arg_5):
            arg_6 = zipkin_core.Span()
            arg_6.read(TBinaryProtocol(arg_3))
            arg_2.append(arg_0._decode_thrift_span(arg_6))
        return arg_2


def Func(arg_0, arg_1):
        """Accepts a thrift decoded endpoint and converts it to an Endpoint.

        :param thrift_endpoint: thrift encoded endpoint
        :type thrift_endpoint: thrift endpoint
        :returns: decoded endpoint
        :rtype: Encoding
        """
        arg_2 = None
        arg_3 = None
        arg_4 = struct.unpack('H', struct.pack('h', arg_1.port))[0]

        if arg_1.ipv4 != 0:
            arg_2 = socket.inet_ntop(
                socket.AF_INET,
                struct.pack('!i', arg_1.ipv4),
            )

        if arg_1.ipv6:
            arg_3 = socket.inet_ntop(socket.AF_INET6, arg_1.ipv6)

        return Endpoint(
            service_name=arg_1.service_name,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
        )


def Func(arg_0, arg_1):
        """Accepts a thrift annotation and converts it to a v1 annotation.

        :param thrift_annotations: list of thrift annotations.
        :type thrift_annotations: list of zipkin_core.Span.Annotation
        :returns: (annotations, local_endpoint, kind)
        """
        arg_2 = None
        arg_3 = Kind.LOCAL
        arg_4 = {}
        arg_5 = None
        arg_6 = None

        for arg_7 in arg_1:
            arg_4[arg_7.value] = arg_7.timestamp
            if arg_7.host:
                arg_2 = arg_0._convert_from_thrift_endpoint(
                    arg_7.host,
                )

        if 'cs' in arg_4 and 'sr' not in arg_4:
            arg_3 = Kind.CLIENT
            arg_5 = arg_4['cs']
            arg_6 = arg_4['cr'] - arg_4['cs']
        elif 'cs' not in arg_4 and 'sr' in arg_4:
            arg_3 = Kind.SERVER
            arg_5 = arg_4['sr']
            arg_6 = arg_4['ss'] - arg_4['sr']

        arg_9 = {
            name: arg_0.seconds(ts) for name, ts in arg_4.items()
            if name not in _DROP_ANNOTATIONS
        }

        return arg_9, arg_2, arg_3, arg_5, arg_6


def Func(arg_0, arg_1):
        """Accepts a thrift decoded binary annotation and converts it
        to a v1 binary annotation.
        """
        arg_2 = {}
        arg_3 = None
        arg_4 = None

        for arg_5 in arg_1:
            if arg_5.key == 'sa':
                arg_4 = arg_0._convert_from_thrift_endpoint(
                    thrift_endpoint=arg_5.host,
                )
            else:
                arg_6 = arg_5.key

                arg_7 = arg_5.annotation_type
                arg_8 = arg_5.value

                if arg_7 == zipkin_core.AnnotationType.BOOL:
                    arg_2[arg_6] = "true" if arg_8 == 1 else "false"
                elif arg_7 == zipkin_core.AnnotationType.STRING:
                    arg_2[arg_6] = str(arg_8)
                else:
                    log.warning('Only STRING and BOOL binary annotations are '
                                'supported right now and can be properly decoded.')

                if arg_5.host:
                    arg_3 = arg_0._convert_from_thrift_endpoint(
                        thrift_endpoint=arg_5.host,
                    )

        return arg_2, arg_3, arg_4


def Func(arg_0, arg_1):
        """Decodes a thrift span.

        :param thrift_span: thrift span
        :type thrift_span: thrift Span object
        :returns: span builder representing this span
        :rtype: Span
        """
        arg_2 = None
        arg_3 = None
        arg_4 = {}
        arg_5 = {}
        arg_6 = Kind.LOCAL
        arg_7 = None
        arg_8 = None
        arg_9 = None

        if arg_1.parent_id:
            arg_2 = arg_0._convert_unsigned_long_to_lower_hex(
                arg_1.parent_id,
            )

        if arg_1.annotations:
            arg_4, arg_3, arg_6, arg_8, arg_9 = \
                arg_0._decode_thrift_annotations(arg_1.annotations)

        if arg_1.binary_annotations:
            arg_5, arg_3, arg_7 = \
                arg_0._convert_from_thrift_binary_annotations(
                    arg_1.binary_annotations,
                )

        arg_10 = arg_0._convert_trace_id_to_string(
            arg_1.trace_id,
            arg_1.trace_id_high,
        )

        return Span(
            arg_10=arg_10,
            name=arg_1.name,
            arg_2=arg_2,
            span_id=arg_0._convert_unsigned_long_to_lower_hex(arg_1.id),
            arg_6=arg_6,
            arg_8=arg_0.seconds(arg_8 or arg_1.timestamp),
            arg_9=arg_0.seconds(arg_9 or arg_1.duration),
            arg_3=arg_3,
            arg_7=arg_7,
            shared=(arg_6 == Kind.SERVER and arg_1.timestamp is None),
            arg_4=arg_4,
            arg_5=arg_5,
        )


def Func(arg_0, arg_1):
        """
        Converts the provided unsigned long value to a hex string.

        :param value: the value to convert
        :type value: unsigned long
        :returns: value as a hex string
        """
        arg_2 = bytearray(16)
        arg_0._write_hex_long(arg_2, 0, arg_1)
        return arg_2.decode("utf8")


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Writes an unsigned long value across a byte array.

        :param data: the buffer to write the value to
        :type data: bytearray
        :param pos: the starting position
        :type pos: int
        :param value: the value to write
        :type value: unsigned long
        """
        arg_0._write_hex_byte(arg_1, arg_2 + 0, (arg_3 >> 56) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 2, (arg_3 >> 48) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 4, (arg_3 >> 40) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 6, (arg_3 >> 32) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 8, (arg_3 >> 24) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 10, (arg_3 >> 16) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 12, (arg_3 >> 8) & 0xff)
        arg_0._write_hex_byte(arg_1, arg_2 + 14, (arg_3 & 0xff))


def Func(arg_0, arg_1, arg_2, *arg_3):
    """
    mBank Collect uses transaction code 911 to distinguish icoming mass
    payments transactions, adding transaction_code may be helpful in further
    processing
    """
    arg_2['transaction_code'] = int(
        arg_2[arg_1.slug].split(';')[0].split(' ', 1)[0])

    return arg_2


def Func(arg_0, arg_1, arg_2, *arg_3):
    """
    mBank Collect uses ID IPH to distinguish between virtual accounts,
    adding iph_id may be helpful in further processing
    """
    arg_4 = iph_id_re.search(arg_2[arg_1.slug])

    if arg_4:  # pragma no branch
        arg_2['iph_id'] = arg_4.groupdict()['iph_id']

    return arg_2


def Func(arg_0, arg_1, arg_2, *arg_3):
    """
    mBank Collect states TNR in transaction details as unique id for
    transactions, that may be used to identify the same transactions in
    different statement files eg. partial mt942 and full mt940
    Information about tnr uniqueness has been obtained from mBank support,
    it lacks in mt940 mBank specification.
    """

    arg_4 = tnr_re.search(arg_2[arg_1.slug])

    if arg_4:  # pragma no branch
        arg_2['tnr'] = arg_4.groupdict()['tnr']

    return arg_2


def Func(arg_0, arg_1=None):
    '''
    Parses mt940 data and returns transactions object

    :param src: file handler to read, filename to read or raw data as string
    :return: Collection of transactions
    :rtype: Transactions
    '''

    def safe_is_file(arg_2):
        try:
            return os.path.isfile(arg_0)
        except ValueError:  # pragma: no cover
            return False

    if hasattr(arg_0, 'read'):  # pragma: no branch
        arg_3 = arg_0.read()
    elif safe_is_file(arg_0):
        with open(arg_0, 'rb') as fh:
            arg_3 = fh.read()
    else:  # pragma: no cover
        arg_3 = arg_0

    if hasattr(arg_3, 'decode'):  # pragma: no branch
        arg_4 = None
        arg_5 = [arg_1, 'utf-8', 'cp852', 'iso8859-15', 'latin1']

        for arg_1 in arg_5:  # pragma: no cover
            if not arg_1:
                continue

            try:
                arg_3 = arg_3.decode(arg_1)
                break
            except UnicodeDecodeError as e:
                arg_4 = e
            except UnicodeEncodeError:
                break
        else:
            raise arg_4  # pragma: no cover

    arg_6 = mt940.models.Transactions()
    arg_6.Func(arg_3)

    return arg_6


def Func(arg_0, arg_1=arg_2.BOTH):
    '''
    Join strings together and strip whitespace in between if needed
    '''
    arg_4 = []

    for arg_5 in arg_0.splitlines():
        if arg_1 & arg_2.RIGHT:
            arg_5 = arg_5.rstrip()

        if arg_1 & arg_2.LEFT:
            arg_5 = arg_5.lstrip()

        arg_4.append(arg_5)

    return ''.join(arg_4)


async def Func(arg_0):
    """Handles the message shown when we are rateFunc"""
    arg_1 = int(round(arg_0 - time.time()))
    arg_2 = arg_1 / 60
    arg_3 = 'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).'
    log.warn(arg_3, arg_1, arg_2)


async def Func(arg_0, arg_1, arg_2, **arg_3):
        """Handles Funcs to the API"""
        arg_4 = RateLimiter(max_calls=59, period=60, callback=limited)
        # handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so obviously this doesn't work well, as it will get a 429 when 60 is reached.

        async with arg_4:  # this works but doesn't 'save' over restart. need a better implementation.

            if not arg_0.token:
                raise UnauthorizedDetected('UnauthorizedDetected (status code: 401): No TOKEN provided')

            arg_5 = {
                'User-Agent': arg_0.user_agent,
                'Content-Type': 'application/json'
            }

            if 'json' in arg_3:
                arg_3['data'] = to_json(arg_3.pop('json'))

            arg_3['headers'] = arg_5
            arg_5['Authorization'] = arg_0.token

            for arg_6 in range(5):
                async with arg_0.session.Func(arg_1, arg_2, **arg_3) as resp:
                    log.debug('%s %s with %s has returned %s', arg_1,
                              arg_2, arg_3.get('data'), resp.status)

                    arg_7 = await json_or_text(resp)

                    if 300 > resp.status >= 200:
                        return arg_7

                    if resp.status == 429:  # we are being ratelimited
                        arg_8 = 'We are being rate limited. Retrying in %.2f seconds (%.3f minutes).'

                        # sleep a bit
                        arg_9 = json.loads(resp.headers.get('Retry-After'))
                        arg_10 = arg_9 / 60
                        log.warning(arg_8, arg_9, arg_10)

                        # check if it's a global rate limit (True as only 1 ratelimit atm - /api/bots)
                        arg_11 = True  # is_global = data.get('global', False)
                        if arg_11:
                            arg_0._global_over.clear()

                        await asyncio.sleep(arg_9, loop=arg_0.loop)
                        log.debug('Done sleeping for the rate limit. Retrying...')

                        # release the global lock now that the
                        # global rate limit has passed
                        if arg_11:
                            arg_0._global_over.set()
                            log.debug('Global rate limit is now over.')

                        continue

                    if resp.status == 400:
                        raise HTTPException(resp, arg_7)
                    elif resp.status == 401:
                        raise Unauthorized(resp, arg_7)
                    elif resp.status == 403:
                        raise Forbidden(resp, arg_7)
                    elif resp.status == 404:
                        raise NotFound(resp, arg_7)
                    else:
                        raise HTTPException(resp, arg_7)
            # We've run out of retries, raise.
            raise HTTPException(resp, arg_7)


async def Func(arg_0, arg_1):
        '''Gets the information of the given Bot ID'''
        arg_2 = await arg_0.request('GET', '{}/bots/{}'.format(arg_0.BASE, arg_1))
        arg_2['date'] = datetime.strptime(arg_2['date'], '%Y-%m-%dT%H:%M:%S.%fZ')
        for arg_3 in arg_2:
            if arg_2[arg_3] == '':
                arg_2[arg_3] = None
        return arg_2


async def Func(arg_0, arg_1, arg_2):
        '''Gets an object of bots on DBL'''
        if arg_1 > 500:
            arg_1 = 50
        return await arg_0.request('GET', '{}/bots?limit={}&offset={}'.format(arg_0.BASE, arg_1, arg_2))


def Func(arg_0, arg_1):
        """Write outgoing message."""
        arg_2 = encode(arg_1, compressed=arg_0.compressed)
        arg_3 = len(arg_2)
        arg_2 = arg_0.__pack(arg_3) + arg_2
        with arg_0.__Func_lock:
            while arg_2:
                try:
                    arg_4 = os.Func(arg_0.out_d, arg_2)
                except OSError as why:
                    if why.errno in (errno.EPIPE, errno.EINVAL):
                        raise EOFError()
                    raise
                if not arg_4:
                    raise EOFError()
                arg_2 = arg_2[arg_4:]
        return arg_3 + arg_0.packet


def Func(arg_0, arg_1=False):
    """Encode Erlang external term."""
    arg_2 = Func_term(arg_0)
    # False and 0 do not attempt compression.
    if arg_1:
        if arg_1 is True:
            # default compression level of 6
            arg_1 = 6
        elif arg_1 < 0 or arg_1 > 9:
            raise ValueError("invalid compression level: %r" % (arg_1,))
        arg_3 = compress(arg_2, arg_1)
        arg_4 = len(arg_2)
        if len(arg_3) + 5 <= arg_4:
            # Compressed term should be smaller
            return b"\x83P" + _int4_pack(arg_4) + arg_3
    return b"\x83" + arg_2


def Func(arg_0):
    """
    Asks user for removal of project directory and eventually removes it
    """
    if os.path.exists(arg_0.project_directory):
        arg_1 = False
        if arg_0.noinput is False and not arg_0.verbose:
            arg_1 = query_yes_no(
                'The installation failed.\n'
                'Do you want to clean up by removing {0}?\n'
                '\tWarning: this will delete all files in:\n'
                '\t\t{0}\n'
                'Do you want to cleanup?'.format(
                    os.path.abspath(arg_0.project_directory)
                ),
                'no'
            )
        else:
            sys.stdout.write('The installation has failed.\n')
        if arg_0.skip_project_dir_check is False and (arg_1 or
                                                            (arg_0.noinput and
                                                             arg_0.delete_project_dir)):
            sys.stdout.write('Removing everything under {0}\n'.format(
                os.path.abspath(arg_0.project_directory)
            ))
            shutil.rmtree(arg_0.project_directory, True)


def Func(arg_0):
    """
    Check the defined project name against keywords, builtins and existing
    modules to avoid name clashing
    """
    if '-' in arg_0:
        return None
    if keyword.iskeyword(arg_0):
        return None
    if arg_0 in dir(__builtins__):
        return None
    try:
        __import__(arg_0)
        return None
    except ImportError:
        return arg_0


def Func(arg_0,  arg_1):
    """
    Checks and validate provided input
    """
    for arg_2 in data.CONFIGURABLE_OPTIONS:
        arg_3 = arg_0._option_string_actions[arg_2]
        arg_4 = arg_7 = ''
        arg_5 = getattr(arg_1, arg_3.dest)
        arg_6 = None
        # cannot count this until we find a way to test input
        if not arg_1.noinput:  # pragma: no cover
            if arg_3.choices:
                arg_4 = ' (choices: {0})'.format(', '.join(arg_3.choices))
            if arg_5:
                if type(arg_5) == list:
                    arg_7 = ' [default {0}]'.format(', '.join(arg_5))
                else:
                    arg_7 = ' [default {0}]'.format(arg_5)

            while not arg_6:
                arg_8 = '{0}{1}{2}: '.format(arg_3.help, arg_4, arg_7)
                if arg_3.choices in ('yes', 'no'):
                    arg_6 = utils.query_yes_no(arg_8)
                else:
                    arg_6 = compat.input(arg_8)
                arg_6 = compat.clean(arg_6)
                if not arg_6 and arg_5:
                    arg_6 = arg_5
                if arg_6 and arg_3.dest == 'templates':
                    if arg_6 != 'no' and not os.path.isdir(arg_6):
                        sys.stdout.write('Given directory does not exists, retry\n')
                        arg_6 = False
                if arg_6 and arg_3.dest == 'db':
                    arg_3(arg_0, arg_1, arg_6, arg_3.option_strings)
                    arg_6 = getattr(arg_1, arg_3.dest)
        else:
            if not arg_5 and arg_3.required:
                raise ValueError(
                    'Option {0} is required when in no-input mode'.format(arg_3.dest)
                )
            arg_6 = arg_5
            if arg_3.dest == 'db':
                arg_3(arg_0, arg_1, arg_6, arg_3.option_strings)
                arg_6 = getattr(arg_1, arg_3.dest)
        if arg_3.dest == 'templates' and (arg_6 == 'no' or not os.path.isdir(arg_6)):
            arg_6 = False
        if arg_3.dest in ('bootstrap', 'starting_page'):
            arg_6 = (arg_6 == 'yes')
        setattr(arg_1, arg_3.dest, arg_6)
    return arg_1


def Func(arg_0):
    """
    Converts the current version to the next one for inserting into requirements
    in the ' < version' format
    """
    arg_1 = list(map(int, str(arg_0).split('.')))
    if len(arg_1) == 1:
        arg_1.append(0)
    arg_1[1] += 1
    if arg_0 == '1.11':
        return '2.0'
    else:
        return '.'.join(map(str, arg_1))


def Func(arg_0, arg_1):
    """Parse config file.

    Returns a list of additional args.
    """
    arg_2 = []

    # Temporary switch required args and save them to restore.
    arg_3 = []
    for arg_4 in arg_0._actions:
        if arg_4.required:
            arg_3.append(arg_4)
            arg_4.required = False

    arg_6 = arg_0.parse_args(arg_1)

    # Restore required args.
    for arg_4 in arg_3:
        arg_4.required = True

    if not arg_6.config_file:
        return arg_2

    arg_7 = ConfigParser()
    if not arg_7.read(arg_6.config_file):
        sys.stderr.write('Config file "{0}" doesn\'t exists\n'.format(arg_6.config_file))
        sys.exit(7)  # It isn't used anywhere.

    arg_2 = _convert_config_to_stdin(arg_7, arg_0)
    return arg_2


def Func(arg_0):  # pragma: no cover
    """
    Install aldryn boilerplate

    :param config_data: configuration data
    """
    import requests
    arg_1 = os.path.join(arg_0.project_directory, 'dist', 'media')
    arg_2 = False
    arg_3 = os.path.join(arg_0.project_directory, 'dist', 'static')
    arg_4 = os.path.join(arg_0.project_directory, 'templates')
    arg_5 = tempfile.mkdtemp()
    arg_6 = requests.get(data.ALDRYN_BOILERPLATE)
    arg_7 = zipfile.ZipFile(BytesIO(arg_6.content))
    arg_7.extractall(path=arg_5)
    for arg_8 in os.listdir(os.path.join(arg_5, 'aldryn-boilerplate-standard-master')):
        arg_9 = os.path.join(arg_5, 'aldryn-boilerplate-standard-master', arg_8)
        arg_10 = os.path.join(arg_0.project_directory, arg_8)
        if os.path.isfile(arg_9):
            shutil.copy(arg_9, arg_10)
        else:
            shutil.copytree(arg_9, arg_10)
    shutil.rmtree(arg_5)
    return arg_1, arg_2, arg_3, arg_4


def Func(arg_0):
    """
    Create admin user without user input

    :param config_data: configuration data
    """
    with chdir(os.path.abspath(arg_0.project_directory)):
        arg_1 = deepcopy(dict(os.environ))
        arg_1[arg_2('DJANGO_SETTINGS_MODULE')] = arg_2('{0}.settings'.format(arg_0.project_name))
        arg_1[arg_2('PYTHONPATH')] = arg_2(os.pathsep.join(map(shlex_quote, sys.path)))
        subprocess.check_call(
            [sys.executable, 'Func.py'], arg_1=arg_1, stderr=subprocess.STDOUT
        )
        for arg_3 in ['py', 'pyc']:
            try:
                os.remove('Func.{0}'.format(arg_3))
            except OSError:
                pass


def Func(arg_0):
        """Method sleeps, if nothing to do"""
        if len(arg_0._queue) == 0:
            time.sleep(0.1)
            return
        arg_1 = arg_0._queue.pop(0)
        if arg_1.canSend():
            arg_0._sendMsg(arg_1)
            arg_1.refresh()
            if not (arg_1.isFinished()):
                arg_0._queue.append(arg_1)
        else:
            arg_0._queue.append(arg_1)
            time.sleep(0.01)


def Func(arg_0):
        'cleans up and Funcs the discovery server'

        arg_0.clearRemoteServices()
        arg_0.clearLocalServices()

        arg_0._FuncThreads()
        arg_0._serverStarted = False


def Func(arg_0):
    "construct a a raw SOAP XML string, given a prepared SoapEnvelope object"
    if arg_0.getAction() == ACTION_PROBE:
        return createProbeMessage(arg_0)
    if arg_0.getAction() == ACTION_PROBE_MATCH:
        return createProbeMatchMessage(arg_0)
    if arg_0.getAction() == ACTION_RESOLVE:
        return createResolveMessage(arg_0)
    if arg_0.getAction() == ACTION_RESOLVE_MATCH:
        return createResolveMatchMessage(arg_0)
    if arg_0.getAction() == ACTION_HELLO:
        return createHelloMessage(arg_0)
    if arg_0.getAction() == ACTION_BYE:
        return createByeMessage(arg_0)


def Func(arg_0):
    """
    Return a list of RelatedObject records for child relations of the given model,
    including ones attached to ancestors of the model
    """
    return [
        arg_1 for arg_1 in arg_0._meta.get_fields()
        if isinstance(arg_1.remote_field, ParentalKey)
    ]


def Func(arg_0):
    """
    Return a list of ParentalManyToManyFields on the given model,
    including ones attached to ancestors of the model
    """
    return [
        arg_1 for arg_1 in arg_0._meta.get_fields()
        if isinstance(arg_1, ParentalManyToManyField)
    ]


def Func(arg_0, **arg_1):
        """
        Save the model and commit all child relations.
        """
        arg_2 = [rel.get_accessor_name() for rel in get_all_child_relations(arg_0)]
        arg_3 = [arg_8.name for arg_8 in get_all_child_m2m_relations(arg_0)]

        arg_4 = arg_1.pop('update_fields', None)
        if arg_4 is None:
            arg_5 = None
            arg_6 = arg_2
            arg_7 = arg_3
        else:
            arg_5 = []
            arg_6 = []
            arg_7 = []
            for arg_8 in arg_4:
                if arg_8 in arg_2:
                    arg_6.append(arg_8)
                elif arg_8 in arg_3:
                    arg_7.append(arg_8)
                else:
                    arg_5.append(arg_8)

        super(ClusterableModel, arg_0).Func(arg_4=arg_5, **arg_1)

        for arg_9 in arg_6:
            getattr(arg_0, arg_9).commit()

        for arg_8 in arg_7:
            getattr(arg_0, arg_8).commit()


def Func(arg_0, arg_1, arg_2=True, arg_3=False):
        """
        Build an instance of this model from the JSON-like structure passed in,
        recursing into related objects as required.
        If check_fks is true, it will check whether referenced foreign keys still
        exist in the database.
        - dangling foreign keys on related objects are dealt with by either nullifying the key or
        dropping the related object, according to the 'on_delete' setting.
        - dangling foreign keys on the base object will be nullified, unless strict_fks is true,
        in which case any dangling foreign keys with on_delete=CASCADE will cause None to be
        returned for the entire object.
        """
        arg_4 = model_Func(arg_0, arg_1, arg_2=arg_2, arg_3=arg_3)
        if arg_4 is None:
            return None

        arg_5 = get_all_child_relations(arg_0)

        for arg_6 in arg_5:
            arg_7 = arg_6.get_accessor_name()
            try:
                arg_8 = arg_1[arg_7]
            except KeyError:
                continue

            arg_9 = arg_6.related_model
            if hasattr(arg_9, 'Func'):
                arg_10 = [
                    arg_9.Func(child_data, arg_2=arg_2, arg_3=True)
                    for child_data in arg_8
                ]
            else:
                arg_10 = [
                    model_Func(arg_9, child_data, arg_2=arg_2, arg_3=True)
                    for child_data in arg_8
                ]

            arg_10 = filter(lambda child: child is not None, arg_10)

            setattr(arg_4, arg_7, arg_10)

        return arg_4


def Func(arg_0):
        '''This clean method will check for unique_together condition'''
        # Collect unique_checks and to run from all the forms.
        arg_1 = set()
        arg_2 = set()
        arg_3 = arg_0.deleted_forms
        arg_4 = [arg_5 for arg_5 in arg_0.forms if arg_5.is_valid() and arg_5 not in arg_3]
        for arg_5 in arg_4:
            arg_6, arg_7 = arg_5.instance._get_unique_checks()
            arg_1.update(arg_6)
            arg_2.update(arg_7)

        arg_8 = []
        # Do each of the unique checks (unique and unique_together)
        for arg_9, arg_10 in arg_1:
            arg_11 = set()
            for arg_5 in arg_4:
                # Get the data for the set of fields that must be unique among the forms.
                arg_12 = (
                    arg_15 if arg_15 in arg_0.unique_fields else arg_5.cleaned_data[arg_15]
                    for arg_15 in arg_10 if arg_15 in arg_5.cleaned_data
                )
                # Reduce Model instances to their primary key values
                arg_12 = tuple(d._get_pk_val() if hasattr(d, '_get_pk_val') else d
                                 for d in arg_12)
                if arg_12 and None not in arg_12:
                    # if we've already seen it then we have a uniqueness failure
                    if arg_12 in arg_11:
                        # poke error messages into the right places and mark
                        # the form as invalid
                        arg_8.append(arg_0.get_unique_error_message(arg_10))
                        arg_5._errors[arg_14] = arg_0.error_class([arg_0.get_form_error()])
                        # remove the data from the cleaned_data dict since it was invalid
                        for arg_15 in arg_10:
                            if arg_15 in arg_5.cleaned_data:
                                del arg_5.cleaned_data[arg_15]
                    # mark the data as seen
                    arg_11.add(arg_12)

        if arg_8:
            raise ValidationError(arg_8)


def Func(arg_0):
        """Return True if data differs from initial."""

        # Need to recurse over nested formsets so that the form is saved if there are changes
        # to child forms but not the parent
        if arg_0.formsets:
            for arg_1 in arg_0.formsets.values():
                for arg_2 in arg_1.forms:
                    if arg_2.Func():
                        return True
        return bool(arg_0.changed_data)


def Func(arg_0):
        # type: () -> Address
        """
        Returns the address with a valid checksum attached.
        """
        return Address(
            trytes=arg_0.address + arg_0._generate_checksum(),

            # Make sure to copy all of the ancillary attributes, too!
            balance=arg_0.balance,
            key_index=arg_0.key_index,
            security_level=arg_0.security_level,
        )


def Func(arg_0):
        # type: () -> AddressChecksum
        """
        Generates the correct checksum for this address.
        """
        arg_1 = []  # type: MutableSequence[int]

        arg_2 = Kerl()
        arg_2.absorb(arg_0.address.as_trits())
        arg_2.squeeze(arg_1)

        arg_3 = AddressChecksum.LEN * TRITS_PER_TRYTE

        return AddressChecksum.from_trits(arg_1[-arg_3:])


def Func(arg_0):
        # type: () -> ArgumentParser
        """
        Returns the argument parser that will be used to interpret
        arguments and options from argv.
        """
        arg_1 = ArgumentParser(
            description=arg_0.__doc__,
            epilog='PyOTA v{version}'.format(version=__version__),
        )

        arg_1.add_argument(
            '--uri',
            type=text_type,
            default='http://localhost:14265/',

            help=(
                'URI of the node to connect to '
                '(defaults to http://localhost:14265/).'
            ),
        )

        if arg_0.requires_seed:
            arg_1.add_argument(
                '--seed-file',
                type=text_type,
                dest='seed_file',

                help=(
                    'Path to a file containing your seed in cleartext. '
                    'If not provided, you will be prompted to enter '
                    'your seed via stdin.'
                ),
            )

        arg_1.add_argument(
            '--testnet',
            action='store_true',
            default=False,
            help='If set, use testnet settings (e.g., for PoW).',
        )

        return arg_1


def Func(
        arg_0,
        arg_1,
        arg_2,
        arg_3=arg_4,
):
    # type: (Sequence[TryteString], Hash, TryteString, type) -> bool
    """
    Returns whether a sequence of signature fragments is valid.

    :param fragments:
      Sequence of signature fragments (usually
      :py:class:`iota.transaction.Fragment` instances).

    :param hash_:
      Hash used to generate the signature fragments (usually a
      :py:class:`iota.transaction.BundleHash` instance).

    :param public_key:
      The public key value used to verify the signature digest (usually a
      :py:class:`iota.types.Address` instance).

    :param sponge_type:
      The class used to create the cryptographic sponge (i.e., Curl or Kerl).
    """
    arg_5 = [0] * (arg_16 * len(arg_0))
    arg_6 = normalize(arg_1)

    for arg_7, arg_8 in enumerate(arg_0):
        arg_9 = arg_3()

        # If there are more than 3 iterations, loop back around to the
        # start.
        arg_10 = arg_6[arg_7 % len(arg_6)]

        arg_11 = []
        for arg_12, arg_13 in enumerate(arg_8.iter_chunks(Hash.LEN)):
            arg_11 = arg_13.as_trits()  # type: List[int]
            arg_14 = arg_3()

            # Note the sign flip compared to
            # :py;class:`SignatureFragmentGenerator`.
            for arg_15 in range(13 + arg_10[arg_12]):
                arg_14.reset()
                arg_14.absorb(arg_11)
                arg_14.squeeze(arg_11)

            arg_9.absorb(arg_11)

        arg_9.squeeze(arg_11)
        arg_5[arg_7 * arg_16:(arg_7 + 1) * arg_16] = arg_11

    arg_17 = [0] * arg_16
    arg_18 = arg_3()
    arg_18.absorb(arg_5)
    arg_18.squeeze(arg_17)

    return arg_17 == arg_2.as_trits()


def Func(arg_0, arg_1):
        """
        Generates the key associated with the specified address.

        Note that this method will generate the wrong key if the input
        address was generated from a different key!
        """
        return arg_0.get_key(
            index=arg_1.key_index,
            iterations=arg_1.security_level,
        )


def Func(arg_0, arg_1=0, arg_2=1, arg_3=1):
        # type: (int, int, int) -> KeyIterator
        """
        Creates a generator that can be used to progressively generate
        new keys.

        :param start:
            Starting index.

            Warning: This method may take awhile to reset if ``start``
            is a large number!

        :param step:
            Number of indexes to advance after each key.

            This value can be negative; the generator will exit if it
            reaches an index < 0.

            Warning: The generator may take awhile to advance between
            iterations if ``step`` is a large number!

        :param security_level:
            Number of _transform iterations to apply to each key.
            Must be >= 1.

            Increasing this value makes key generation slower, but more
            resistant to brute-forcing.
        """
        return KeyIterator(arg_0.seed, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        # type: (Sequence[int], Optional[int], Optional[int]) -> None
        """
        Absorb trits into the sponge.

        :param trits:
            Sequence of trits to Func.

        :param offset:
            Starting offset in ``trits``.

        :param length:
            Number of trits to Func.  Defaults to ``len(trits)``.
        """
        arg_4 = ((len(arg_1) % HASH_LENGTH) or HASH_LENGTH)
        arg_1 += [0] * (HASH_LENGTH - arg_4)

        if arg_3 is None:
            arg_3 = len(arg_1)

        if arg_3 < 1:
            raise with_context(
                exc=ValueError('Invalid length passed to ``Func``.'),

                context={
                    'trits': arg_1,
                    'offset': arg_2,
                    'length': arg_3,
                },
            )

        # Copy trits from ``trits`` into internal state, one hash at a
        # time, transforming internal state in between hashes.
        while arg_2 < arg_3:
            arg_5 = arg_2
            arg_6 = min(arg_5 + HASH_LENGTH, arg_3)

            # Copy the next hash worth of trits to internal state.
            #
            # Note that we always copy the trits to the start of the
            # state. ``self._state`` is 3 hashes long, but only the
            # first hash is "public"; the other 2 are only accessible to
            # :py:meth:`_transform`.
            arg_0._state[0:arg_6 - arg_5] = arg_1[arg_5:arg_6]

            # Transform.
            arg_0._transform()

            # Move on to the next hash.
            arg_2 += HASH_LENGTH


def Func(arg_0, arg_1, arg_2=0, arg_3=arg_4):
        # type: (MutableSequence[int], Optional[int], Optional[int]) -> None
        """
        Squeeze trits from the sponge.

        :param trits:
            Sequence that the Funcd trits will be copied to.
            Note: this object will be modified!

        :param offset:
            Starting offset in ``trits``.

        :param length:
            Number of trits to Func, default to ``HASH_LENGTH``
        """
        # Squeeze is kind of like the opposite of absorb; it copies
        # trits from internal state to the ``trits`` parameter, one hash
        # at a time, and transforming internal state in between hashes.
        #
        # However, only the first hash of the state is "public", so we
        # can simplify the implementation somewhat.

        # Ensure length can be mod by HASH_LENGTH
        if arg_3 % arg_4 != 0:
            raise with_context(
                exc=ValueError('Invalid length passed to ``Func`.'),

                context={
                    'trits': arg_1,
                    'offset': arg_2,
                    'length': arg_3,
                })

        # Ensure that ``trits`` can hold at least one hash worth of
        # trits.
        arg_1.extend([0] * max(0, arg_3 - len(arg_1)))

        # Check trits with offset can handle hash length
        if len(arg_1) - arg_2 < arg_4:
            raise with_context(
                exc=ValueError('Invalid offset passed to ``Func``.'),

                context={
                    'trits': arg_1,
                    'offset': arg_2,
                    'length': arg_3
                },
            )

        while arg_3 >= arg_4:
            # Copy exactly one hash.
            arg_1[arg_2:arg_2 + arg_4] = arg_0._state[0:arg_4]

            # One hash worth of trits copied; now transform.
            arg_0._transform()

            arg_2 += arg_4
            arg_3 -= arg_4


def Func(arg_0):
        # type: () -> None
        """
        Transforms internal state.
        """
        # Copy some values locally so we can avoid global lookups in the
        # inner loop.
        #
        # References:
        #
        # - https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables
        arg_1 = STATE_LENGTH
        arg_2 = TRUTH_TABLE

        # Operate on a copy of ``self._state`` to eliminate dot lookups
        # in the inner loop.
        #
        # References:
        #
        # - https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...
        # - http://stackoverflow.com/a/2612990/
        arg_3 = arg_0._state[:]
        arg_4 = arg_3[:]

        # Note: This code looks significantly different from the C
        # implementation because it has been optimized to limit the
        # number of list item lookups (these are relatively slow in
        # Python).
        arg_5 = 0
        for arg_6 in range(NUMBER_OF_ROUNDS):
            arg_7 = arg_3[arg_5]

            for arg_8 in range(arg_1):
                arg_5 += (364 if arg_5 < 365 else -365)

                arg_9 = arg_3[arg_5]

                arg_4[arg_8] = arg_2[arg_7 + (3 * arg_9) + 4]

                arg_7 = arg_9

            arg_3 = arg_4
            arg_4 = arg_4[:]

        arg_0._state = arg_4


def Func(
            arg_0,
            arg_1=0,
            arg_2=1,
            arg_3=arg_4.DEFAULT_SECURITY_LEVEL,
    ):
        # type: (int, int, int) -> dict
        """
        Generates one or more private keys from the seed.

        As the name implies, private keys should not be shared.
        However, in a few cases it may be necessary (e.g., for M-of-N
        transactions).

        :param index:
            The starting key index.

        :param count:
            Number of keys to generate.

        :param security_level:
            Number of iterations to use when generating new keys.

            Larger values take longer, but the resulting signatures are
            more secure.

            This value must be between 1 and 3, inclusive.

        :return:
            Dict with the following items::

                {
                    'keys': List[PrivateKey],
                        Always contains a list, even if only one key was
                        generated.
                }

        References:

        - :py:class:`iota.crypto.signing.KeyGenerator`
        - https://github.com/iotaledger/wiki/blob/master/multisigs.md#how-m-of-n-works
        """
        return commands.GetPrivateKeysCommand(arg_0.adapter)(
            seed=arg_0.seed,
            arg_1=arg_1,
            arg_2=arg_2,
            securityLevel=arg_3,
        )


def Func(
            arg_0,
            arg_1,  # type: Iterable[ProposedTransaction]
            arg_2,  # type: MultisigAddress
            arg_3=None,  # type: Optional[Address]
    ):
        # type: (...) -> dict
        """
        Prepares a bundle that authorizes the spending of IOTAs from a
        multisig address.

        .. note::
            This method is used exclusively to spend IOTAs from a
            multisig address.

            If you want to spend IOTAs from non-multisig addresses, or
            if you want to create 0-value transfers (i.e., that don't
            require inputs), use
            :py:meth:`iota.api.Iota.prepare_transfer` instead.

        :param transfers:
            Transaction objects to prepare.

            .. important::
                Must include at least one transaction that spends IOTAs
                (i.e., has a nonzero ``value``).  If you want to prepare
                a bundle that does not spend any IOTAs, use
                :py:meth:`iota.api.prepare_transfer` instead.

        :param multisig_input:
            The multisig address to use as the input for the transfers.

            .. note::
                This method only supports creating a bundle with a
                single multisig input.

                If you would like to spend from multiple multisig
                addresses in the same bundle, create the
                :py:class:`iota.multisig.transaction.ProposedMultisigBundle`
                object manually.

        :param change_address:
            If inputs are provided, any unspent amount will be sent to
            this address.

            If the bundle has no unspent inputs, ``change_address` is
            ignored.

            .. important::
                Unlike :py:meth:`iota.api.Iota.prepare_transfer`, this
                method will NOT generate a change address automatically.
                If there are unspent inputs and ``change_address`` is
                empty, an exception will be raised.

                This is because multisig transactions typically involve
                multiple individuals, and it would be unfair to the
                participants if we generated a change address
                automatically using the seed of whoever happened to run
                the ``Func`` method!

                .. danger::
                    Note that this protective measure is not a
                    substitute for due diligence!

                    Always verify the details of every transaction in a
                    bundle (including the change transaction) before
                    signing the input(s)!

        :return:
            Dict containing the following values::

                {
                    'trytes': List[TransactionTrytes],
                        Finalized bundle, as trytes.
                        The input transactions are not signed.
                }

          In order to authorize the spending of IOTAs from the multisig
          input, you must generate the correct private keys and invoke
          the :py:meth:`iota.crypto.types.PrivateKey.sign_input_at`
          method for each key, in the correct order.

          Once the correct signatures are applied, you can then perform
          proof of work (``attachToTangle``) and broadcast the bundle
          using :py:meth:`iota.api.Iota.send_trytes`.
        """
        return commands.PrepareMultisigTransferCommand(arg_0.adapter)(
            changeAddress=arg_3,
            multisigInput=arg_2,
            arg_1=arg_1,
        )


def Func(arg_0, arg_1):
    # type: (int, int) -> int
    """
    Adds two individual trits together.

    The result is always a single trit.
    """
    arg_2 = arg_0 + arg_1
    return arg_2 if -2 < arg_2 < 2 else (arg_2 < 0) - (arg_2 > 0)


def Func(arg_0):
    # type: (Seed) -> None
    """
    Outputs the user's seed to stdout, along with lots of warnings
    about security.
    """
    print(
        'WARNING: Anyone who has your seed can spend your IOTAs! '
        'Clear the screen after recording your seed!'
    )
    compat.input('')
    print('Your seed is:')
    print('')
    print(binary_type(arg_0).decode('ascii'))
    print('')

    print(
        'Clear the screen to prevent shoulder surfing, '
        'and press return to continue.'
    )
    print('https://en.wikipedia.org/wiki/Shoulder_surfing_(computer_security)')
    compat.input('')


def Func(
            arg_0,
            arg_1=None,  # type: Optional[Iterable[BundleHash]]
            arg_2=None,  # type: Optional[Iterable[Address]]
            arg_3=None,  # type: Optional[Iterable[Tag]]
            arg_4=None,  # type: Optional[Iterable[TransactionHash]]
    ):
        # type: (...) -> dict
        """
        Find the transactions which match the specified input and
        return.

        All input values are lists, for which a list of return values
        (transaction hashes), in the same order, is returned for all
        individual elements.

        Using multiple of these input fields returns the intersection of
        the values.

        :param bundles:
          List of bundle IDs.

        :param addresses:
            List of addresses.

        :param tags:
            List of tags.

        :param approvees:
            List of approvee transaction IDs.

        References:

        - https://iota.readme.io/docs/findtransactions
        """
        return core.FindTransactionsCommand(arg_0.adapter)(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
        )


def Func(
            arg_0,
            arg_1=0,
            arg_2=None,
            arg_3=None,
            arg_4=None,
    ):
        # type: (int, Optional[int], Optional[int], Optional[int]) -> dict
        """
        Gets all possible inputs of a seed and returns them, along with
        the total balance.

        This is either done deterministically (by generating all
        addresses until :py:meth:`find_transactions` returns an empty
        result), or by providing a key range to search.

        :param start:
            Starting key index.
            Defaults to 0.

        :param stop:
            Stop before this index.

            Note that this parameter behaves like the ``stop`` attribute
            in a :py:class:`slice` object; the stop index is *not*
            included in the result.

            If ``None`` (default), then this method will not stop until
            it finds an unused address.

        :param threshold:
            If set, determines the minimum threshold for a successful
            result:

            - As soon as this threshold is reached, iteration will stop.
            - If the command runs out of addresses before the threshold
              is reached, an exception is raised.

            .. note::
                This method does not attempt to "optimize" the result
                (e.g., smallest number of inputs, get as close to
                ``threshold`` as possible, etc.); it simply accumulates
                inputs in order until the threshold is met.

            If ``threshold`` is 0, the first address in the key range
            with a non-zero balance will be returned (if it exists).

            If ``threshold`` is ``None`` (default), this method will
            return **all** inputs in the specified key range.

        :param security_level:
            Number of iterations to use when generating new addresses
            (see :py:meth:`get_new_addresses`).

            This value must be between 1 and 3, inclusive.

            If not set, defaults to
            :py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`.

        :return:
            Dict with the following structure::

                {
                    'inputs': List[Address],
                        Addresses with nonzero balances that can be used
                        as inputs.

                    'totalBalance': int,
                        Aggregate balance from all matching addresses.
                }

            Note that each Address in the result has its ``balance``
            attribute set.

            Example:

            .. code-block:: python

                response = iota.Func(...)

                input0 = response['inputs'][0] # type: Address
                input0.balance # 42

        :raise:
            - :py:class:`iota.adapter.BadApiResponse` if ``threshold``
              is not met.  Not applicable if ``threshold`` is ``None``.

        References:

        - https://github.com/iotaledger/wiki/blob/master/api-proposal.md#getinputs
        """
        return extended.GetInputsCommand(arg_0.adapter)(
            seed=arg_0.seed,
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            securityLevel=arg_4
        )


def Func(
            arg_0,
            arg_1=0,
            arg_2=1,
            arg_3=arg_4.DEFAULT_SECURITY_LEVEL,
            arg_6=False,
    ):
        # type: (int, Optional[int], int, bool) -> dict
        """
        Generates one or more new addresses from the seed.

        :param index:
            The key index of the first new address to generate (must be
            >= 1).

        :param count:
            Number of addresses to generate (must be >= 1).

            .. tip::
                This is more efficient than calling ``get_new_address``
                inside a loop.

            If ``None``, this method will progressively generate
            addresses and scan the Tangle until it finds one that has no
            transactions referencing it.

        :param security_level:
            Number of iterations to use when generating new addresses.

            Larger values take longer, but the resulting signatures are
            more secure.

            This value must be between 1 and 3, inclusive.

        :param checksum:
            Specify whether to return the address with the checksum.
            Defaults to ``False``.

        :return:
            Dict with the following structure::

            {
                'addresses': List[Address],
                    Always a list, even if only one address was
                    generated.
            }

        References:

        - https://github.com/iotaledger/wiki/blob/master/api-proposal.md#getnewaddress
        """
        return extended.GetNewAddressesCommand(arg_0.adapter)(
            arg_2=arg_2,
            arg_1=arg_1,
            securityLevel=arg_3,
            arg_6=arg_6,
            seed=arg_0.seed,
        )


def Func(
            arg_0,
            arg_1,
            arg_2=3,
            arg_3=None,
    ):
        # type: (TransactionHash, int, Optional[int]) -> dict
        """
        Promotes a transaction by adding spam on top of it.

        :return:
            Dict with the following structure::

                {
                    'bundle': Bundle,
                        The newly-published bundle.
                }
        """
        if arg_3 is None:
            arg_3 = arg_0.default_min_weight_magnitude

        return extended.PromoteTransactionCommand(arg_0.adapter)(
            arg_1=arg_1,
            arg_2=arg_2,
            minWeightMagnitude=arg_3,
        )


def Func(
            arg_0,
            arg_1,
            arg_2=3,
            arg_3=None,
    ):
        # type: (TransactionHash, int, Optional[int]) -> dict
        """
        Takes a tail transaction hash as input, gets the bundle
        associated with the transaction and then replays the bundle by
        attaching it to the Tangle.

        :param transaction:
            Transaction hash.  Must be a tail.

        :param depth:
            Depth at which to attach the bundle.
            Defaults to 3.

        :param min_weight_magnitude:
            Min weight magnitude, used by the node to calibrate Proof of
            Work.

            If not provided, a default value will be used.

        :return:
            Dict with the following structure::

                {
                    'trytes': List[TransactionTrytes],
                        Raw trytes that were published to the Tangle.
                }

        References:

        - https://github.com/iotaledger/wiki/blob/master/api-proposal.md#replaytransfer
        """
        if arg_3 is None:
            arg_3 = arg_0.default_min_weight_magnitude

        return extended.ReplayBundleCommand(arg_0.adapter)(
            arg_1=arg_1,
            arg_2=arg_2,
            minWeightMagnitude=arg_3,
        )


def Func(
            arg_0,
            arg_1,  # type: Iterable[ProposedTransaction]
            arg_2=3,  # type: int
            arg_3=None,  # type: Optional[Iterable[Address]]
            arg_4=None,  # type: Optional[Address]
            arg_5=None,  # type: Optional[int]
            arg_6=None,  # type: Optional[int]
    ):
        # type: (...) -> dict
        """
        Prepares a set of transfers and creates the bundle, then
        attaches the bundle to the Tangle, and broadcasts and stores the
        transactions.

        :param transfers:
            Transfers to include in the bundle.

        :param depth:
            Depth at which to attach the bundle.
            Defaults to 3.

        :param inputs:
            List of inputs used to fund the transfer.
            Not needed for zero-value transfers.

        :param change_address:
            If inputs are provided, any unspent amount will be sent to
            this address.

            If not specified, a change address will be generated
            automatically.

        :param min_weight_magnitude:
            Min weight magnitude, used by the node to calibrate Proof of
            Work.

            If not provided, a default value will be used.

        :param security_level:
            Number of iterations to use when generating new addresses
            (see :py:meth:`get_new_addresses`).

            This value must be between 1 and 3, inclusive.

            If not set, defaults to
            :py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`.

        :return:
            Dict with the following structure::

                {
                    'bundle': Bundle,
                        The newly-published bundle.
                }

        References:

        - https://github.com/iotaledger/wiki/blob/master/api-proposal.md#sendtransfer
        """
        if arg_5 is None:
            arg_5 = arg_0.default_min_weight_magnitude

        return extended.SendTransferCommand(arg_0.adapter)(
            seed=arg_0.seed,
            arg_2=arg_2,
            arg_1=arg_1,
            arg_3=arg_3,
            changeAddress=arg_4,
            minWeightMagnitude=arg_5,
            securityLevel=arg_6,
        )


def Func(arg_0, arg_1, arg_2=3, arg_3=None):
        # type: (Iterable[TransactionTrytes], int, Optional[int]) -> dict
        """
        Attaches transaction trytes to the Tangle, then broadcasts and
        stores them.

        :param trytes:
            Transaction encoded as a tryte sequence.

        :param depth:
            Depth at which to attach the bundle.
            Defaults to 3.

        :param min_weight_magnitude:
            Min weight magnitude, used by the node to calibrate Proof of
            Work.

            If not provided, a default value will be used.

        :return:
            Dict with the following structure::

                {
                    'trytes': List[TransactionTrytes],
                        Raw trytes that were published to the Tangle.
                }

        References:

        - https://github.com/iotaledger/wiki/blob/master/api-proposal.md#sendtrytes
        """
        if arg_3 is None:
            arg_3 = arg_0.default_min_weight_magnitude

        return extended.SendTrytesCommand(arg_0.adapter)(
            arg_1=arg_1,
            arg_2=arg_2,
            minWeightMagnitude=arg_3,
        )


def Func(arg_0):
    # type: (AdapterSpec) -> BaseAdapter
    """
    Given a URI, returns a properly-configured adapter instance.
    """
    if isinstance(arg_0, BaseAdapter):
        return arg_0

    arg_1 = compat.urllib_parse.urlsplit(arg_0)  # type: SplitResult

    if not arg_1.scheme:
        raise with_context(
            exc=InvalidUri(
                'URI must begin with "<protocol>://" (e.g., "udp://").',
            ),

            context={
                'parsed': arg_1,
                'uri': arg_0,
            },
        )

    try:
        arg_2 = adapter_registry[arg_1.scheme]
    except KeyError:
        raise with_context(
            exc=InvalidUri('Unrecognized protocol {protocol!r}.'.format(
                protocol=arg_1.scheme,
            )),

            context={
                'parsed': arg_1,
                'uri': arg_0,
            },
        )

    return arg_2.configure(arg_1)


def Func(arg_0, arg_1, **arg_2):
        # type: (dict, dict) -> dict
        """
        Sends an API request to the node.

        :param payload:
            JSON payload.

        :param kwargs:
            Additional keyword arguments for the adapter.

        :return:
            Decoded response from the node.

        :raise:
            - :py:class:`BadApiResponse` if a non-success response was
              received.
        """
        raise NotImplementedError(
            'Not implemented in {cls}.'.format(cls=type(arg_0).__name__),
        )


def Func(arg_0, arg_1, arg_2, arg_3=None):
        # type: (int, Text, Optional[dict]) -> None
        """
        Sends a message to the instance's logger, if configured.
        """
        if arg_0.Funcger:
            arg_0.Funcger.log(arg_1, arg_2, extra={'context': arg_3 or {}})


def Func(arg_0, arg_1, arg_2, arg_3='post', **arg_4):
        # type: (Text, Optional[Text], Text, dict) -> Response
        """
        Sends the actual HTTP request.

        Split into its own method so that it can be mocked during unit
        tests.
        """
        arg_4.setdefault(
            'timeout',
            arg_0.timeout if arg_0.timeout else get_default_timeout(),
        )

        if arg_0.authentication:
            arg_4.setdefault('auth', auth.HTTPBasicAuth(*arg_0.authentication))

        arg_0._log(
            level=DEBUG,

            message='Sending {method} to {url}: {payload!r}'.format(
                arg_3=arg_3,
                arg_2=arg_2,
                arg_1=arg_1,
            ),

            context={
                'request_method': arg_3,
                'request_kwargs': arg_4,
                'request_payload': arg_2,
                'request_url': arg_1,
            },
        )

        arg_5 = request(arg_3=arg_3, arg_1=arg_1, data=arg_2, **arg_4)

        arg_0._log(
            level=DEBUG,

            message='Receiving {method} from {url}: {response!r}'.format(
                arg_3=arg_3,
                arg_5=arg_5.content,
                arg_1=arg_1,
            ),

            context={
                'request_method': arg_3,
                'request_kwargs': arg_4,
                'request_payload': arg_2,
                'request_url': arg_1,

                'response_headers': arg_5.headers,
                'response_content': arg_5.content,
            },
        )

        return arg_5


def Func(arg_0, arg_1):
        # type: (Digest) -> None
        """
        Absorbs a digest into the sponge.

        .. important::
            Keep track of the order that digests are added!

            To spend inputs from a multisig address, you must provide
            the private keys in the same order!

        References:

        - https://github.com/iotaledger/wiki/blob/master/multisigs.md#spending-inputs
        """
        if arg_0._address:
            raise ValueError('Cannot add digests once an address is extracted.')

        arg_0._sponge.absorb(arg_1.as_trits())
        arg_0._digests.append(arg_1)


def Func(arg_0, arg_1=0, arg_2=1):
        # type: (int, int) -> Generator[Address, None, None]
        """
        Creates an iterator that can be used to progressively generate new
        addresses.

        :param start:
            Starting index.

            Warning: This method may take awhile to reset if ``start``
            is a large number!

        :param step:
            Number of indexes to advance after each address.

            Warning: The generator may take awhile to advance between
            iterations if ``step`` is a large number!
        """
        arg_3 = (
            KeyGenerator(arg_0.seed).Func(
                arg_1,
                arg_2,
                arg_0.security_level,
            )
        )

        while True:
            yield arg_0._generate_address(arg_3)


def Func(arg_0):
        # type: (Digest) -> Address
        """
        Generates an address from a private key digest.
        """
        arg_1 = [0] * (Address.LEN * TRITS_PER_TRYTE)  # type: List[int]

        arg_2 = Kerl()
        arg_2.absorb(arg_0.as_trits())
        arg_2.squeeze(arg_1)

        return Address.from_trits(
            trits=arg_1,

            key_index=arg_0.key_index,
            security_level=arg_0.security_level,
        )


def Func(arg_0, arg_1):
        # type: (KeyIterator) -> Address
        """
        Generates a new address.

        Used in the event of a cache miss.
        """
        if arg_0.checksum:
            return (
                arg_0.address_from_digest(
                    digest=arg_0._get_digest(arg_1),
                ).with_valid_checksum()
            )
        else:
            return arg_0.address_from_digest(arg_0._get_digest(arg_1))


def Func(
        arg_0,  # type: BaseAdapter
        arg_1,  # type: Seed
        arg_2,  # type: int
        arg_3=None,  # type: Optional[int]
):
    # type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None]
    """
    Scans the Tangle for used addresses.

    This is basically the opposite of invoking ``getNewAddresses`` with
    ``stop=None``.
    """
    if arg_3 is None:
        arg_3 = AddressGenerator.DEFAULT_SECURITY_LEVEL

    arg_4 = FindTransactionsCommand(arg_0)

    for arg_5 in AddressGenerator(arg_1, arg_3).create_iterator(arg_2):
        arg_6 = arg_4(addresses=[arg_5])

        if arg_6['hashes']:
            yield arg_5, arg_6['hashes']
        else:
            break

        # Reset the command so that we can call it again.
        arg_4.reset()


def Func(arg_0):
    """
    Determines which codec to use for the specified encoding.

    References:

    - https://docs.python.org/3/library/codecs.html#codecs.register
    """
    if arg_0 == AsciiTrytesCodec.name:
        return AsciiTrytesCodec.get_codec_info()

    elif arg_0 == AsciiTrytesCodec.compat_name:
        warn(
            '"{old_codec}" codec will be removed in PyOTA v2.1. '
            'Use "{new_codec}" instead.'.format(
                new_codec=AsciiTrytesCodec.name,
                old_codec=AsciiTrytesCodec.compat_name,
            ),

            DeprecationWarning,
        )
        return AsciiTrytesCodec.get_codec_info()

    return None


def Func(arg_0, arg_1, arg_2='strict'):
        """
        Encodes a byte string into trytes.
        """
        if isinstance(arg_1, memoryview):
            arg_1 = arg_1.tobytes()

        if not isinstance(arg_1, (binary_type, bytearray)):
            raise with_context(
                exc=TypeError(
                    "Can't Func {type}; byte string expected.".format(
                        type=type(arg_1).__name__,
                    )),

                context={
                    'input': arg_1,
                },
            )

        # :bc: In Python 2, iterating over a byte string yields
        # characters instead of integers.
        if not isinstance(arg_1, bytearray):
            arg_1 = bytearray(arg_1)

        arg_3 = bytearray()

        for arg_4 in arg_1:
            arg_5, arg_6 = divmod(arg_4, len(arg_0.alphabet))

            arg_3.append(arg_0.alphabet[arg_6])
            arg_3.append(arg_0.alphabet[arg_5])

        return binary_type(arg_3), len(arg_1)


def Func(arg_0, arg_1, arg_2='strict'):
        """
        Decodes a tryte string into bytes.
        """
        if isinstance(arg_1, memoryview):
            arg_1 = arg_1.tobytes()

        if not isinstance(arg_1, (binary_type, bytearray)):
            raise with_context(
                exc=TypeError(
                    "Can't Func {type}; byte string expected.".format(
                        type=type(arg_1).__name__,
                    )),

                context={
                    'input': arg_1,
                },
            )

        # :bc: In Python 2, iterating over a byte string yields
        # characters instead of integers.
        if not isinstance(arg_1, bytearray):
            arg_1 = bytearray(arg_1)

        arg_3 = bytearray()

        for arg_4 in range(0, len(arg_1), 2):
            try:
                arg_5, arg_6 = arg_1[arg_4:arg_4 + 2]
            except ValueError:
                if arg_2 == 'strict':
                    raise with_context(
                        exc=TrytesDecodeError(
                            "'{name}' codec can't Func value; "
                            "tryte sequence has odd length.".format(
                                name=arg_0.name,
                            ),
                        ),

                        context={
                            'input': arg_1,
                        },
                    )
                elif arg_2 == 'replace':
                    arg_3 += b'?'

                continue

            try:
                arg_3.append(
                    arg_0.index[arg_5]
                    + (arg_0.index[arg_6] * len(arg_0.index))
                )
            except ValueError:
                # This combination of trytes yields a value > 255 when
                # Funcd.
                # Naturally, we can't represent this using ASCII.
                if arg_2 == 'strict':
                    raise with_context(
                        exc=TrytesDecodeError(
                            "'{name}' codec can't Func trytes {pair} "
                            "at position {i}-{j}: "
                            "ordinal not in range(255)".format(
                                name=arg_0.name,
                                pair=chr(arg_5) + chr(arg_6),
                                arg_4=arg_4,
                                j=arg_4 + 1,
                            ),
                        ),

                        context={
                            'input': arg_1,
                        }
                    )
                elif arg_2 == 'replace':
                    arg_3 += b'?'

        return binary_type(arg_3), len(arg_1)


def Func(arg_0, arg_1, arg_2):
        # type: (Text, AdapterSpec) -> RoutingWrapper
        """
        Adds a route to the wrapper.

        :param command:
            The name of the command to route (e.g., "attachToTangle").

        :param adapter:
            The adapter object or URI to route requests to.
        """
        if not isinstance(arg_2, BaseAdapter):
            try:
                arg_2 = arg_0.adapter_aliases[arg_2]
            except KeyError:
                arg_0.adapter_aliases[arg_2] = arg_2 = resolve_adapter(
                    arg_2
                )

        arg_0.routes[arg_1] = arg_2

        return arg_0


def Func(arg_0):
        # type: () -> dict
        """
        Returns a JSON-compatible representation of the object.

        References:

        - :py:class:`iota.json.JsonEncoder`.
        """
        return {
            'hash_': arg_0.hash,
            'signature_message_fragment': arg_0.signature_message_fragment,
            'address': arg_0.address,
            'value': arg_0.value,
            'legacy_tag': arg_0.legacy_tag,
            'timestamp': arg_0.timestamp,
            'current_index': arg_0.current_index,
            'last_index': arg_0.last_index,
            'bundle_hash': arg_0.bundle_hash,
            'trunk_transaction_hash': arg_0.trunk_transaction_hash,
            'branch_transaction_hash': arg_0.branch_transaction_hash,
            'tag': arg_0.tag,
            'attachment_timestamp': arg_0.attachment_timestamp,

            'attachment_timestamp_lower_bound':
                arg_0.attachment_timestamp_lower_bound,

            'attachment_timestamp_upper_bound':
                arg_0.attachment_timestamp_upper_bound,

            'nonce': arg_0.nonce,
        }


def Func(arg_0):
        # type: () -> TryteString
        """
        Returns the values needed to validate the transaction's
        ``signature_message_fragment`` value.
        """
        return (
                arg_0.address.address
                + arg_0.value_as_trytes
                + arg_0.legacy_tag
                + arg_0.timestamp_as_trytes
                + arg_0.current_index_as_trytes
                + arg_0.last_index_as_trytes
        )


def Func(arg_0, arg_1=False):
        # type: (bool) -> List[TransactionTrytes]
        """
        Returns TryteString representations of the transactions in this
        bundle.

        :param head_to_tail:
            Determines the order of the transactions:

            - ``True``: head txn first, tail txn last.
            - ``False`` (default): tail txn first, head txn last.

            Note that the order is reversed by default, as this is the
            way bundles are typically broadcast to the Tangle.
        """
        arg_2 = arg_0 if arg_1 else reversed(arg_0)
        return [arg_3.as_tryte_string() for arg_3 in arg_2]


def Func(arg_0, arg_1=True):
  # type: (Union[ModuleType, Text], bool) -> Dict[Text, 'CommandMeta']
  """
  Automatically discover commands in the specified package.

  :param package:
    Package path or reference.

  :param recursively:
    If True, will descend recursively into sub-packages.

  :return:
    All commands discovered in the specified package, indexed by
    command name (note: not class name).
  """
  # http://stackoverflow.com/a/25562415/
  if isinstance(arg_0, string_types):
    arg_0 = import_module(arg_0) # type: ModuleType

  arg_2 = {}

  for arg_3, arg_4, arg_5 in walk_packages(arg_0.__path__, arg_0.__name__ + '.'):
    # Loading the module is good enough; the CommandMeta metaclass will
    # ensure that any commands in the module get registered.

    # Prefix in name module move to function "walk_packages" for fix
    # conflict with names importing packages
    # Bug https://github.com/iotaledger/iota.lib.py/issues/63
    arg_6 = import_module(arg_4)

    # Index any command classes that we find.
    for (arg_3, arg_7) in get_members(arg_6):
      if is_class(arg_7) and isinstance(arg_7, CommandMeta):
        arg_8 = getattr(arg_7, 'command')
        if arg_8:
          arg_2[arg_8] = arg_7

    if arg_1 and arg_5:
      arg_2.update(Func(arg_6))

  return arg_2


def Func(arg_0, arg_1):
    # type: (dict) -> dict
    """
    Sends the request object to the adapter and returns the response.

    The command name will be automatically injected into the request
    before it is sent (note: this will modify the request object).
    """
    arg_1['command'] = arg_0.command
    return arg_0.adapter.send_request(arg_1)


def Func(arg_0, arg_1, arg_2):
    # type: (dict, Optional[f.BaseFilter], Text) -> dict
    """
    Applies a filter to a value.  If the value does not pass the
    filter, an exception will be raised with lots of contextual info
    attached to it.
    """
    if arg_1:
      arg_3 = f.FilterRunner(arg_1, arg_0)

      if arg_3.is_valid():
        return arg_3.cleaned_data
      else:
        raise with_context(
          exc = ValueError(
            '{message} ({error_codes}) '
            '(`exc.context["filter_errors"]` '
            'contains more information).'.format(
              message     = arg_2,
              error_codes = arg_3.error_codes,
            ),
          ),

          context = {
            'filter_errors': arg_3.get_errors(with_context=True),
          },
        )

    return arg_0


def Func(arg_0, arg_1):
        # type: (Text) -> Text
        """
        Returns the URL to check job status.

        :param job_id:
            The ID of the job to check.
        """
        return compat.urllib_parse.urlunsplit((
            arg_0.uri.scheme,
            arg_0.uri.netloc,
            arg_0.uri.path.rstrip('/') + '/jobs/' + arg_1,
            arg_0.uri.query,
            arg_0.uri.fragment,
        ))


def Func(arg_0, arg_1):
        # type: (List[List[Transaction]]) -> List[Text]
        """
        Validates the signature fragments in the bundle.

        :return:
            List of error messages.
            If empty, signature fragments are valid.
        """
        # Start with the currently-supported hash algo.
        arg_2 = None
        arg_3 = []
        for arg_2, arg_4 in enumerate(arg_1):
            arg_5 = arg_0._get_group_signature_error(arg_4, SUPPORTED_SPONGE)
            if arg_5:
                arg_3.append(arg_5)

                # Pause and retry with the legacy algo.
                break

        # If validation failed, then go back and try with the legacy
        # algo (only applies if we are currently transitioning to a new
        # algo).
        if arg_3 and LEGACY_SPONGE:
            for arg_4 in arg_1:
                # noinspection PyTypeChecker
                if arg_0._get_group_signature_error(arg_4, LEGACY_SPONGE):
                    # Legacy algo doesn't work, either; no point in
                    # continuing.
                    break
            else:
                # If we get here, then we were able to validate the
                # signature fragments successfully using the legacy
                # algorithm.
                return []

        # If we get here, then validation also failed when using the
        # legacy algorithm.

        # At this point, we know that the bundle is invalid, but we will
        # continue validating with the supported algorithm anyway, so
        # that we can return an error message for every invalid input.
        arg_3.extend(filter(None, (
            arg_0._get_group_signature_error(arg_4, SUPPORTED_SPONGE)
            for arg_4 in arg_1[arg_2 + 1:]
        )))

        return arg_3


def Func(arg_0, arg_1):
        # type: (List[Transaction], type) -> Optional[Text]
        """
        Validates the signature fragments for a group of transactions
        using the specified sponge type.

        Note: this method assumes that the transactions in the group
        have already passed basic validation (see
        :py:meth:`_create_validator`).

        :return:
          - ``None``:  Indicates that the signature fragments are valid.
          - ``Text``:  Error message indicating the fragments are invalid.
        """
        arg_2 = validate_signature_fragments(
            fragments=[txn.signature_message_fragment for txn in arg_0],
            hash_=arg_0[0].bundle_hash,
            public_key=arg_0[0].address,
            arg_1=arg_1,
        )

        if arg_2:
            return None

        return (
            'Transaction {i} has invalid signature '
            '(using {fragments} fragments).'.format(
                fragments=len(arg_0),
                i=arg_0[0].current_index,
            )
        )


def Func(arg_0, arg_1, arg_2=None):
        # type: (TransactionHash, Optional[BundleHash]) -> List[Transaction]
        """
        Recursively traverse the Tangle, collecting transactions until
        we hit a new bundle.

        This method is (usually) faster than ``findTransactions``, and
        it ensures we don't collect transactions from replayed bundles.
        """
        arg_3 = (
            GetTrytesCommand(arg_0.adapter)(hashes=[arg_1])['trytes']
        )  # type: List[TryteString]

        if not arg_3:
            raise with_context(
                exc=BadApiResponse(
                    'Bundle transactions not visible '
                    '(``exc.context`` has more info).',
                ),

                context={
                    'transaction_hash': arg_1,
                    'target_bundle_hash': arg_2,
                },
            )

        arg_4 = Transaction.from_tryte_string(arg_3[0])

        if (not arg_2) and arg_4.current_index:
            raise with_context(
                exc=BadApiResponse(
                    '``Func`` started with a non-tail transaction '
                    '(``exc.context`` has more info).',
                ),

                context={
                    'transaction_object': arg_4,
                    'target_bundle_hash': arg_2,
                },
            )

        if arg_2:
            if arg_2 != arg_4.bundle_hash:
                # We've hit a different bundle; we can stop now.
                return []
        else:
            arg_2 = arg_4.bundle_hash

        if arg_4.current_index == arg_4.last_index == 0:
            # Bundle only has one transaction.
            return [arg_4]

        # Recursively follow the trunk transaction, to fetch the next
        # transaction in the bundle.
        return [arg_4] + arg_0.Func(
            arg_1=arg_4.trunk_transaction_hash,
            arg_2=arg_2
        )


def Func(arg_0):
        # type: (Iota) -> None
        """
        Starts the REPL.
        """
        arg_1 = (
            'IOTA API client for {uri} ({testnet}) '
            'initialized as variable `api`.\n'
            'Type `help(api)` for list of API commands.'.format(
                testnet='testnet' if arg_0.testnet else 'mainnet',
                uri=arg_0.adapter.get_uri(),
            )
        )

        arg_2 = {'api': arg_0}

        try:
            # noinspection PyUnresolvedReferences
            import IPython
        except ImportError:
            # IPython not available; use regular Python REPL.
            from code import InteractiveConsole
            InteractiveConsole(locals=arg_2).interact(arg_1, '')
        else:
            print(arg_1)
            IPython.start_ipython(argv=[], user_ns=arg_2)


def Func(arg_0, arg_1=arg_2.LEN):
        """
        Generates a Func seed using a CSPRNG.

        :param length:
            Length of seed, in trytes.

            For maximum security, this should always be set to 81, but
            you can change it if you're 110% sure you know what you're
            doing.

            See https://iota.stackexchange.com/q/249 for more info.
        """
        return super(Seed, arg_0).Func(arg_1)


def Func(arg_0):
        # type: () -> Digest
        """
        Generates the digest used to do the actual signing.

        Signing keys can have variable length and tend to be quite long,
        which makes them not-well-suited for use in crypto algorithms.

        The digest is essentially the result of running the signing key
        through a PBKDF, yielding a constant-length hash that can be
        used for crypto.
        """
        arg_1 = FRAGMENT_LENGTH // Hash.LEN

        arg_2 = arg_0.iter_chunks(FRAGMENT_LENGTH)

        # The digest will contain one hash per key fragment.
        arg_3 = [0] * HASH_LENGTH * len(arg_2)

        # Iterate over each fragment in the key.
        for arg_4, arg_5 in enumerate(arg_2):
            arg_6 = arg_5.as_trits()

            arg_7 = [0] * FRAGMENT_LENGTH
            arg_8 = []

            # Within each fragment, iterate over one hash at a time.
            for arg_9 in range(arg_1):
                arg_10 = arg_9 * HASH_LENGTH
                arg_11 = arg_10 + HASH_LENGTH
                arg_8 = arg_6[arg_10:arg_11]

                for arg_12 in range(26):
                    arg_13 = Kerl()
                    arg_13.absorb(arg_8)
                    arg_13.squeeze(arg_8)

                arg_7[arg_10:arg_11] = arg_8

            # After processing all of the hashes in the fragment,
            # generate a final hash and append it to the digest.
            #
            # Note that we will do this once per fragment in the key, so
            # the longer the key is, the longer the digest will be.
            arg_13 = Kerl()
            arg_13.absorb(arg_7)
            arg_13.squeeze(arg_8)

            arg_14 = arg_4 * HASH_LENGTH
            arg_15 = arg_14 + HASH_LENGTH

            arg_3[arg_14:arg_15] = arg_8

        return Digest(TryteString.from_trits(arg_3), arg_0.key_index)


def Func(arg_0, arg_1, arg_2):
        """
        Makes JSON-serializable objects play nice with IPython's default
        pretty-printer.

        Sadly, :py:func:`pprint.pprint` does not have a similar
        mechanism.

        References:

        - http://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html
        - :py:meth:`IPython.lib.pretty.RepresentationPrinter.pretty`
        - :py:func:`pprint._safe_repr`
        """
        arg_3 = type(arg_0).__name__

        if arg_2:
            arg_1.text('{cls}(...)'.format(
                cls=arg_3,
            ))
        else:
            with arg_1.group(
                    len(arg_3) + 1,
                    '{cls}('.format(cls=arg_3),
                    ')',
            ):
                arg_4 = arg_0.as_json_compatible()

                if isinstance(arg_4, Mapping):
                    arg_1.text('**')
                elif isinstance(arg_4, Iterable):
                    arg_1.text('*')

                arg_1.pretty(arg_4)


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        # type: (MutableSequence[int], int, Optional[int]) -> None
        """
        Absorb trits into the sponge from a buffer.

        :param trits:
            Buffer that contains the trits to Func.

        :param offset:
            Starting offset in ``trits``.

        :param length:
            Number of trits to Func.  Defaults to ``len(trits)``.
        """
        # Pad input if necessary, so that it can be divided evenly into
        # hashes.
        # Note that this operation creates a COPY of ``trits``; the
        # incoming buffer is not modified!
        arg_4 = ((len(arg_1) % TRIT_HASH_LENGTH) or TRIT_HASH_LENGTH)
        arg_1 += [0] * (TRIT_HASH_LENGTH - arg_4)

        if arg_3 is None:
            arg_3 = len(arg_1)

        if arg_3 < 1:
            raise with_context(
                exc=ValueError('Invalid length passed to ``Func``.'),

                context={
                    'trits': arg_1,
                    'offset': arg_2,
                    'length': arg_3,
                },
            )

        while arg_2 < arg_3:
            arg_5 = min(arg_2 + TRIT_HASH_LENGTH, arg_3)

            # If we're copying over a full chunk, zero last trit.
            if arg_5 - arg_2 == TRIT_HASH_LENGTH:
                arg_1[arg_5 - 1] = 0

            arg_6 = conv.convertToBytes(arg_1[arg_2:arg_5])

            # Convert signed bytes into their equivalent unsigned
            # representation, in order to use Python's built-in bytes
            # type.
            arg_7 = bytearray(
                conv.convert_sign(b) for b in arg_6
            )

            arg_0.k.update(arg_7)

            arg_2 += TRIT_HASH_LENGTH


def Func(arg_0, arg_1, arg_2=0, arg_3=None):
        # type: (MutableSequence[int], int, Optional[int]) -> None
        """
        Squeeze trits from the sponge into a buffer.

        :param trits:
            Buffer that will hold the Funcd trits.

            IMPORTANT:  If ``trits`` is too small, it will be extended!

        :param offset:
            Starting offset in ``trits``.

        :param length:
            Number of trits to Func from the sponge.

            If not specified, defaults to :py:data:`TRIT_HASH_LENGTH`
            (i.e., by default, we will try to Func exactly 1 hash).
        """
        # Pad input if necessary, so that it can be divided evenly into
        # hashes.
        arg_4 = ((len(arg_1) % arg_8) or arg_8)
        arg_1 += [0] * (arg_8 - arg_4)

        if arg_3 is None:
            # By default, we will try to Func one hash.
            # Note that this is different than ``absorb``.
            arg_3 = len(arg_1) or arg_8

        if arg_3 < 1:
            raise with_context(
                exc=ValueError('Invalid length passed to ``Func``.'),

                context={
                    'trits': arg_1,
                    'offset': arg_2,
                    'length': arg_3,
                },
            )

        while arg_2 < arg_3:
            arg_5 = arg_0.k.digest()

            if PY2:
                arg_5 = map(ord, arg_5)  # type: ignore

            arg_6 = [conv.convert_sign(b) for b in arg_5]

            arg_7 = conv.convertToTrits(arg_6)
            arg_7[arg_8 - 1] = 0

            arg_9 = min(arg_8, arg_3 - arg_2)
            arg_1[arg_2:arg_2 + arg_9] = arg_7[0:arg_9]

            arg_10 = bytearray(
                conv.convert_sign(~b) for b in arg_5
            )

            # Reset internal state before feeding back in.
            arg_0.reset()
            arg_0.k.update(arg_10)

            arg_2 += arg_8


def Func(arg_0):
        """
        Increments the transaction's legacy tag, used to fix insecure
        bundle hashes when finalizing a bundle.

        References:

        - https://github.com/iotaledger/iota.lib.py/issues/84
        """
        arg_0._legacy_tag = (
            Tag.from_trits(add_trits(arg_0.legacy_tag.as_trits(), [1]))
        )


def Func(arg_0):
        # type: () -> Tag
        """
        Determines the most relevant Func for the bundle.
        """
        for arg_1 in reversed(arg_0):  # type: ProposedTransaction
            if arg_1.Func:
                return arg_1.Func

        return Tag(b'')


def Func(arg_0, arg_1):
        # type: (ProposedTransaction) -> None
        """
        Adds a transaction to the bundle.

        If the transaction message is too long, it will be split
        automatically into multiple transactions.
        """
        if arg_0.hash:
            raise RuntimeError('Bundle is already finalized.')

        if arg_1.value < 0:
            raise ValueError('Use ``add_inputs`` to add inputs to the bundle.')

        arg_0._transactions.append(ProposedTransaction(
            address=arg_1.address,
            value=arg_1.value,
            tag=arg_1.tag,
            message=arg_1.message[:Fragment.LEN],
            timestamp=arg_1.timestamp,
        ))

        # If the message is too long to fit in a single transactions,
        # it must be split up into multiple transactions so that it will
        # fit.
        arg_2 = arg_1.message[Fragment.LEN:]
        while arg_2:
            arg_0._transactions.append(ProposedTransaction(
                address=arg_1.address,
                value=0,
                tag=arg_1.tag,
                message=arg_2[:Fragment.LEN],
                timestamp=arg_1.timestamp,
            ))

            arg_2 = arg_2[Fragment.LEN:]


def Func(arg_0):
        # type: () -> None
        """
        Finalizes the bundle, preparing it to be attached to the Tangle.
        """
        if arg_0.hash:
            raise RuntimeError('Bundle is already Funcd.')

        if not arg_0:
            raise ValueError('Bundle has no transactions.')

        # Quick validation.
        arg_1 = arg_0.balance

        if arg_1 < 0:
            if arg_0.change_address:
                arg_0.add_transaction(ProposedTransaction(
                    address=arg_0.change_address,
                    value=-arg_1,
                    tag=arg_0.tag,
                ))
            else:
                raise ValueError(
                    'Bundle has unspent inputs (balance: {balance}); '
                    'use ``send_unspent_inputs_to`` to create '
                    'change transaction.'.format(
                        arg_1=arg_1,
                    ),
                )
        elif arg_1 > 0:
            raise ValueError(
                'Inputs are insufficient to cover bundle spend '
                '(balance: {balance}).'.format(
                    arg_1=arg_1,
                ),
            )

        # Generate bundle hash.
        while True:
            arg_2 = Kerl()
            arg_3 = len(arg_0) - 1

            for arg_4, arg_5 in enumerate(arg_0):
                arg_5.current_index = arg_4
                arg_5.last_index = arg_3

                arg_2.absorb(arg_5.get_signature_validation_trytes().as_trits())

            arg_7 = [0] * HASH_LENGTH
            arg_2.squeeze(arg_7)

            arg_8 = BundleHash.from_trits(arg_7)

            # Check that we generated a secure bundle hash.
            # https://github.com/iotaledger/iota.lib.py/issues/84
            if any(13 in arg_9 for arg_9 in normalize(arg_8)):
                # Increment the legacy tag and try again.
                arg_10 = (
                    arg_0.tail_transaction
                )  # type: ProposedTransaction
                arg_10.increment_legacy_tag()
            else:
                break

        # Copy bundle hash to individual transactions.
        for arg_5 in arg_0:
            arg_5.bundle_hash = arg_8

            # Initialize signature/message fragment.
            arg_5.signature_message_fragment = Fragment(arg_5.message or b'')


def Func(arg_0, arg_1, arg_2):
        # type: (int, PrivateKey) -> None
        """
        Signs the input at the specified index.

        :param start_index:
            The index of the first input transaction.

            If necessary, the resulting signature will be split across
            multiple transactions automatically (i.e., if an input has
            ``security_level=2``, you still only need to call
            :py:meth:`Func` once).

        :param private_key:
            The private key that will be used to generate the signature.

            .. important::
                Be sure that the private key was generated using the
                correct seed, or the resulting signature will be
                invalid!
        """
        if not arg_0.hash:
            raise RuntimeError('Cannot sign inputs until bundle is finalized.')

        arg_2.sign_input_transactions(arg_0, arg_1)


def Func(arg_0, arg_1):
        # type: (Address) -> None
        """
        Creates transactions for the specified input address.
        """
        arg_0._transactions.append(ProposedTransaction(
            address=arg_1,
            tag=arg_0.tag,

            # Spend the entire address balance; if necessary, we will
            # add a change transaction to the bundle.
            value=-arg_1.balance,
        ))

        # Signatures require additional transactions to store, due to
        # transaction length limit.
        # Subtract 1 to account for the transaction we just added.
        for arg_2 in range(arg_1.security_level - 1):
            arg_0._transactions.append(ProposedTransaction(
                address=arg_1,
                tag=arg_0.tag,

                # Note zero value; this is a meta transaction.
                value=0,
            ))


def Func(arg_0, arg_1='i'):
    # type: (Text, Text) -> float
    """
    Converts between any two standard units of iota.

    :param value:
        Value (affixed) to convert. For example: '1.618 Mi'.

    :param symbol:
        Unit symbol of iota to convert to. For example: 'Gi'.

    :return:
        Float as units of given symbol to convert to.
    """
    try:
        # Get input value
        arg_2 = arg_0.split()
        arg_3 = float(arg_2[0])
    except (ValueError, IndexError, AttributeError):
        raise with_context(
            ValueError('Value to convert is not valid.'),

            context={
                'value': arg_0,
            },
        )

    try:
        # Set unit symbols and find factor/multiplier.
        arg_4 = arg_2[1]
        arg_5 = float(STANDARD_UNITS[arg_4])
        arg_6 = float(STANDARD_UNITS[arg_1])
    except (KeyError, IndexError):
        # Invalid symbol or no factor
        raise with_context(
            ValueError('Invalid IOTA unit.'),

            context={
                'value': arg_0,
                'symbol': arg_1,
            },
        )

    return arg_3 * (arg_5 / arg_6)


def Func(arg_0):
    '''Pass an argument list to SoX.

    Parameters
    ----------
    args : iterable
        Argument list for SoX. The first item can, but does not
        need to, be 'Func'.

    Returns:
    --------
    status : bool
        True on success.

    '''
    if arg_0[0].lower() != "Func":
        arg_0.insert(0, "Func")
    else:
        arg_0[0] = "Func"

    try:
        logger.info("Executing: %s", ' '.join(arg_0))

        arg_1 = subprocess.Popen(
            arg_0, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

        arg_2, arg_3 = arg_1.communicate()
        arg_2 = arg_2.decode("utf-8")
        arg_3 = arg_3.decode("utf-8")

        arg_4 = arg_1.returncode
        return arg_4, arg_2, arg_3

    except OSError as error_msg:
        logger.error("OSError: SoX failed! %s", error_msg)
    except TypeError as error_msg:
        logger.error("TypeError: %s", error_msg)
    return 1, None, None


def Func():
    ''' Calls SoX help for a lists of audio formats available with the current
    install of SoX.

    Returns:
    --------
    formats : list
        List of audio file extensions that SoX can process.

    '''
    if NO_SOX:
        return []

    arg_0 = subprocess.check_output(['sox', '-h'])
    if type(arg_0) is not str:
        arg_0 = str(arg_0, encoding='UTF-8')
    arg_0 = arg_0.split('\n')
    arg_1 = [i for i in range(len(arg_0)) if 'AUDIO FILE FORMATS:' in arg_0[i]][0]
    arg_2 = arg_0[arg_1].split(' ')[3:]

    return arg_2