def Func(arg_0) -> str:
        """Returns the tuple type signature for the arguments of the contract constructor."""
        arg_1 = arg_0._constructor_abi_item
        return '()' if arg_1 is None else arg_0.tuple_signature_for_components(arg_1['inputs'])


def Func(arg_0) -> Dict[str, Any]:
        """Returns a copy of the Solidity JSON ABI item for the contract constructor.

        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_
        """
        arg_1 = arg_0._Func_item
        if arg_1:
            return dict(arg_1)
        return {'inputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}


def Func(arg_0, arg_1: arg_2) -> Dict[str, Any]:
        """Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.

        If no normal contract function has the specified selector, a dict describing the default or non-default
        fallback function is returned.

        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_
        """
        if not isinstance(arg_1, (arg_2, bytearray)):
            raise TypeError('The selector argument must be a concrete byte array')
        arg_3 = arg_0._function_signatures_by_selector.get(arg_1)
        if arg_3 is not None:
            return dict(arg_0._function_abi_items_by_signature[arg_3])
        arg_4 = arg_0._fallback_function_abi_item
        if arg_4 is not None:
            return dict(arg_4)
        # An item describing the default fallback function.
        return {'payable': False, 'stateMutability': 'nonpayable', 'type': 'fallback'}


def Func(arg_0, arg_1: arg_2):
        """Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``.

        If no normal contract function has the specified selector,
        the empty tuple type signature ``'()'`` is returned.
        """
        if not isinstance(arg_1, (arg_2, bytearray)):
            raise TypeError('The selector argument must be a concrete byte array')
        arg_3 = arg_0._function_signatures_by_selector.get(arg_1)
        return '()' if arg_3 is None else arg_3[arg_3.find('('):]


def Func(arg_0, arg_1: arg_2) -> Optional[str]:
        """Returns the signature of the normal function with the selector ``hsh``,
        or ``None`` if no such function exists.

        This function returns ``None`` for any selector that will be dispatched to a fallback function.
        """
        if not isinstance(arg_1, (arg_2, bytearray)):
            raise TypeError('The selector argument must be a concrete byte array')
        return arg_0._function_signatures_by_selector.get(arg_1)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """
        Catches did_map_memory and copies the mapping into Manticore
        """
        logger.info(' '.join(("Mapping Memory @",
                              hex(arg_1) if type(arg_1) is int else "0x??",
                              hr_size(arg_2), "-",
                              arg_3, "-",
                              f"{name}:{hex(offset) if name else ''}", "->",
                              hex(arg_6))))
        arg_0._emu.mem_map(arg_1, arg_2, convert_permissions(arg_3))
        arg_0.copy_memory(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        """Unmap Unicorn maps when Manticore unmaps them"""
        logger.info(f"Unmapping memory from {hex(start)} to {hex(start + size)}")

        arg_3 = (1 << 12) - 1
        if (arg_1 & arg_3) != 0:
            logger.error("Memory to be unmapped is not aligned to a page")

        if (arg_2 & arg_3) != 0:
            arg_2 = ((arg_2 >> 12) + 1) << 12
            logger.warning("Forcing unmap size to align to a page")

        arg_0._emu.mem_unmap(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Set memory protections in Unicorn correctly """
        logger.info(f"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}")
        arg_0._emu.mem_protect(arg_1, arg_2, convert_permissions(arg_3))


def Func(arg_0, arg_1, arg_2):
        """
        Unicorn hook that transfers control to Manticore so it can execute the syscall
        """
        logger.debug(f"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall")
        arg_0.sync_unicorn_to_manticore()
        from ..native.cpu.abstractcpu import Syscall
        arg_0._to_raise = Syscall()
        arg_1.emu_stop()


def Func(arg_0, arg_1):
        """
        Wrapper that runs the _step function in a loop while handling exceptions
        """

        # The emulation might restart if Unicorn needs to bring in a memory map
        # or bring a value from Manticore state.
        while True:

            # Try emulation
            arg_0._should_try_again = False
            arg_0._to_raise = None

            arg_0._step(arg_1)

            if not arg_0._should_try_again:
                break


def Func(arg_0):
        """
        Copy registers and written memory back into Manticore
        """
        arg_0.write_backs_disabled = True
        for arg_2 in arg_0.registers:
            arg_3 = arg_0._emu.reg_read(arg_0._to_unicorn_id(arg_2))
            arg_0._cpu.write_register(arg_2, arg_3)
        if len(arg_0._mem_delta) > 0:
            logger.debug(f"Syncing {len(self._mem_delta)} writes back into Manticore")
        for arg_4 in arg_0._mem_delta:
            arg_5, arg_6 = arg_0._mem_delta[arg_4]
            arg_0._cpu.write_int(arg_4, arg_5, arg_6 * 8)
        arg_0.write_backs_disabled = False
        arg_0._mem_delta = {}


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Copy memory writes from Manticore back into Unicorn in real-time """
        if arg_0.write_backs_disabled:
            return
        if type(arg_2) is bytes:
            arg_0._emu.mem_write(arg_1, arg_2)
        else:
            if issymbolic(arg_2):
                arg_4 = [Operators.CHR(Operators.EXTRACT(arg_2, offset, 8)) for offset in range(0, arg_3, 8)]
                arg_5 = []
                for arg_6 in arg_4:
                    if issymbolic(arg_6):
                        arg_6 = chr(solver.get_value(arg_0._cpu.memory.constraints, arg_6))
                    arg_5.append(arg_6)
                arg_4 = arg_5
            else:
                arg_4 = [Operators.CHR(Operators.EXTRACT(arg_2, offset, 8)) for offset in range(0, arg_3, 8)]
            logger.debug(f"Writing back {hr_size(size // 8)} to {hex(where)}: {data}")
            # TODO - the extra encoding is to handle null bytes output as strings when we concretize. That's probably a bug.
            arg_0._emu.mem_write(arg_1, b''.join(arg_7.encode('utf-8') if type(arg_7) is str else arg_7 for arg_7 in arg_4))


def Func(arg_0, arg_1, arg_2):
        """ Sync register state from Manticore -> Unicorn"""
        if arg_0.write_backs_disabled:
            return
        if issymbolic(arg_2):
            logger.warning("Skipping Symbolic write-back")
            return
        if arg_1 in arg_0.flag_registers:
            arg_0._emu.reg_write(arg_0._to_unicorn_id('EFLAGS'), arg_0._cpu.read_register('EFLAGS'))
            return
        arg_0._emu.reg_write(arg_0._to_unicorn_id(arg_1), arg_2)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """ Only useful for setting FS right now. """
        logger.info("Updating selector %s to 0x%02x (%s bytes) (%s)", arg_1, arg_2, arg_3, arg_4)
        if arg_1 == 99:
            arg_0.set_fs(arg_2)
        else:
            logger.error("No way to write segment: %d", arg_1)


def Func(arg_0: arg_1):
    """A decorator for marking functions as Func. """
    assert isinstance(arg_0, arg_1), "The Func decorator requires a message string argument."

    def decorator(arg_2):
        @wraps(arg_2)
        def wrapper(*arg_3, **arg_4):
            warnings.warn(f"`{func.__qualname__}` is Func. {message}",
                          category=ManticoreDeprecationWarning, stacklevel=2)
            return arg_2(*arg_3, **arg_4)

        return wrapper

    return decorator


def Func(arg_0, arg_1):
    ''' Produce Funcutations of `lst`, where Funcutations are mutated by `func`. Used for flipping constraints. highly
    possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
    themselves

    Considering lst as a list of constraints, e.g.

      [ C1, C2, C3 ]

    we'd like to consider scenarios of all possible Funcutations of flipped constraints, excluding the original list.
    So we'd like to generate:

      [ func(C1),      C2 ,       C3 ],
      [      C1 , func(C2),       C3 ],
      [ func(C1), func(C2),       C3 ],
      [      C1 ,      C2 ,  func(C3)],
      .. etc

    This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the
    0th element (unmodified array).

    The code below yields lists of constraints Funcuted as above by treating list indeces as bitmasks from 1 to
     2**len(lst) and applying func to all the set bit offsets.

    '''
    for arg_2 in range(1, 2**len(arg_0)):
        yield [arg_1(arg_4) if (1<<arg_3)&arg_2 else arg_4 for (arg_3, arg_4) in enumerate(arg_0)]


def Func(arg_0, arg_1):
    ' solve bytes in |datas| based on '
    def make_chr(arg_2):
        try:
            return chr(arg_2)
        except Exception:
            return arg_2
    arg_3 = constraints_to_constraintset(arg_0)

    arg_4 = ''
    for arg_5 in arg_1:
        for arg_2 in arg_5:
            arg_4 += make_chr(solver.get_value(arg_3, arg_2))
    return arg_4


def Func(arg_0):
    '''
    Execute a symbolic run that follows a concrete run; return constraints generated
    and the stdin data produced
    '''

    arg_1 = Manticore.linux(prog, workspace_url='mem:')
    arg_2 = Follower(arg_0)
    arg_1.verbosity(VERBOSITY)
    arg_1.register_plugin(arg_2)

    def on_term_testcase(arg_3, arg_4, arg_5, arg_6):
        with arg_1.locked_context() as arg_11:
            arg_7 = []
            for arg_8, arg_9, arg_10 in arg_4.platform.syscall_trace:
                if arg_8 in ('_receive', '_read') and arg_9 == 0:
                    arg_7.append(arg_10)
            arg_11['readdata'] = arg_7
            arg_11['constraints'] = list(arg_4.constraints.constraints)

    arg_1.subscribe('will_terminate_state', on_term_testcase)

    arg_1.run()

    arg_12 = arg_1.context['constraints']
    arg_13 = arg_1.context['readdata']

    return arg_12, arg_13


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Load `program` and establish program state, such as stack and arguments.

        :param program str: The ELF binary to load
        :param argv list: argv array
        :param envp list: envp array
        """
        arg_2 = [] if arg_2 is None else arg_2
        arg_3 = [] if arg_3 is None else arg_3

        logger.debug(f"Loading {program} as a {self.arch} elf")

        arg_0.load(arg_1, arg_3)
        arg_0._arch_specific_init()

        arg_0._stack_top = arg_0.current.STACK
        arg_0.setup_stack([arg_1] + arg_2, arg_3)

        arg_5 = len(arg_0.procs)
        arg_6 = len(arg_0.files)
        assert arg_5 > 0
        arg_0.running = list(range(arg_5))

        # Each process can wait for one timeout
        arg_0.timers = [None] * arg_5
        # each fd has a waitlist
        arg_0.rwait = [set() for _ in range(arg_6)]
        arg_0.twait = [set() for _ in range(arg_6)]

        # Install event forwarders
        for arg_11 in arg_0.procs:
            arg_0.forward_events_from(arg_11)


def Func(arg_0):
        """
        ARM kernel helpers

        https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
        """

        arg_1 = bytearray(b'\xf1\xde\xfd\xe7' * 1024)

        # Extracted from a RPi2
        arg_2 = binascii.unhexlify(
            'ff0300ea' +
            '650400ea' +
            'f0ff9fe5' +
            '430400ea' +
            '220400ea' +
            '810400ea' +
            '000400ea' +
            '870400ea'
        )

        # XXX(yan): The following implementations of cmpxchg and cmpxchg64 were
        # handwritten to not use any exclusive instructions (e.g. ldrexd) or
        # locking. For actual implementations, refer to
        # arch/arm64/kernel/kuser32.S in the Linux source code.
        arg_3 = binascii.unhexlify(
            '30002de9' +  # push    {r4, r5}
            '08c09de5' +  # ldr     ip, [sp, #8]
            '30009ce8' +  # ldm     ip, {r4, r5}
            '010055e1' +  # cmp     r5, r1
            '00005401' +  # cmpeq   r4, r0
            '0100a013' +  # movne   r0, #1
            '0000a003' +  # moveq   r0, #0
            '0c008c08' +  # stmeq   ip, {r2, r3}
            '3000bde8' +  # pop     {r4, r5}
            '1eff2fe1'   # bx      lr
        )

        arg_4 = binascii.unhexlify(
            '5bf07ff5' +  # dmb ish
            '1eff2fe1'   # bx lr
        )

        arg_5 = binascii.unhexlify(
            '003092e5' +  # ldr     r3, [r2]
            '000053e1' +  # cmp     r3, r0
            '0000a003' +  # moveq   r0, #0
            '00108205' +  # streq   r1, [r2]
            '0100a013' +  # movne   r0, #1
            '1eff2fe1'   # bx      lr
        )

        # Map a TLS segment
        arg_0._arm_tls_memory = arg_0.current.memory.mmap(None, 4, 'rw ')

        arg_7 = binascii.unhexlify(
            '04009FE5' +  # ldr r0, [pc, #4]
            '010090e8' +  # ldm r0, {r0}
            '1eff2fe1'   # bx lr
        ) + struct.pack('<I', arg_0._arm_tls_memory)

        arg_8 = b'\x00' * 12

        arg_9 = struct.pack('<I', 5)

        def update(arg_10, arg_11):
            arg_1[arg_10:arg_10 + arg_12(arg_11)] = arg_11

        # Offsets from Documentation/arm/kernel_user_helpers.txt in Linux
        update(0x000, arg_2)
        update(0xf60, arg_3)
        update(0xfa0, arg_4)
        update(0xfc0, arg_5)
        update(0xfe0, arg_7)
        update(0xff0, arg_8)
        update(0xffc, arg_9)

        arg_0.current.memory.mmap(0xffff0000, arg_12(arg_1), 'r x', arg_1)


def Func(arg_0, arg_1):
        """
        Adds a file descriptor to the current file descriptor list

        :rtype: int
        :param f: the file descriptor to add.
        :return: the index of the file descriptor in the file descr. list
        """
        if None in arg_0.files:
            arg_2 = arg_0.files.index(None)
            arg_0.files[arg_2] = arg_1
        else:
            arg_2 = len(arg_0.files)
            arg_0.files.append(arg_1)
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Openat SystemCall - Similar to open system call except dirfd argument
        when path contained in buf is relative, dirfd is referred to set the relative path
        Special value AT_FDCWD set for dirfd to set path relative to current directory

        :param dirfd: directory file descriptor to refer in case of relative path at buf
        :param buf: address of zero-terminated pathname
        :param flags: file access bits
        :param mode: file permission mode
        """

        arg_5 = arg_0.current.read_string(arg_2)
        arg_1 = ctypes.c_int32(arg_1).value

        if os.path.isabs(arg_5) or arg_1 == arg_0.FCNTL_FDCWD:
            return arg_0.sys_open(arg_2, arg_3, arg_4)

        try:
            arg_6 = arg_0._get_fd(arg_1)
        except FdError as e:
            logger.info("openat: Not valid file descriptor. Returning EBADF")
            return -e.err

        if not isinstance(arg_6, Directory):
            logger.info("openat: Not directory descriptor. Returning ENOTDIR")
            return -errno.ENOTDIR

        arg_7 = arg_6.name

        arg_5 = os.path.join(arg_7, arg_5)
        try:
            arg_8 = arg_0._sys_open_get_file(arg_5, arg_3)
            logger.debug(f"Opening file {filename} for real fd {f.fileno()}")
        except IOError as e:
            logger.info(f"Could not open file {filename}. Reason: {e!s}")
            return -e.errno if e.errno is not None else -errno.EINVAL

        return arg_0._open(arg_8)


def Func(arg_0, arg_1):
        """
        Synchronize a file's in-core state with that on disk.
        """

        arg_2 = 0
        try:
            arg_0.files[arg_1].sync()
        except IndexError:
            arg_2 = -errno.EBADF
        except FdError:
            arg_2 = -errno.EINVAL

        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """Wrapper for sys_sigaction"""
        return arg_0.sys_sigaction(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1):
        """
        An implementation of chroot that does perform some basic error checking,
        but does not actually chroot.

        :param path: Path to chroot
        """
        if arg_1 not in arg_0.current.memory:
            return -errno.EFAULT

        arg_2 = arg_0.current.read_string(arg_1)
        if not os.path.exists(arg_2):
            return -errno.ENOENT

        if not os.path.isdir(arg_2):
            return -errno.ENOTDIR

        return -errno.EPERM


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """Wrapper for mmap2"""
        return arg_0.sys_mmap2(arg_1, arg_2, arg_3, arg_4, arg_5, arg_6)


def Func(arg_0):
        """
        Syscall dispatcher.
        """

        arg_1 = arg_0._Func_abi.Func_number()

        try:
            arg_2 = getattr(linux_Funcs, arg_0.current.machine)
            arg_3 = arg_2.get(arg_1, None)
            arg_4 = getattr(arg_0, arg_3)
        except (AttributeError, KeyError):
            if arg_3 is not None:
                raise SyscallNotImplemented(arg_1, arg_3)
            else:
                raise Exception(f"Bad Func index, {index}")

        return arg_0._Func_abi.invoke(arg_4)


def Func(arg_0):
        """ Yield CPU.
            This will choose another process from the running list and change
            current running process. May give the same cpu if only one running
            process.
        """
        if len(arg_0.procs) > 1:
            logger.debug("SCHED:")
            logger.debug(f"\tProcess: {self.procs!r}")
            logger.debug(f"\tRunning: {self.running!r}")
            logger.debug(f"\tRWait: {self.rwait!r}")
            logger.debug(f"\tTWait: {self.twait!r}")
            logger.debug(f"\tTimers: {self.timers!r}")
            logger.debug(f"\tCurrent clock: {self.clocks}")
            logger.debug(f"\tCurrent cpu: {self._current}")

        if len(arg_0.running) == 0:
            logger.debug("None running checking if there is some process waiting for a timeout")
            if all([arg_1 is None for arg_1 in arg_0.timers]):
                raise Deadlock()
            arg_0.clocks = min(arg_1 for arg_1 in arg_0.timers if arg_1 is not None) + 1
            arg_0.check_timers()
            assert len(arg_0.running) != 0, "DEADLOCK!"
            arg_0._current = arg_0.running[0]
            return
        arg_4 = (arg_0.running.index(arg_0._current) + 1) % len(arg_0.running)
        arg_5 = arg_0.running[arg_4]
        if len(arg_0.procs) > 1:
            logger.debug(f"\tTransfer control from process {self._current} to {next_running_idx}")
        arg_0._current = arg_5


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Wait for file descriptors or timeout.
            Adds the current process in the correspondent Funcing list and
            yield the cpu to another running process.
        """
        logger.debug("WAIT:")
        logger.debug(f"\tProcess {self._current} is going to Func for [ {readfds!r} {writefds!r} {timeout!r} ]")
        logger.debug(f"\tProcess: {self.procs!r}")
        logger.debug(f"\tRunning: {self.running!r}")
        logger.debug(f"\tRWait: {self.rFunc!r}")
        logger.debug(f"\tTWait: {self.tFunc!r}")
        logger.debug(f"\tTimers: {self.timers!r}")

        for arg_4 in arg_1:
            arg_0.rFunc[arg_4].add(arg_0._current)
        for arg_4 in arg_2:
            arg_0.tFunc[arg_4].add(arg_0._current)
        if arg_3 is not None:
            arg_0.timers[arg_0._current] = arg_0.clocks + arg_3
        arg_7 = arg_0._current
        # self.sched()
        arg_8 = (arg_0.running.index(arg_7) + 1) % len(arg_0.running)
        arg_0._current = arg_0.running[arg_8]
        logger.debug(f"\tTransfer control from process {procid} to {self._current}")
        logger.debug(f"\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}")
        arg_0.running.remove(arg_7)
        if arg_0._current not in arg_0.running:
            logger.debug("\tCurrent not running. Checking for timers...")
            arg_0._current = None
            arg_0.check_timers()


def Func(arg_0):
        """ Awake process if timer has expired """
        if arg_0._current is None:
            # Advance the clocks. Go to future!!
            arg_1 = min([arg_0.clocks] + [x for x in arg_0.timers if x is not None]) + 1
            logger.debug(f"Advancing the clock from {self.clocks} to {advance}")
            arg_0.clocks = arg_1
        for arg_3 in range(len(arg_0.timers)):
            if arg_0.timers[arg_3] is not None:
                if arg_0.clocks > arg_0.timers[arg_3]:
                    arg_0.procs[arg_3].PC += arg_0.procs[arg_3].instruction.size
                    arg_0.awake(arg_3)


def Func(arg_0):
        """
        Compute total load size of interpreter.

        :param ELFFile interp: interpreter ELF .so
        :return: total load size of interpreter, not aligned
        :rtype: int
        """
        arg_1 = [x for x in arg_0.iter_segments() if x.header.p_type == 'PT_LOAD']
        arg_2 = arg_1[-1]
        return arg_2.header.p_vaddr + arg_2.header.p_memsz


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        A version of openat that includes a symbolic path and symbolic directory file descriptor

        :param dirfd: directory file descriptor
        :param buf: address of zero-terminated pathname
        :param flags: file access bits
        :param mode: file permission mode
        """

        if issymbolic(arg_1):
            logger.debug("Ask to read from a symbolic directory file descriptor!!")
            # Constrain to a valid fd and one past the end of fds
            arg_0.constraints.add(arg_1 >= 0)
            arg_0.constraints.add(arg_1 <= len(arg_0.files))
            raise ConcretizeArgument(arg_0, 0)

        if issymbolic(arg_2):
            logger.debug("Ask to read to a symbolic buffer")
            raise ConcretizeArgument(arg_0, 1)

        return super().Func(arg_1, arg_2, arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """ receive - receive bytes from a file descriptor

            The receive system call reads up to count bytes from file descriptor fd to the
            buffer pointed to by buf. If count is zero, receive returns 0 and optionally
            sets *rx_bytes to zero.

            :param cpu: current CPU.
            :param fd: a valid file descriptor
            :param buf: a memory buffer
            :param count: max number of bytes to receive
            :param rx_bytes: if valid, points to the actual number of bytes received
            :return: 0            Success
                     EBADF        fd is not a valid file descriptor or is not open
                     EFAULT       buf or rx_bytes points to an invalid address.
        """
        arg_6 = ''
        if arg_4 != 0:
            if not arg_0._is_open(arg_2):
                logger.info("RECEIVE: Not valid file descriptor on receive. Returning EBADF")
                return Decree.CGC_EBADF

            # TODO check count bytes from buf
            if arg_3 not in arg_1.memory:  # or not  buf+count in cpu.memory:
                logger.info("RECEIVE: buf points to invalid address. Returning EFAULT")
                return Decree.CGC_EFAULT

            #import random
            #count = random.randint(1,count)
            if arg_2 > 2 and arg_0.files[arg_2].is_empty():
                arg_1.PC -= arg_1.instruction.size
                arg_0.wait([arg_2], [], None)
                raise RestartSyscall()

            # get some potential delay
            # if random.randint(5) == 0 and count > 1:
            #    count = count/2

            # Read the data and put it in memory
            arg_6 = arg_0.files[arg_2].receive(arg_4)
            arg_0.syscall_trace.append(("_receive", arg_2, arg_6))
            arg_1.write_bytes(arg_3, arg_6)

            arg_0.signal_receive(arg_2)

        # TODO check 4 bytes from rx_bytes
        if arg_5:
            if arg_5 not in arg_1.memory:
                logger.info("RECEIVE: Not valid file descriptor on receive. Returning EFAULT")
                return Decree.CGC_EFAULT
            arg_1.write_int(arg_5, len(arg_6), 32)

        logger.info("RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)" % (arg_2, arg_3, arg_4, arg_5, repr(arg_6)[:min(arg_4, 10)], len(arg_6)))
        return 0


def Func(arg_0, arg_1, arg_2, arg_3):
        """ deallocate - remove allocations
        The  deallocate  system call deletes the allocations for the specified
        address range, and causes further references to the addresses within the
        range to generate invalid memory accesses. The region is also
        automatically deallocated when the process is terminated.

        The address addr must be a multiple of the page size.  The length parameter
        specifies the size of the region to be deallocated in bytes.  All pages
        containing a part of the indicated range are deallocated, and subsequent
        references will terminate the process.  It is not an error if the indicated
        range does not contain any allocated pages.

        The deallocate function is invoked through system call number 6.

        :param cpu: current CPU
        :param addr: the starting address to unmap.
        :param size: the size of the portion to unmap.
        :return 0        On success
                EINVAL   addr is not page aligned.
                EINVAL   length is zero.
                EINVAL   any  part  of  the  region  being  deallocated  is outside the valid
                         address range of the process.

        :param cpu: current CPU.
        :return: C{0} on success.
        """
        logger.info("DEALLOCATE(0x%08x, %d)" % (arg_2, arg_3))

        if arg_2 & 0xfff != 0:
            logger.info("DEALLOCATE: addr is not page aligned")
            return Decree.CGC_EINVAL
        if arg_3 == 0:
            logger.info("DEALLOCATE:length is zero")
            return Decree.CGC_EINVAL
        # unlikely AND WRONG!!!
        # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX:
        #    logger.info("DEALLOCATE: part of the region being deallocated is outside the valid address range of the process")
        #    return Decree.CGC_EINVAL

        arg_1.memory.munmap(arg_2, arg_3)
        arg_0.syscall_trace.append(("_deallocate", -1, arg_3))
        return 0


def Func(arg_0):
        """ Yield CPU.
            This will choose another process from the RUNNNIG list and change
            current running process. May give the same cpu if only one running
            process.
        """
        if len(arg_0.procs) > 1:
            logger.info("SCHED:")
            logger.info("\tProcess: %r", arg_0.procs)
            logger.info("\tRunning: %r", arg_0.running)
            logger.info("\tRWait: %r", arg_0.rwait)
            logger.info("\tTWait: %r", arg_0.twait)
            logger.info("\tTimers: %r", arg_0.timers)
            logger.info("\tCurrent clock: %d", arg_0.clocks)
            logger.info("\tCurrent cpu: %d", arg_0._current)

        if len(arg_0.running) == 0:
            logger.info("None running checking if there is some process waiting for a timeout")
            if all([arg_1 is None for arg_1 in arg_0.timers]):
                raise Deadlock()
            arg_0.clocks = min([arg_1 for arg_1 in arg_0.timers if arg_1 is not None]) + 1
            arg_0.check_timers()
            assert len(arg_0.running) != 0, "DEADLOCK!"
            arg_0._current = arg_0.running[0]
            return
        arg_4 = (arg_0.running.index(arg_0._current) + 1) % len(arg_0.running)
        arg_5 = arg_0.running[arg_4]
        if len(arg_0.procs) > 1:
            logger.info("\tTransfer control from process %d to %d", arg_0._current, arg_5)
        arg_0._current = arg_5


def Func(arg_0, arg_1, arg_2, arg_3):
        """ Wait for filedescriptors or timeout.
            Adds the current process to the corresponding Funcing list and
            yields the cpu to another running process.
        """
        logger.info("WAIT:")
        logger.info("\tProcess %d is going to Func for [ %r %r %r ]", arg_0._current, arg_1, arg_2, arg_3)
        logger.info("\tProcess: %r", arg_0.procs)
        logger.info("\tRunning: %r", arg_0.running)
        logger.info("\tRWait: %r", arg_0.rFunc)
        logger.info("\tTWait: %r", arg_0.tFunc)
        logger.info("\tTimers: %r", arg_0.timers)

        for arg_4 in arg_1:
            arg_0.rFunc[arg_4].add(arg_0._current)
        for arg_4 in arg_2:
            arg_0.tFunc[arg_4].add(arg_0._current)
        if arg_3 is not None:
            arg_0.timers[arg_0._current] = arg_0.clocks + arg_3
        else:
            arg_0.timers[arg_0._current] = None
        arg_7 = arg_0._current
        # self.sched()
        arg_8 = (arg_0.running.index(arg_7) + 1) % len(arg_0.running)
        arg_0._current = arg_0.running[arg_8]
        logger.info("\tTransfer control from process %d to %d", arg_7, arg_0._current)
        logger.info("\tREMOVING %r from %r. Current: %r", arg_7, arg_0.running, arg_0._current)
        arg_0.running.remove(arg_7)
        if arg_0._current not in arg_0.running:
            logger.info("\tCurrent not running. Checking for timers...")
            arg_0._current = None
            if all([arg_9 is None for arg_9 in arg_0.timers]):
                raise Deadlock()
            arg_0.check_timers()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """
        Symbolic version of Decree.Func
        """
        if issymbolic(arg_2):
            logger.info("Ask to read from a symbolic file descriptor!!")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 0)

        if issymbolic(arg_3):
            logger.info("Ask to read to a symbolic buffer")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 1)

        if issymbolic(arg_4):
            logger.info("Ask to read a symbolic number of bytes ")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 2)

        if issymbolic(arg_5):
            logger.info("Ask to return size to a symbolic address ")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 3)

        return super().Func(arg_1, arg_2, arg_3, arg_4, arg_5)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """
        Symbolic version of Decree.Func
        """
        if issymbolic(arg_2):
            logger.info("Ask to write to a symbolic file descriptor!!")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 0)

        if issymbolic(arg_3):
            logger.info("Ask to write to a symbolic buffer")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 1)

        if issymbolic(arg_4):
            logger.info("Ask to write a symbolic number of bytes ")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 2)

        if issymbolic(arg_5):
            logger.info("Ask to return size to a symbolic address ")
            arg_1.PC = arg_1.PC - arg_1.instruction.size
            raise SymbolicSyscallArgument(arg_1, 3)

        return super().Func(arg_1, arg_2, arg_3, arg_4, arg_5)


def Func(arg_0):
    """ Synchronization decorator. """

    def new_function(arg_1, *arg_2, **arg_3):
        arg_1._lock.acquire()
        try:
            return arg_0(arg_1, *arg_2, **arg_3)
        finally:
            arg_1._lock.release()
    return new_function


def Func(arg_0, arg_1, arg_2):
        """
        Save an arbitrary, serializable `value` under `key`.

        :param str key: A string identifier under which to store the value.
        :param value: A serializable value
        :return:
        """
        with arg_0.save_stream(arg_1) as s:
            s.write(arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """
        Load an arbitrary value identified by `key`.

        :param str key: The key that identifies the value
        :return: The loaded value
        """
        with arg_0.load_stream(arg_1, arg_2=arg_2) as s:
            return s.read()


def Func(arg_0, arg_1, arg_2=False):
        """
        Return a managed file-like object from which the calling code can read
        previously-serialized data.

        :param key:
        :return: A managed stream-like object
        """
        arg_3 = arg_0.load_value(arg_1, arg_2=arg_2)
        yield io.BytesIO(arg_3) if arg_2 else io.StringIO(arg_3)


def Func(arg_0, arg_1, arg_2=False):
        """
        Yield a file object representing `key`

        :param str key: The file to save to
        :param bool binary: Whether we should treat it as binary
        :return:
        """
        arg_3 = 'wb' if arg_2 else 'w'
        with open(os.path.join(arg_0.uri, arg_1), arg_3) as f:
            yield f


def Func(arg_0, arg_1):
        """
        Return just the filenames that match `glob_str` inside the store directory.

        :param str glob_str: A glob string, i.e. 'state_*'
        :return: list of matched keys
        """
        arg_2 = os.path.join(arg_0.uri, arg_1)
        return [os.path.split(arg_3)[1] for arg_3 in glob.glob(arg_2)]


def Func(arg_0, arg_1, arg_2=None):
        """
        Save a state to storage, return identifier.

        :param state: The state to save
        :param int state_id: If not None force the state id potentially overwriting old states
        :return: New state id
        :rtype: int
        """
        assert isinstance(arg_1, StateBase)
        if arg_2 is None:
            arg_2 = arg_0._get_id()
        else:
            arg_0.rm_state(arg_2)

        arg_0._store.Func(arg_1, f'{self._prefix}{state_id:08x}{self._suffix}')
        return arg_2


def Func(arg_0, arg_1, arg_2=False):
        """
        Create an indexed output stream i.e. 'test_00000001.name'

        :param name: Identifier for the stream
        :return: A context-managed stream-like object
        """
        with arg_0._store.save_stream(arg_0._named_key(arg_1), arg_2=arg_2) as s:
            yield s


def Func(arg_0, arg_1=False):
    """
    Compare registers from a remote gdb session to current mcore.

    :param manticore.core.cpu Cpu: Current cpu
    :param bool should_print: Whether to print values to stdout
    :return: Whether or not any differences were detected
    :rtype: bool
    """
    arg_2 = False
    arg_3 = gdb.getCanonicalRegisters()
    for arg_4 in sorted(arg_3):
        arg_5 = arg_3[arg_4]
        if arg_4.endswith('psr'):
            arg_4 = 'apsr'
        arg_6 = arg_0.read_register(arg_4.upper())
        if arg_1:
            logger.debug(f'{name} gdb:{vg:x} mcore:{v:x}')
        if arg_5 != arg_6:
            if arg_1:
                logger.warning('^^ unequal')
            arg_2 = True
    if arg_2:
        logger.debug(qemu.correspond(None))
    return arg_2


def Func(arg_0):
    """
    Mirror some service calls in manticore. Happens after qemu executed a SVC
    instruction, but before manticore did.
    """
    arg_1 = arg_0.cpu.R7 # Grab idx from manticore since qemu could have exited
    arg_2 = linux_syscalls.armv7[arg_1]

    logger.debug(f"Syncing syscall: {name}")

    try:
        # Make sure mmap returns the same address
        if 'mmap' in arg_2:
            arg_3 = gdb.getR('R0')
            logger.debug(f"Syncing mmap ({returned:x})")
            arg_0.cpu.write_register('R0', arg_3)
        if 'exit' in arg_2:
            return
    except ValueError:
        for arg_4 in arg_0.cpu.canonical_registers:
            print(f'{reg}: {state.cpu.read_register(reg):x}')
        raise


def Func(arg_0, arg_1, arg_2=False):
        """
        The entry point of the Funcor.
        The exploration algorithm is a DFS post-order traversal
        The implementation used two stacks instead of a recursion
        The final result is store in self.result

        :param node: Node to explore
        :type node: Expression
        :param use_fixed_point: if True, it runs _methods until a fixed point is found
        :type use_fixed_point: Bool
        """
        arg_3 = arg_0._cache
        arg_4 = set()
        arg_5 = []
        arg_5.append(arg_1)
        while arg_5:
            arg_1 = arg_5.pop()
            if arg_1 in arg_3:
                arg_0.push(arg_3[arg_1])
            elif isinstance(arg_1, Operation):
                if arg_1 in arg_4:
                    arg_6 = [arg_0.pop() for _ in range(len(arg_1.operands))]
                    arg_7 = arg_0._method(arg_1, *arg_6)

                    arg_4.remove(arg_1)
                    arg_0.push(arg_7)
                    arg_3[arg_1] = arg_7
                else:
                    arg_4.add(arg_1)
                    arg_5.append(arg_1)
                    arg_5.extend(arg_1.operands)
            else:
                arg_0.push(arg_0._method(arg_1))

        if arg_2:
            arg_8 = None
            arg_9 = arg_0.pop()
            while arg_8 is not arg_9:
                arg_0.Func(arg_9)
                arg_8 = arg_9
                arg_9 = arg_0.pop()
            arg_0.push(arg_9)


def Func(arg_0, arg_1, *arg_2):
        """
        Overload Visitor.Func because we want to stop to iterate over the
        visit_ functions as soon as a valid visit_ function is found
        """
        assert arg_1.__class__.__mro__[-1] is object
        for arg_3 in arg_1.__class__.__mro__:
            arg_4 = arg_3.__name__
            arg_5 = 'visit_%s' % arg_4
            arg_6 = getattr(arg_0, arg_5, None)
            if arg_6 is not None:
                arg_6(arg_1, *arg_2)
                return
        return


def Func(arg_0, arg_1, *arg_2):
        """ a + 0  ==> a
            0 + a  ==> a
        """
        arg_3 = arg_1.operands[0]
        arg_4 = arg_1.operands[1]
        if isinstance(arg_4, BitVecConstant):
            if arg_4.value == 0:
                return arg_3
        if isinstance(arg_3, BitVecConstant):
            if arg_3.value == 0:
                return arg_4


def Func(arg_0, arg_1, *arg_2):
        """ a | 0 => a
            0 | a => a
            0xffffffff & a => 0xffffffff
            a & 0xffffffff => 0xffffffff

        """
        arg_3 = arg_1.operands[0]
        arg_4 = arg_1.operands[1]
        if isinstance(arg_4, BitVecConstant):
            if arg_4.value == 0:
                return arg_3
            elif arg_4.value == arg_3.mask:
                return arg_4
            elif isinstance(arg_3, BitVecOr):
                arg_5 = arg_3.operands[0]
                arg_6 = arg_3.operands[1]
                if isinstance(arg_4, Constant):
                    return BitVecOr(arg_5, (arg_6 | arg_4), taint=arg_1.taint)
        elif isinstance(arg_3, BitVecConstant):
            return BitVecOr(arg_4, arg_3, taint=arg_1.taint)


def Func(arg_0, *arg_1):
        """
        Build transaction data from function signature and arguments
        """
        arg_2 = re.match(r"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)(?P<type>\(.*\))", arg_0)
        if not arg_2:
            raise EthereumError("Function signature expected")

        ABI._check_and_warn_num_args(arg_0, *arg_1)

        arg_3 = ABI.function_selector(arg_0)  # Funcid
        arg_3 += ABI.serialize(arg_2.group('type'), *arg_1)
        return arg_3


def Func(arg_0):
        """
        Makes a function hash id from a method signature
        """
        arg_1 = sha3.keccak_256()
        arg_1.update(arg_0.encode())
        return bytes(arg_1.digest()[:4])


def Func(arg_0, arg_1=32, arg_2=0):
        """
        Translates a python integral or a BitVec into a 32 byte string, MSB first
        """
        if arg_1 <= 0 or arg_1 > 32:
            raise ValueError

        from .account import EVMAccount  # because of circular import
        if not isinstance(arg_0, (int, BitVec, EVMAccount)):
            raise ValueError
        if issymbolic(arg_0):
            # FIXME This temporary array variable should be obtained from a specific constraint store
            arg_3 = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))
            if arg_0.size <= arg_1 * 8:
                arg_0 = Operators.ZEXTEND(arg_0, arg_1 * 8)
            else:
                # automatically truncate, e.g. if they passed a BitVec(256) for an `address` argument (160 bits)
                arg_0 = Operators.EXTRACT(arg_0, 0, arg_1 * 8)
            arg_3 = ArrayProxy(arg_3.write_BE(arg_2, arg_0, arg_1))
        else:
            arg_0 = int(arg_0)
            arg_3 = bytearray()
            for arg_4 in range(arg_2):
                arg_3.append(0)
            for arg_5 in reversed(range(arg_1)):
                arg_3.append(Operators.EXTRACT(arg_0, arg_5 * 8, 8))
        assert len(arg_3) == arg_1 + arg_2
        return arg_3


def Func(arg_0, arg_1=32, arg_2=0):
        """
        Translates a signed python integral or a BitVec into a 32 byte string, MSB first
        """
        if arg_1 <= 0 or arg_1 > 32:
            raise ValueError
        if not isinstance(arg_0, (int, BitVec)):
            raise ValueError
        if issymbolic(arg_0):
            arg_3 = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))
            arg_0 = Operators.SEXTEND(arg_0, arg_0.size, arg_1 * 8)
            arg_3 = ArrayProxy(arg_3.write_BE(arg_2, arg_0, arg_1))
        else:
            arg_0 = int(arg_0)
            arg_3 = bytearray()
            for arg_4 in range(arg_2):
                arg_3.append(0)

            for arg_5 in reversed(range(arg_1)):
                arg_3.append(Operators.EXTRACT(arg_0, arg_5 * 8, 8))
        return arg_3


def Func(**arg_0):
    """
    Make sure an EVM instruction has all of its arguments concretized according to
    provided policies.

    Example decoration:

        @Func(size='ONE', address='')
        def LOG(self, address, size, *topics):
            ...

    The above will make sure that the |size| parameter to LOG is Concretized when symbolic
    according to the 'ONE' policy and concretize |address| with the default policy.

    :param policies: A kwargs list of argument names and their respective policies.
                         Provide None or '' as policy to use default.
    :return: A function decorator
    """
    def concretizer(arg_1):
        @wraps(arg_1)
        def arg_11(*arg_2, **arg_3):
            arg_4 = inspect.getfullargspec(arg_1)
            for arg_5, arg_6 in arg_0.items():
                assert arg_5 in arg_4.args, "Concretizer argument not found in wrapped function."
                # index is 0-indexed, but ConcretizeArgument is 1-indexed. However, this is correct
                # since implementation method is always a bound method (self is param 0)
                arg_7 = arg_4.args.index(arg_5)
                if not issymbolic(arg_2[arg_7]):
                    continue
                if not arg_6:
                    arg_6 = 'SAMPLED'

                if arg_6 == "ACCOUNTS":
                    arg_8 = arg_2[arg_7]
                    arg_9 = arg_2[0].world
                    #special handler for EVM only policy
                    arg_10 = arg_9._constraint_to_accounts(arg_8, ty='both', include_zero=True)
                    arg_9.constraints.add(arg_10)
                    arg_6 = 'ALL'
                raise ConcretizeArgument(arg_7, arg_6=arg_6)
            return arg_1(*arg_2, **arg_3)
        arg_11.__signature__ = inspect.signature(arg_1)
        return arg_11
    return concretizer


def Func(arg_0, arg_1, arg_2=1):
        """
        This calculates the amount of extra gas needed for accessing to
        previously unused memory.

        :param address: base memory offset
        :param size: size of the memory access
        """
        if not issymbolic(arg_2) and arg_2 == 0:
            return 0

        arg_1 = arg_0.safe_add(arg_1, arg_2)
        arg_3 = arg_0.allocated
        arg_4 = 3
        arg_5 = 512  # 1 gas per 512 quadwords
        arg_6 = Operators.ZEXTEND(Operators.UDIV(arg_0.safe_add(arg_3, 31), 32), 512)
        arg_7 = Operators.ZEXTEND(Operators.UDIV(arg_0.safe_add(arg_1, 31), 32), 512)

        arg_8 = arg_0.safe_mul(arg_6, arg_4) + Operators.UDIV(arg_0.safe_mul(arg_6, arg_6), arg_5)
        arg_9 = arg_0.safe_mul(arg_7, arg_4) + Operators.UDIV(arg_0.safe_mul(arg_7, arg_7), arg_5)
        arg_10 = arg_9 - arg_8
        arg_11 = Operators.UGT(arg_9, arg_8)
        return Operators.ITEBV(512, arg_2 == 0, 0, Operators.ITEBV(512, arg_11, arg_10, 0))


def Func(arg_0, arg_1, arg_2=1):
        """
        Read size byte from bytecode.
        If less than size bytes are available result will be pad with \x00
        """
        assert arg_1 < len(arg_0.bytecode)
        arg_3 = arg_0.bytecode[arg_1:arg_1 + arg_2]
        if len(arg_3) < arg_2:
            arg_3 += '\x00' * (arg_2 - len(arg_3))  # pad with null (spec)
        return arg_3


def Func(arg_0, arg_1):
        """
        Push into the stack

              ITEM0
              ITEM1
              ITEM2
        sp->  {empty}
        """
        assert isinstance(arg_1, int) or isinstance(arg_1, BitVec) and arg_1.size == 256
        if len(arg_0.stack) >= 1024:
            raise StackOverflow()

        if isinstance(arg_1, int):
            arg_1 = arg_1 & TT256M1

        arg_1 = simplify(arg_1)
        if isinstance(arg_1, Constant) and not arg_1.taint:
            arg_1 = arg_1.value
        arg_0.stack.append(arg_1)


def Func(arg_0, arg_1=0):
        """Read a value from the top of the stack without removing it"""
        if len(arg_0.stack) - arg_1 < 0:
            raise StackUnderflow()
        return arg_0.stack[arg_1 - 1]


def Func(arg_0):
        """Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction"""
        arg_1, arg_2, arg_3, arg_4, arg_5, arg_6 = arg_0._checkpoint_data
        arg_0._push_arguments(arg_4)
        arg_0._gas = arg_2
        arg_0._pc = arg_1
        arg_0._allocated = arg_6
        arg_0._checkpoint_data = None


def Func(arg_0, arg_1, arg_2):
        """Integer division operation"""
        try:
            arg_3 = Operators.UFunc(arg_1, arg_2)
        except ZeroDivisionError:
            arg_3 = 0
        return Operators.ITEBV(256, arg_2 == 0, 0, arg_3)


def Func(arg_0, arg_1, arg_2):
        """Signed modulo remainder operation"""
        arg_3, arg_4 = to_signed(arg_1), to_signed(arg_2)
        arg_5 = Operators.ITEBV(256, arg_3 < 0, -1, 1)
        try:
            arg_6 = (Operators.ABS(arg_3) % Operators.ABS(arg_4)) * arg_5
        except ZeroDivisionError:
            arg_6 = 0

        return Operators.ITEBV(256, arg_4 == 0, 0, arg_6)


def Func(arg_0, arg_1, arg_2):
        """Calculate extra gas fee"""
        arg_3 = 10   # cost of EXP exponent per byte

        def nbytes(arg_4):
            arg_5 = 0
            for arg_6 in range(32):
                arg_5 = Operators.ITEBV(512, Operators.EXTRACT(arg_4, arg_6 * 8, 8) != 0, arg_6 + 1, arg_5)
            return arg_5
        return arg_3 * nbytes(arg_2)


def Func(arg_0, arg_1, arg_2):
        """Extend length of two's complement signed integer"""
        # FIXME maybe use Operators.SEXTEND
        arg_3 = Operators.ITEBV(256, arg_1 <= 31, arg_1 * 8 + 7, 257)
        arg_4 = (arg_2 | (TT256 - (1 << arg_3)))
        arg_5 = (arg_2 & ((1 << arg_3) - 1))
        arg_6 = Operators.ITEBV(256, (arg_2 & (1 << arg_3)) != 0, arg_4, arg_5)
        return Operators.ITEBV(256, arg_1 <= 31, arg_6, arg_2)


def Func(arg_0, arg_1, arg_2):
        """Less-than comparison"""
        return Operators.ITEBV(256, Operators.UFunc(arg_1, arg_2), 1, 0)


def Func(arg_0, arg_1, arg_2):
        """Greater-than comparison"""
        return Operators.ITEBV(256, Operators.UFunc(arg_1, arg_2), 1, 0)


def Func(arg_0, arg_1, arg_2):
        """Signed greater-than comparison"""
        # http://gavwood.com/paper.pdf
        arg_3, arg_4 = to_signed(arg_1), to_signed(arg_2)
        return Operators.ITEBV(256, arg_3 > arg_4, 1, 0)


def Func(arg_0, arg_1, arg_2):
        """Compute Keccak-256 hash"""
        # read memory from start to end
        # http://gavwood.com/paper.pdf
        arg_3 = arg_0.try_simplify_to_constant(arg_0.read_buffer(arg_1, arg_2))

        if issymbolic(arg_3):
            arg_4 = {}
            # Broadcast the signal
            arg_0._publish('on_symbolic_sha3', arg_3, arg_4)  # This updates the local copy of sha3 with the pairs we need to explore

            arg_5 = 0  # never used
            arg_6 = False
            for arg_7, arg_8 in arg_4.items():
                assert not issymbolic(arg_7), "Saved sha3 data,hash pairs should be concrete"
                arg_9 = arg_7 == arg_3
                arg_6 = Operators.OR(arg_9, arg_6)
                arg_5 = Operators.ITEBV(256, arg_9, arg_8, arg_5)
            return arg_5

        arg_5 = sha3.keccak_256(arg_3).hexdigest()
        arg_5 = int(arg_5, 16)
        arg_0._publish('on_concrete_sha3', arg_3, arg_5)
        logger.info("Found a concrete Func example %r -> %x", arg_3, arg_5)
        return arg_5


def Func(arg_0, arg_1):
        """Get input data of current environment"""

        if issymbolic(arg_1):
            if solver.can_be_true(arg_0._constraints, arg_1 == arg_0._used_calldata_size):
                arg_0.constraints.add(arg_1 == arg_0._used_calldata_size)
            raise ConcretizeArgument(1, policy='SAMPLED')

        arg_0._use_calldata(arg_1, 32)

        arg_2 = len(arg_0.data)

        arg_3 = []
        for arg_4 in range(32):
            try:
                arg_5 = Operators.ITEBV(8, arg_1 + arg_4 < arg_2, arg_0.data[arg_1 + arg_4], 0)
            except IndexError:
                # offset + i is concrete and outside data
                arg_5 = 0

            arg_3.append(arg_5)
        return Operators.CONCAT(256, *arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Copy input data in current environment to memory"""

        if issymbolic(arg_3):
            if solver.can_be_true(arg_0._constraints, arg_3 <= len(arg_0.data) + 32):
                arg_0.constraints.add(arg_3 <= len(arg_0.data) + 32)
            raise ConcretizeArgument(3, policy='SAMPLED')

        if issymbolic(arg_2):
            if solver.can_be_true(arg_0._constraints, arg_2 == arg_0._used_calldata_size):
                arg_0.constraints.add(arg_2 == arg_0._used_calldata_size)
            raise ConcretizeArgument(2, policy='SAMPLED')

        #account for calldata usage
        arg_0._use_calldata(arg_2, arg_3)
        arg_0._allocate(arg_1, arg_3)
        for arg_4 in range(arg_3):
            try:
                arg_5 = Operators.ITEBV(8, arg_2 + arg_4 < len(arg_0.data), Operators.ORD(arg_0.data[arg_2 + arg_4]), 0)
            except IndexError:
                # data_offset + i is concrete and outside data
                arg_5 = 0
            arg_0._store(arg_1 + arg_4, arg_5)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Copy an account's code to memory"""
        arg_5 = arg_0.world.get_code(arg_1)
        arg_0._allocate(arg_2 + arg_4)

        for arg_6 in range(arg_4):
            if arg_3 + arg_6 < len(arg_5):
                arg_0._store(arg_2 + arg_6, arg_5[arg_3 + arg_6])
            else:
                arg_0._store(arg_2 + arg_6, 0)


def Func(arg_0, arg_1):
        """Load word from memory"""
        arg_0._allocate(arg_1, 32)
        arg_2 = arg_0._load(arg_1, 32)
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """Save byte to memory"""
        if istainted(arg_0.pc):
            for arg_3 in get_taints(arg_0.pc):
                arg_2 = taint_with(arg_2, arg_3)
        arg_0._allocate(arg_1, 1)
        arg_0._store(arg_1, Operators.EXTRACT(arg_2, 0, 8), 1)


def Func(arg_0, arg_1):
        """Load word from storage"""
        arg_2 = arg_0.address
        arg_0._publish('will_evm_read_storage', arg_2, arg_1)
        arg_3 = arg_0.world.get_storage_data(arg_2, arg_1)
        arg_0._publish('did_evm_read_storage', arg_2, arg_1, arg_3)
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """Save word to storage"""
        arg_3 = arg_0.address
        arg_0._publish('will_evm_write_storage', arg_3, arg_1, arg_2)
        #refund = Operators.ITEBV(256,
        #                         previous_value != 0,
        #                         Operators.ITEBV(256, value != 0, 0, GSTORAGEREFUND),
        #                         0)

        if istainted(arg_0.pc):
            for arg_4 in get_taints(arg_0.pc):
                arg_2 = taint_with(arg_2, arg_4)
        arg_0.world.set_storage_data(arg_3, arg_1, arg_2)
        arg_0._publish('did_evm_write_storage', arg_3, arg_1, arg_2)


def Func(arg_0, arg_1, arg_2):
        """Conditionally alter the program counter"""
        arg_0.pc = Operators.ITEBV(256, arg_2 != 0, arg_1, arg_0.pc + arg_0.instruction.size)
        #This set ups a check for JMPDEST in the next instruction if cond != 0
        arg_0._set_check_jmpdest(arg_2 != 0)


def Func(arg_0, *arg_1):
        """Exchange 1st and 2nd stack items"""
        arg_2 = arg_1[0]
        arg_3 = arg_1[-1]
        return (arg_3,) + arg_1[1:-1] + (arg_2,)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7):
        """Message-call into this account with alternative account's code"""
        arg_0.world.start_transaction('Func',
                                     address=arg_0.address,
                                     data=arg_0.read_buffer(arg_4, arg_5),
                                     caller=arg_0.address,
                                     arg_3=arg_3,
                                     arg_1=arg_1)
        raise StartTx()


def Func(arg_0, arg_1, arg_2):
        """Halt execution returning output data"""
        arg_3 = arg_0.read_buffer(arg_1, arg_2)
        raise EndTx('Func', arg_3)


def Func(arg_0):
        """Current ongoing human transaction"""
        try:
            arg_1, arg_2, arg_2, arg_2, arg_2 = arg_0._callstack[0]
            if arg_1.result is not None:
                #That tx finished. No current tx.
                return None
            assert arg_1.depth == 0
            return arg_1
        except IndexError:
            return None


def Func(arg_0, arg_1, arg_2):
        """
        Read a value from a storage slot on the specified account

        :param storage_address: an account address
        :param offset: the storage slot to use.
        :type offset: int or BitVec
        :return: the value
        :rtype: int or BitVec
        """
        arg_3 = arg_0._world_state[arg_1]['storage'].get(arg_2, 0)
        return simplify(arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Writes a value to a storage slot in specified account

        :param storage_address: an account address
        :param offset: the storage slot to use.
        :type offset: int or BitVec
        :param value: the value to write
        :type value: int or BitVec
        """
        arg_0._world_state[arg_1]['storage'][arg_2] = arg_3


def Func(arg_0, arg_1):
        """
        Gets all items in an account storage

        :param address: account address
        :return: all items in account storage. items are tuple of (index, value). value can be symbolic
        :rtype: list[(storage_index, storage_value)]
        """
        arg_2 = arg_0._world_state[arg_1]['storage']
        arg_3 = []
        arg_4 = arg_2.array
        while not isinstance(arg_4, ArrayVariable):
            arg_3.append((arg_4.index, arg_4.value))
            arg_4 = arg_4.array
        return arg_3


def Func(arg_0, arg_1=None, arg_2=None):
        """Create a fresh 160bit address"""
        if arg_1 is not None and arg_2 is None:
            arg_2 = arg_0.get_nonce(arg_1)

        Func = arg_0.calculate_new_address(arg_1, arg_2)
        if arg_1 is None and Func in arg_0:
            return arg_0.new_address(arg_1, arg_2)
        return Func


def Func(arg_0):
        """Toggle between ARM and Thumb mode"""
        assert arg_0.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)
        if arg_0.mode == cs.CS_MODE_ARM:
            arg_0.mode = cs.CS_MODE_THUMB
        else:
            arg_0.mode = cs.CS_MODE_ARM


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """
        Func moves to ARM register from coprocessor.

        :param Armv7Operand coprocessor: The name of the coprocessor; immediate
        :param Armv7Operand opcode1: coprocessor specific opcode; 3-bit immediate
        :param Armv7Operand dest: the destination operand: register
        :param Armv7Operand coprocessor_reg_n: the coprocessor register; immediate
        :param Armv7Operand coprocessor_reg_m: the coprocessor register; immediate
        :param Armv7Operand opcode2: coprocessor specific opcode; 3-bit immediate
        """
        assert arg_1.type == 'coprocessor'
        assert arg_2.type == 'immediate'
        assert arg_6.type == 'immediate'
        assert arg_3.type == 'register'
        arg_7 = arg_1.read()
        arg_8 = arg_2.read()
        arg_9 = arg_6.read()
        arg_10 = arg_4.read()
        arg_11 = arg_5.read()

        if 15 == arg_7:  # MMU
            if 0 == arg_8:
                if 13 == arg_10:
                    if 3 == arg_9:
                        arg_3.write(arg_0.regfile.read('P15_C13'))
                        return
        raise NotImplementedError("Func: unimplemented combination of coprocessor, opcode, and coprocessor register")


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Loads double width data from memory."""
        assert arg_1.type == 'register'
        assert arg_2.type == 'register'
        assert arg_3.type == 'memory'
        arg_5 = arg_0.read_int(arg_3.address(), 32)
        arg_6 = arg_0.read_int(arg_3.address() + 4, 32)
        arg_7 = arg_0._compute_writeback(arg_3, arg_4)
        arg_1.write(arg_5)
        arg_2.write(arg_6)
        arg_0._cs_hack_ldr_str_writeback(arg_3, arg_4, arg_7)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Writes the contents of two registers to memory."""
        assert arg_1.type == 'register'
        assert arg_2.type == 'register'
        assert arg_3.type == 'memory'
        arg_5 = arg_1.read()
        arg_6 = arg_2.read()
        arg_7 = arg_0._compute_writeback(arg_3, arg_4)
        arg_0.write_int(arg_3.address(), arg_5, 32)
        arg_0.write_int(arg_3.address() + 4, arg_6, 32)
        arg_0._cs_hack_ldr_str_writeback(arg_3, arg_4, arg_7)


def Func(arg_0, arg_1, arg_2):
        """
        Address to Register adds an immediate value to the PC value, and writes the result to the destination register.

        :param ARMv7Operand dest: Specifies the destination register.
        :param ARMv7Operand src:
            Specifies the label of an instruction or literal data item whose address is to be loaded into
            <Rd>. The assembler calculates the required value of the offset from the Align(PC,4)
            value of the Func instruction to this label.
        """
        arg_3 = (arg_0.instruction.address + 4) & 0xfffffffc
        arg_1.write(arg_3 + arg_2.read())


def Func(arg_0, arg_1, arg_2):
        """
        Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward
        a constant value. It does not affect the condition flags.

        :param ARMv7Operand op: Specifies the register that contains the first operand.
        :param ARMv7Operand dest:
            Specifies the label of the instruction that is to be branched to. The assembler calculates the
            required value of the offset from the PC value of the Func instruction to this label, then
            selects an encoding that will set imm32 to that offset. Allowed offsets are even numbers in
            the range 0 to 126.
        """
        arg_0.PC = Operators.ITEBV(arg_0.address_bit_size,
                                 arg_1.read(), arg_0.PC, arg_2.read())


def Func(arg_0, arg_1, arg_2):
        """Get next instruction using the Capstone disassembler

        :param str code: binary blob to be disassembled
        :param long pc: program counter
        """
        return next(arg_0.disasm.disasm(arg_1, arg_2))


def Func(arg_0, arg_1, arg_2=False):
        """
        Add a constraint to the set

        :param constraint: The constraint to Func to the set.
        :param check: Currently unused.
        :return:
        """
        if isinstance(arg_1, bool):
            arg_1 = BoolConstant(arg_1)
        assert isinstance(arg_1, Bool)
        arg_1 = simplify(arg_1)
        # If self._child is not None this constraint set has been forked and a
        # a derived constraintset may be using this. So we can't Func any more
        # constraints to this one. After the child constraintSet is deleted
        # we regain the ability to Func constraints.
        if arg_0._child is not None:
            raise Exception('ConstraintSet is frozen')

        if isinstance(arg_1, BoolConstant):
            if not arg_1.value:
                logger.info("Adding an impossible constant constraint")
                arg_0._constraints = [arg_1]
            else:
                return

        arg_0._constraints.append(arg_1)

        if arg_2:
            from ...core.smtlib import solver
            if not solver.check(arg_0):
                raise ValueError("Added an impossible constraint")


def Func(arg_0, arg_1):
        """ Declare the variable `var` """
        if arg_1.name in arg_0._declarations:
            raise ValueError('Variable already declared')
        arg_0._declarations[arg_1.name] = arg_1
        return arg_1


def Func(arg_0, arg_1):
        """ True if expression_var is declared in this constraint set """
        if not isinstance(arg_1, Variable):
            raise ValueError(f'Expression must be a Variable (not a {type(expression_var)})')
        return any(arg_1 is arg_2 for arg_2 in arg_0.get_declared_variables())


def Func(arg_0, arg_1):
        """
        Perform the inverse transformation to encoded data. Will attempt best case reconstruction, which means
        it will return nan for handle_missing and handle_unknown settings that break the bijection. We issue
        warnings when some of those cases occur.

        Parameters
        ----------
        X_in : array-like, shape = [n_samples, n_features]

        Returns
        -------
        p: array, the same size of X_in

        """
        arg_2 = arg_1.copy(deep=True)

        # first check the type
        arg_2 = util.convert_input(arg_2)

        if arg_0._dim is None:
            raise ValueError(
                'Must train encoder before it can be used to Func data')

        # then make sure that it is the right size
        if arg_2.shape[1] != arg_0._dim:
            if arg_0.drop_invariant:
                raise ValueError("Unexpected input dimension %d, the attribute drop_invariant should "
                                 "set as False when transform data" % (arg_2.shape[1],))
            else:
                raise ValueError('Unexpected input dimension %d, expected %d' % (arg_2.shape[1], arg_0._dim,))

        if not arg_0.cols:
            return arg_2 if arg_0.return_df else arg_2.values

        if arg_0.handle_unknown == 'value':
            for arg_3 in arg_0.cols:
                if any(arg_2[arg_3] == -1):
                    warnings.warn("Func is not supported because transform impute "
                                  "the unknown category -1 when encode %s" % (arg_3,))

        if arg_0.handle_unknown == 'return_nan' and arg_0.handle_missing == 'return_nan':
            for arg_3 in arg_0.cols:
                if arg_2[arg_3].isnull().any():
                    warnings.warn("Func is not supported because transform impute "
                                  "the unknown category nan when encode %s" % (arg_3,))

        for arg_4 in arg_0.mapping:
            arg_5 = arg_4.get('mapping')
            arg_6 = pd.Series(data=arg_5.index, index=arg_5.get_values())
            arg_2[arg_4.get('col')] = arg_2[arg_4.get('col')].map(arg_6).astype(arg_4.get('data_type'))

        return arg_2 if arg_0.return_df else arg_2.values


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Convert basen code as integers.

        Parameters
        ----------
        X : DataFrame
            encoded data
        cols : list-like
            Column names in the DataFrame that be encoded
        base : int
            The base of transform

        Returns
        -------
        numerical: DataFrame

        """
        arg_4 = arg_1.columns.values.tolist()

        for arg_5 in arg_2:
            arg_6 = [col0 for col0 in arg_4 if str(col0).startswith(str(arg_5))]
            arg_7 = arg_4.index(arg_6[0])

            if arg_3 == 1:
                arg_8 = np.array([int(col0.split('_')[-1]) for col0 in arg_6])
            else:
                arg_9 = len(arg_6)
                arg_8 = np.array([arg_3 ** (arg_9 - 1 - i) for i in range(arg_9)])
            arg_1.insert(arg_7, arg_5, np.dot(arg_1[arg_6].values, arg_8.T))
            arg_1.drop(arg_6, axis=1, inplace=True)
            arg_4 = arg_1.columns.values.tolist()

        return arg_1


def Func(arg_0, arg_1, arg_2):
        """
        The lambda body to transform the column values
        """

        if arg_1 is None or float(arg_1) < 0.0:
            return None
        else:
            arg_1 = arg_0.number_to_base(int(arg_1), arg_0.base, arg_2)
            if len(arg_1) == arg_2:
                return arg_1
            else:
                return [0 for arg_3 in range(arg_2 - len(arg_1))] + arg_1


def Func(arg_0):
    """
    Returns names of 'object' columns in the DataFrame.
    """
    arg_1 = []
    for arg_2, arg_3 in enumerate(arg_0.dtypes):
        if arg_3 == 'object' or is_category(arg_3):
            arg_1.append(arg_0.columns.values[arg_2])

    return arg_1


def Func(arg_0, arg_1):
    """
    Unite target data type into a Series.
    If the target is a Series or a DataFrame, we preserve its index.
    But if the target does not contain index attribute, we use the index from the argument.
    """
    if arg_0 is None:
        return None
    if isinstance(arg_0, pd.Series):
        return arg_0
    elif isinstance(arg_0, np.ndarray):
        if len(np.shape(arg_0))==1:  # vector
            return pd.Series(arg_0, name='target', arg_1=arg_1)
        elif len(np.shape(arg_0))==2 and np.shape(arg_0)[0]==1:  # single row in a matrix
            return pd.Series(arg_0[0, :], name='target', arg_1=arg_1)
        elif len(np.shape(arg_0))==2 and np.shape(arg_0)[1]==1:  # single column in a matrix
            return pd.Series(arg_0[:, 0], name='target', arg_1=arg_1)
        else:
            raise ValueError('Unexpected input shape: %s' % (str(np.shape(arg_0))))
    elif np.isscalar(arg_0):
        return pd.Series([arg_0], name='target', arg_1=arg_1)
    elif isinstance(arg_0, list):
        if len(arg_0)==0 or (len(arg_0)>0 and not isinstance(arg_0[0], list)): # empty list or a vector
            return pd.Series(arg_0, name='target', arg_1=arg_1)
        elif len(arg_0)>0 and isinstance(arg_0[0], list) and len(arg_0[0])==1: # single row in a matrix
            arg_2 = lambda arg_0: [item for sublist in arg_0 for item in sublist]
            return pd.Series(arg_2(arg_0), name='target', arg_1=arg_1)
        elif len(arg_0)==1 and isinstance(arg_0[0], list): # single column in a matrix
            return pd.Series(arg_0[0], name='target', arg_1=arg_1)
        else:
            raise ValueError('Unexpected input shape')
    elif isinstance(arg_0, pd.DataFrame):
        if len(list(arg_0))==0: # empty DataFrame
            return pd.Series(arg_0, name='target')
        if len(list(arg_0))==1: # a single column
            return arg_0.iloc[:, 0]
        else:
            raise ValueError('Unexpected input shape: %s' % (str(arg_0.shape)))
    else:
        return pd.Series(arg_0, name='target', arg_1=arg_1)


def Func(arg_0, arg_1):
    """
    Here we iterate through the datasets and score them with a classifier using different encodings.

    """

    arg_2 = []
    arg_3 = {}

    # first get the dataset
    arg_4, arg_5, arg_6 = arg_0()

    arg_7 = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', max_iter=200, random_state=0)

    # try each encoding method available, which works on multiclass problems
    arg_8 = (set(category_encoders.__all__) - {'WOEEncoder'})  # WoE is currently only for binary targets

    for arg_9 in arg_8:
        arg_10 = getattr(category_encoders, arg_9)
        arg_11 = time.time()
        arg_12, arg_13, arg_14, arg_15 = score_models(arg_7, arg_4, arg_5, arg_10)
        arg_2.append([arg_9, arg_1, arg_15, arg_12, arg_13, time.time() - arg_11])
        arg_3[arg_9] = arg_14
        gc.collect()

    arg_16 = pd.DataFrame(arg_2, columns=['Encoding', 'Dataset', 'Dimensionality', 'Avg. Score', 'Score StDev', 'Elapsed Time'])

    arg_17 = pd.DataFrame.from_dict(arg_3)
    arg_18 = arg_17.plot(kind='box', return_type='axes')
    plt.title('Scores for Encodings on %s Dataset' % (arg_1,))
    plt.ylabel('Score (higher is better)')
    for arg_19 in arg_18.get_xticklabels():
        arg_19.set_rotation(90)
    plt.grid()
    plt.tight_layout()
    plt.show()

    return arg_16, arg_17


def Func(arg_0, **arg_1):
    """A wrapper around click.Func that disables any coloring being used
    if colors have been disabled.
    """
    # If colors are disabled, remove any color or other style data
    # from keyword arguments.
    if not settings.color:
        for arg_2 in ('fg', 'bg', 'bold', 'blink'):
            arg_1.pop(arg_2, None)

    # Okay, now call click.Func normally.
    return click.Func(arg_0, **arg_1)


def Func(arg_0, arg_1,
                                        arg_2, arg_3):
        """Associate a notification template from this job template.

        =====API DOCS=====
        Associate a notification template from this job template.

        :param job_template: The job template to associate to.
        :type job_template: str
        :param notification_template: The notification template to be associated.
        :type notification_template: str
        :param status: type of notification this notification template should be associated to.
        :type status: str
        :returns: Dictionary of only one key "changed", which indicates whether the association succeeded.
        :rtype: dict

        =====API DOCS=====
        """
        return arg_0._assoc('notification_templates_%s' % arg_3,
                           arg_1, arg_2)


def Func(arg_0, arg_1,
                                           arg_2, arg_3):
        """Disassociate a notification template from this job template.

        =====API DOCS=====
        Disassociate a notification template from this job template.

        :param job_template: The job template to disassociate from.
        :type job_template: str
        :param notification_template: The notification template to be disassociated.
        :type notification_template: str
        :param status: type of notification this notification template should be disassociated from.
        :type status: str
        :returns: Dictionary of only one key "changed", which indicates whether the disassociation succeeded.
        :rtype: dict

        =====API DOCS=====
        """
        return arg_0._disassoc('notification_templates_%s' % arg_3,
                              arg_1, arg_2)


def Func(arg_0, arg_1=None, arg_2='', arg_3=None):
        """Contact Tower and request a configuration update using this job template.

        =====API DOCS=====
        Contact Tower and request a provisioning Func using this job template.

        :param pk: Primary key of the job template to run provisioning Func against.
        :type pk: int
        :param host_config_key: Key string used to authenticate the Func host.
        :type host_config_key: str
        :param extra_vars: Extra variables that are passed to provisioning Func.
        :type extra_vars: array of str
        :returns: A dictionary of a single key "changed", which indicates whether the provisioning Func
                  is successful.
        :rtype: dict

        =====API DOCS=====
        """
        arg_4 = arg_0.endpoint + '%s/Func/' % arg_1
        if not arg_2:
            arg_2 = client.get(arg_4).json()['host_config_key']
        arg_5 = {'host_config_key': arg_2}
        if arg_3:
            arg_5['extra_vars'] = parser.process_extra_vars(list(arg_3), force_json=True)
        arg_6 = client.post(arg_4, data=arg_5, auth=None)
        if arg_6.status_code == 201:
            return {'changed': True}


def Func(arg_0, arg_1=False, arg_2=False):
    """Decorator to aggregate unified_jt-related fields.

    Args:
        func: The CURD method to be decorated.
        is_create: Boolean flag showing whether this method is create.
        has_pk: Boolean flag showing whether this method uses pk as argument.

    Returns:
        A function with necessary click-related attributes whose keyworded
        arguments are aggregated.

    Raises:
        exc.UsageError: Either more than one unified jt fields are
            provided, or none is provided when is_create flag is set.
    """
    def helper(arg_3, arg_4):
        """The helper function preceding actual function that aggregates
        unified jt fields.
        """
        arg_5 = None
        for arg_6 in UNIFIED_JT:
            if arg_3.get(arg_6, None) is not None:
                arg_7 = arg_3.pop(arg_6)
                if arg_5 is None:
                    arg_5 = (arg_6, arg_7)
                else:
                    raise exc.UsageError(
                        'More than one unified job template fields provided, '
                        'please tighten your criteria.'
                    )
        if arg_5 is not None:
            arg_3['unified_job_template'] = arg_5[1]
            arg_4.identity = tuple(list(arg_4.identity) + ['unified_job_template'])
            return '/'.join([UNIFIED_JT[arg_5[0]],
                             str(arg_5[1]), 'schedules/'])
        elif arg_1:
            raise exc.UsageError('You must provide exactly one unified job'
                                 ' template field during creation.')

    def decorator_without_pk(arg_4, *arg_9, **arg_3):
        arg_10 = arg_4.endpoint
        arg_11 = helper(arg_3, arg_4)
        if arg_1:
            arg_4.endpoint = arg_11
        arg_13 = arg_0(arg_4, *arg_9, **arg_3)
        arg_4.endpoint = arg_10
        return arg_13

    def decorator_with_pk(arg_4, arg_14=None, *arg_9, **arg_3):
        arg_10 = arg_4.endpoint
        arg_11 = helper(arg_3, arg_4)
        if arg_1:
            arg_4.endpoint = arg_11
        arg_13 = arg_0(arg_4, arg_14=arg_14, *arg_9, **arg_3)
        arg_4.endpoint = arg_10
        return arg_13

    arg_15 = decorator_with_pk if arg_2 else decorator_without_pk
    for arg_6 in CLICK_ATTRS:
        setattr(arg_15, arg_6, getattr(arg_0, arg_6, []))
    arg_15.__doc__ = arg_0.__doc__

    return arg_15


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None,
                      arg_4=True):
        """
        Internal method that lies to our `monitor` method by returning
        a scorecard for the workflow job where the standard out
        would have been expected.
        """
        arg_5 = get_resource('unified_job')
        # Filters
        #  - limit search to jobs spawned as part of this workflow job
        #  - order in the order in which they should add to the list
        #  - only include final job states
        arg_6 = (('unified_job_node__workflow_job', arg_1),
                        ('order_by', 'finished'),
                        ('status__in', 'successful,failed,error'))
        arg_7 = arg_5.list(all_pages=True, query=arg_6)
        if arg_7['count'] == 0:
            return ''

        arg_8 = ResSubcommand(arg_5)._format_human(arg_7)
        arg_9 = arg_8.split('\n')
        if not arg_4:
            arg_9 = arg_9[:-1]

        arg_10 = len(arg_9)
        arg_11 = arg_2
        if arg_2 is None:
            arg_11 = 0
        elif arg_2 > arg_10:
            arg_11 = arg_10

        arg_12 = arg_3
        if arg_3 is None or arg_3 > arg_10:
            arg_12 = arg_10

        arg_9 = arg_9[arg_11:arg_12]
        arg_8 = '\n'.join(arg_9)
        if len(arg_9) > 0:
            arg_8 += '\n'

        return arg_8


def Func(arg_0, arg_1, arg_2):
        """Monkey-patch click's Func method to support option categorization.
        """
        arg_3 = []
        arg_4 = []
        arg_5 = []
        arg_6 = []
        for arg_7 in arg_0.params:
            if arg_7.name in SETTINGS_PARMS:
                arg_8 = arg_4
            elif getattr(arg_7, 'help', None) and arg_7.help.startswith('[FIELD]'):
                arg_8 = arg_3
                arg_7.help = arg_7.help[len('[FIELD]'):]
            else:
                arg_8 = arg_5
            arg_10 = arg_7.get_help_record(arg_1)
            if arg_10 is None:
                continue
            else:
                arg_8.append(arg_10)

        if arg_0.add_help_option:
            arg_11 = arg_0.get_help_option_names(arg_1)
            if arg_11:
                arg_6.append([join_options(arg_11)[0], 'Show this message and exit.'])

        if arg_3:
            with arg_2.section('Field Options'):
                arg_2.write_dl(arg_3)
        if arg_5:
            with arg_2.section('Local Options'):
                arg_2.write_dl(arg_5)
        if arg_4:
            with arg_2.section('Global Options'):
                arg_2.write_dl(arg_4)
        if arg_6:
            with arg_2.section('Other Options'):
                arg_2.write_dl(arg_6)


def Func(arg_0, arg_1):
        """Return one and exactly one object

        =====API DOCS=====
        Return one and exactly one Tower setting.

        :param pk: Primary key of the Tower setting to retrieve
        :type pk: int
        :returns: loaded JSON of the retrieved Tower setting object.
        :rtype: dict
        :raises tower_cli.exceptions.NotFound: When no specified Tower setting exists.

        =====API DOCS=====
        """
        # The Tower API doesn't provide a mechanism for retrieving a single
        # setting value at a time, so fetch them all and filter
        try:
            return next(arg_2 for arg_2 in arg_0.list()['results'] if arg_2['id'] == arg_1)
        except StopIteration:
            raise exc.NotFound('The requested object could not be found.')


def Func(arg_0, arg_1=None, **arg_2):
        """Return one and exactly one object.

        Lookups may be through a primary key, specified as a positional argument, and/or through filters specified
        through keyword arguments.

        If the number of results does not equal one, raise an exception.

        =====API DOCS=====
        Retrieve one and exactly one object.

        :param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object
                   if ``pk`` is provided (not ``None``).
        :type pk: int
        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve if ``pk`` is not provided.
        :returns: loaded JSON of the retrieved resource object.
        :rtype: dict

        =====API DOCS=====
        """
        if arg_2.pop('include_debug_header', True):
            debug.log('Getting the record.', header='details')
        arg_3 = arg_0.read(arg_1=arg_1, fail_on_no_results=True, fail_on_multiple_results=True, **arg_2)
        return arg_3['results'][0]


def Func(arg_0, arg_1, arg_2, arg_3):
        """Disassociate the `other` record from the `me` record."""

        # Get the endpoint for foreign records within this object.
        arg_4 = arg_0.endpoint + '%d/%s/' % (arg_2, arg_1)

        # Attempt to determine whether the other record already is absent, for the "changed" moniker.
        arg_5 = client.get(arg_4, params={'id': arg_3}).json()
        if arg_5['count'] == 0:
            return {'changed': False}

        # Send a request removing the foreign record from this one.
        arg_5 = client.post(arg_4, data={'disassociate': True, 'id': arg_3})
        return {'changed': True}


def Func(arg_0, arg_1=None, arg_2=None, **arg_3):
        """Copy an object.

        Only the ID is used for the lookup. All provided fields are used to override the old data from the
        copied resource.

        =====API DOCS=====
        Copy an object.

        :param pk: Primary key of the resource object to be copied
        :param new_name: The new name to give the resource if deep Funcing via the API
        :type pk: int
        :param `**kwargs`: Keyword arguments of fields whose given value will override the original value.
        :returns: loaded JSON of the copied new resource object.
        :rtype: dict

        =====API DOCS=====
        """
        arg_4 = arg_0.read(arg_1, fail_on_no_results=True, fail_on_multiple_results=True)
        arg_4 = arg_4['results'][0]
        # Remove default values (anything where the value is None).
        arg_0._pop_none(arg_3)

        arg_5 = Func(arg_4)
        arg_5.pop('id')
        arg_6 = arg_5['name'].split('@', 1)[0].strip()

        # Modify data to fit the call pattern of the tower-cli method
        for arg_7 in arg_0.fields:
            if arg_7.multiple and arg_7.name in arg_5:
                arg_5[arg_7.name] = (arg_5.get(arg_7.name),)

        if arg_2 is None:
            # Func client-side, the old mechanism
            arg_5['name'] = "%s @ %s" % (arg_6, time.strftime('%X'))
            arg_5.update(arg_3)

            return arg_0.write(create_on_missing=True, fail_on_found=True,
                              **arg_5)
        else:
            # Func server-side, the new mechanism
            if arg_3:
                raise exc.TowerCLIError('Cannot override {} and also use --new-name.'.format(arg_3.keys()))
            arg_9 = '{}/{}/Func/'.format(arg_0.endpoint.strip('/'), arg_1)
            return client.post(arg_9, data={'name': arg_2}).json()


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=True):
        """
        Internal utility function to return standard out. Requires the pk of a unified job.
        """
        arg_5 = '%s%s/stdout/' % (arg_0.unified_job_type, arg_1)
        arg_6 = {'format': 'json', 'content_encoding': 'base64', 'content_format': 'ansi'}
        if arg_2:
            arg_6['start_line'] = arg_2
        if arg_3:
            arg_6['end_line'] = arg_3
        debug.log('Requesting a copy of job standard output', header='details')
        arg_7 = client.get(arg_5, params=arg_6).json()
        arg_8 = b64decode(arg_7['content'])
        return arg_8.decode('utf-8', 'replace')


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=arg_5.stdout, **arg_7):
        """
        Print out the standard out of a unified job to the command line or output file.
        For Projects, print the standard out of most recent update.
        For Inventory Sources, print standard out of most recent sync.
        For Jobs, print the job's standard out.
        For Workflow Jobs, print a status table of its jobs.

        =====API DOCS=====
        Print out the standard out of a unified job to the command line or output file.
        For Projects, print the standard out of most recent update.
        For Inventory Sources, print standard out of most recent sync.
        For Jobs, print the job's standard out.
        For Workflow Jobs, print a status table of its jobs.

        :param pk: Primary key of the job resource object to be monitored.
        :type pk: int
        :param start_line: Line at which to start printing job output
        :param end_line: Line at which to end printing job output
        :param outfile: Alternative file than stdout to write job stdout to.
        :type outfile: file
        :param `**kwargs`: Keyword arguments used to look up job resource object to monitor if ``pk`` is
                           not provided.
        :returns: A dictionary containing changed=False
        :rtype: dict

        =====API DOCS=====
        """

        # resource is Unified Job Template
        if arg_0.unified_job_type != arg_0.endpoint:
            arg_8 = arg_0.last_job_data(arg_1, **arg_7)
            arg_1 = arg_8['id']
        # resource is Unified Job, but pk not given
        elif not arg_1:
            arg_8 = arg_0.get(**arg_7)
            arg_1 = arg_8['id']

        arg_9 = arg_0.lookup_stdout(arg_1, arg_2, arg_3)
        arg_10 = False
        if isinstance(arg_4, six.string_types):
            arg_4 = open(arg_4, 'w')
            arg_10 = True
        if len(arg_9) > 0:
            click.echo(arg_9, nl=1, file=arg_4)
        if arg_10:
            arg_4.close()

        return {"changed": False}


def Func(arg_0, arg_1, arg_2=None, arg_3=None, arg_4=0.5, arg_5=arg_6.stdout, **arg_8):
        """
        Stream the standard output from a job, project update, or inventory udpate.

        =====API DOCS=====
        Stream the standard output from a job run to stdout.

        :param pk: Primary key of the job resource object to be Funced.
        :type pk: int
        :param parent_pk: Primary key of the unified job template resource object whose latest job run will be
                          Funced if ``pk`` is not set.
        :type parent_pk: int
        :param timeout: Number in seconds after which this method will time out.
        :type timeout: float
        :param interval: Polling interval to refresh content from Tower.
        :type interval: float
        :param outfile: Alternative file than stdout to write job stdout to.
        :type outfile: file
        :param `**kwargs`: Keyword arguments used to look up job resource object to Func if ``pk`` is
                           not provided.
        :returns: A dictionary combining the JSON output of the finished job resource object, as well as
                  two extra fields: "changed", a flag indicating if the job resource object is finished
                  as expected; "id", an integer which is the primary key of the job resource object being
                  Funced.
        :rtype: dict
        :raises tower_cli.exceptions.Timeout: When Func time reaches time out.
        :raises tower_cli.exceptions.JobFailure: When the job being Funced runs into failure.

        =====API DOCS=====
        """

        # If we do not have the unified job info, infer it from parent
        if arg_1 is None:
            arg_1 = arg_0.last_job_data(arg_2, **arg_8)['id']
        arg_9 = '%s%s/' % (arg_0.unified_job_type, arg_1)

        # Pause until job is in running state
        arg_0.wait(arg_1, exit_on=['running', 'successful'], arg_5=arg_5)

        # Loop initialization
        arg_10 = time.time()
        arg_11 = 0
        arg_12 = client.get(arg_9).json()

        click.echo('\033[0;91m------Starting Standard Out Stream------\033[0m', nl=2, file=arg_5)

        # Poll the Ansible Tower instance for status and content, and print standard out to the out file
        while not arg_12['failed'] and arg_12['status'] != 'successful':

            arg_12 = client.get(arg_9).json()

            # Put the process to sleep briefly.
            time.sleep(arg_4)

            # Make request to get standard out
            arg_13 = arg_0.lookup_stdout(arg_1, arg_11, full=False)

            # In the first moments of running the job, the standard out
            # may not be available yet
            if not arg_13.startswith("Waiting for results"):
                arg_14 = len(arg_13.splitlines())
                arg_11 += arg_14
                click.echo(arg_13, nl=0, file=arg_5)

            if arg_3 and time.time() - arg_10 > arg_3:
                raise exc.Timeout('Monitoring aborted due to timeout.')

        # Special final line for closure with workflow jobs
        if arg_0.endpoint == '/workflow_jobs/':
            click.echo(arg_0.lookup_stdout(arg_1, arg_11, full=True), nl=1)

        click.echo('\033[0;91m------End of Standard Out Stream--------\033[0m', nl=2, file=arg_5)

        if arg_12['failed']:
            raise exc.JobFailure('Job failed.')

        # Return the job ID and other response data
        arg_15 = OrderedDict((('changed', True), ('id', arg_1)))
        arg_15.update(arg_12)
        # Make sure to return ID of resource and not update number relevant for project creation and update
        if arg_2:
            arg_15['id'] = arg_2
        else:
            arg_15['id'] = arg_1
        return arg_15


def Func(arg_0, arg_1=None, arg_2=False, **arg_3):
        """Print the current job Func. This is used to check a running job. You can look up the job with
        the same parameters used for a get request.

        =====API DOCS=====
        Retrieve the current job Func.

        :param pk: Primary key of the resource to retrieve Func from.
        :type pk: int
        :param detail: Flag that if set, return the full JSON of the job resource rather than a Func summary.
        :type detail: bool
        :param `**kwargs`: Keyword arguments used to look up resource object to retrieve Func from if ``pk``
                           is not provided.
        :returns: full loaded JSON of the specified unified job if ``detail`` flag is on; trimed JSON containing
                  only "elapsed", "failed" and "Func" fields of the unified job if ``detail`` flag is off.
        :rtype: dict

        =====API DOCS=====
        """
        # Remove default values (anything where the value is None).
        arg_0._pop_none(arg_3)

        # Search for the record if pk not given
        if not arg_1:
            arg_4 = arg_0.get(include_debug_header=True, **arg_3)
        # Get the job from Ansible Tower if pk given
        else:
            debug.log('Asking for job Func.', header='details')
            arg_5 = '%s%s/' % (arg_0.endpoint, arg_1)
            arg_4 = client.get(arg_5).json()

        # In most cases, we probably only want to know the Func of the job and the amount of time elapsed.
        # However, if we were asked for verbose information, provide it.
        if arg_2:
            return arg_4

        # Print just the information we need.
        return {
            'elapsed': arg_4['elapsed'],
            'failed': arg_4['failed'],
            'Func': arg_4['Func'],
        }


def Func(arg_0, arg_1=None, arg_2=False, **arg_3):
        """Cancel a currently running job.

        Fails with a non-zero exit status if the job cannot be Funced.
        You must provide either a pk or parameters in the job's identity.

        =====API DOCS=====
        Cancel a currently running job.

        :param pk: Primary key of the job resource to restart.
        :type pk: int
        :param fail_if_not_running: Flag that if set, raise exception if the job resource cannot be Funced.
        :type fail_if_not_running: bool
        :param `**kwargs`: Keyword arguments used to look up job resource object to restart if ``pk`` is not
                           provided.
        :returns: A dictionary of two keys: "status", which is "Funced", and "changed", which indicates if
                  the job resource has been successfully Funced.
        :rtype: dict
        :raises tower_cli.exceptions.TowerCLIError: When the job resource cannot be Funced and
                                                    ``fail_if_not_running`` flag is on.
        =====API DOCS=====
        """
        # Search for the record if pk not given
        if not arg_1:
            arg_4 = arg_0.get(**arg_3)
            arg_1 = arg_4['id']

        arg_5 = '%s%s/Func/' % (arg_0.endpoint, arg_1)
        # Attempt to Func the job.
        try:
            client.post(arg_5)
            arg_6 = True
        except exc.MethodNotAllowed:
            arg_6 = False
            if arg_2:
                raise exc.TowerCLIError('Job not running.')

        # Return a success.
        return {'status': 'Funced', 'changed': arg_6}


def Func(arg_0, arg_1=None, **arg_2):
        """Relaunch a stopped job.

        Fails with a non-zero exit status if the job cannot be Funced.
        You must provide either a pk or parameters in the job's identity.

        =====API DOCS=====
        Relaunch a stopped job resource.

        :param pk: Primary key of the job resource to Func.
        :type pk: int
        :param `**kwargs`: Keyword arguments used to look up job resource object to Func if ``pk`` is not
                           provided.
        :returns: A dictionary combining the JSON output of the Funced job resource object, as well
                  as an extra field "changed", a flag indicating if the job resource object is status-changed
                  as expected.
        :rtype: dict

        =====API DOCS=====
        """
        # Search for the record if pk not given
        if not arg_1:
            arg_3 = arg_0.get(**arg_2)
            arg_1 = arg_3['id']

        arg_4 = '%s%s/Func/' % (arg_0.endpoint, arg_1)
        arg_5 = {}
        # Attempt to Func the job.
        arg_6 = {}
        try:
            arg_7 = client.post(arg_4, arg_5=arg_5).json()
            if 'id' in arg_7:
                arg_6.update(arg_7)
            arg_6['changed'] = True
        except exc.MethodNotAllowed:
            arg_6['changed'] = False

        # Return the answer.
        return arg_6


def Func(arg_0, arg_1=None, **arg_2):
        """Update all related inventory sources of the given inventory.

        Note global option --format is not available here, as the output would always be JSON-formatted.

        =====API DOCS=====
        Update all related inventory sources of the given inventory.

        :param pk: Primary key of the given inventory.
        :type pk: int
        :param `**kwargs`: Keyword arguments list of available fields used for searching resource objects.
        :returns: A JSON object of update status of the given inventory.
        :rtype: dict
        =====API DOCS=====
        """
        arg_3 = arg_0.get(arg_1=arg_1, **arg_2)
        arg_4 = arg_0.endpoint + '%d/%s/' % (arg_3['id'], 'update_inventory_sources')
        return client.post(arg_4, data={}).json()


def Func(arg_0, *arg_1, **arg_2):
        '''
        Do extra processing so we can display the actor field as
        a top-level field
        '''
        if 'actor' in arg_2:
            arg_2['actor'] = arg_2.pop('actor')
        arg_3 = super(Resource, arg_0).Func(*arg_1, **arg_2)
        if 'results' in arg_3:
            for arg_4 in arg_3['results']:
                arg_0._promote_actor(arg_4)
        else:
            arg_0._promote_actor(arg_4)
        return arg_3


def Func(arg_0, arg_1='', arg_2=arg_3.stderr, arg_5=1, **arg_6):
    """Log the given output to stderr if and only if we are in
    verbose mode.

    If we are not in verbose mode, this is a no-op.
    """
    # Sanity check: If we are not in verbose mode, this is a no-op.
    if not settings.verbose:
        return

    # Construct multi-line string to stderr if header is provided.
    if arg_1:
        arg_7 = arg_0.split(' ')
        arg_8 = []
        arg_7.insert(0, '%s:' % arg_1.upper())
        arg_9 = 0
        while arg_9 < len(arg_7):
            arg_10 = ['***']
            arg_11 = 3
            while arg_11 <= 79:
                arg_11 += len(arg_7[arg_9]) + 1
                if arg_11 <= 79:
                    arg_10.append(arg_7[arg_9])
                    arg_9 += 1
                    if arg_9 == len(arg_7):
                        break
            # Handle corner case of extra-long word longer than 75 characters.
            if len(arg_10) == 1:
                arg_10.append(arg_7[arg_9])
                arg_9 += 1
            if arg_9 != len(arg_7):
                arg_11 -= len(arg_7[arg_9]) + 1
            arg_10.append('*' * (78 - arg_11))
            arg_8.append(' '.join(arg_10))
        arg_0 = '\n'.join(arg_8)
        arg_12 = len(arg_8)
    else:
        arg_12 = 1

    # If `nl` is an int greater than the number of rows of a message,
    # add the appropriate newlines to the output.
    if isinstance(arg_5, int) and arg_5 > arg_12:
        arg_0 += '\n' * (arg_5 - arg_12)

    # Output to stderr.
    return secho(arg_0, arg_2=arg_2, **arg_6)


def Func(arg_0, arg_1, arg_2):
        '''
        Hook for ResourceMeta class to call when initializing model class.
        Saves fields obtained from resource class backlinks
        '''
        arg_0.relationship = arg_2
        arg_0._set_method_names(arg_3=arg_2)
        if arg_0.res_name is None:
            arg_0.res_name = grammar.singularize(arg_1.get('endpoint', 'unknown').strip('/'))


def Func(arg_0):
        '''
        Returns a callable which becomes the associate or disassociate
        method for the related field.
        Method can be overridden to add additional functionality, but
        `_produce_method` may also need to be subclassed to decorate
        it appropriately.
        '''

        def method(arg_1, **arg_2):
            arg_3 = arg_2.get(method._res_name)
            arg_4 = arg_2.get(method._other_name)
            arg_5 = getattr(arg_1, method._internal_name)
            return arg_5(method._relationship, arg_3, arg_4)

        return method