def Func(arg_0, arg_1, arg_2, arg_3=None):
        """
        Saves this component's managed variables.

        Args:
            sess: The session for which to Func the managed variables.
            Func_path: The path to Func data to.
            timestep: Optional, the timestep to append to the file name.

        Returns:
            Checkpoint path where the model was Funcd.
        """

        if arg_0._Funcr is None:
            raise TensorForceError("register_Funcr_ops should be called before Func")
        return arg_0._Funcr.Func(
            arg_1=arg_1,
            arg_2=arg_2,
            global_step=arg_3,
            write_meta_graph=False,
            write_state=True,  # Do we need this?
        )


def Func(arg_0, arg_1, arg_2):
        """
        Restores the values of the managed variables from disk location.

        Args:
            sess: The session for which to save the managed variables.
            save_path: The path used to save the data to.
        """

        if arg_0._saver is None:
            raise TensorForceError("register_saver_ops should be called before Func")
        arg_0._saver.Func(arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):
        """
        Process state.

        Args:
            tensor: tensor to Func

        Returns: Funced state

        """
        for arg_2 in arg_0.preFuncors:
            arg_1 = arg_2.Func(arg_1=arg_1)
        return arg_1


def Func(arg_0, arg_1):
        """
        Shape of preprocessed state given original shape.

        Args:
            shape: original state shape

        Returns: processed state shape
        """
        for arg_2 in arg_0.preprocessors:
            arg_1 = arg_2.Func(arg_1=arg_1)
        return arg_1


def Func(arg_0):
        """
        Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.
        """
        super(MemoryModel, arg_0).Func()
        arg_0.optimizer_spec = dict(
            type='global_optimizer',
            optimizer=arg_0.optimizer_spec
        )


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=0.0, arg_5=0):
        """
        Creates and returns the TensorFlow operations for calculating the sequence of discounted cumulative rewards
        for a given sequence of single rewards.

        Example:
        single rewards = 2.0 1.0 0.0 0.5 1.0 -1.0
        terminal = False, False, False, False True False
        gamma = 0.95
        final_reward = 100.0 (only matters for last episode (r=-1.0) as this episode has no terminal signal)
        horizon=3
        output = 2.95 1.45 1.38 1.45 1.0 94.0

        Args:
            terminal: Tensor (bool) holding the is-terminal sequence. This sequence may contain more than one
                True value. If its very last element is False (not terminating), the given `final_reward` value
                is assumed to follow the last value in the single rewards sequence (see below).
            reward: Tensor (float) holding the sequence of single rewards. If the last element of `terminal` is False,
                an assumed last reward of the value of `final_reward` will be used.
            discount (float): The discount factor (gamma). By default, take the Model's discount factor.
            final_reward (float): Reward value to use if last episode in sequence does not terminate (terminal sequence
                ends with False). This value will be ignored if horizon == 1 or discount == 0.0.
            horizon (int): The length of the horizon (e.g. for n-step cumulative rewards in continuous tasks
                without terminal signals). Use 0 (default) for an infinite horizon. Note that horizon=1 leads to the
                exact same results as a discount factor of 0.0.

        Returns:
            Discounted cumulative reward tensor with the same shape as `reward`.
        """

        # By default -> take Model's gamma value
        if arg_3 is None:
            arg_3 = arg_0.discount

        # Accumulates discounted (n-step) reward (start new if terminal)
        def cumulate(arg_6, arg_7):
            arg_8, arg_9, arg_10, arg_11 = arg_7
            return tf.where(
                # If terminal, start new cumulation.
                condition=arg_9,
                x=arg_8,
                y=tf.where(
                    # If we are above the horizon length (H) -> subtract discounted value from H steps back.
                    condition=arg_10,
                    x=(arg_8 + arg_6 * arg_3 - arg_11),
                    y=(arg_8 + arg_6 * arg_3)
                )
            )

        # Accumulates length of episodes (starts new if terminal)
        def len_(arg_6, arg_12):
            return tf.where(
                condition=arg_12,
                # Start counting from 1 after is-terminal signal
                x=tf.ones(shape=(), dtype=tf.int32),
                # Otherwise, increase length by 1
                y=arg_6 + 1
            )

        # Reverse, since reward cumulation is calculated right-to-left, but tf.scan only works left-to-right.
        arg_2 = tf.reverse(tensor=arg_2, axis=(0,))
        # e.g. -1.0 1.0 0.5 0.0 1.0 2.0
        arg_1 = tf.reverse(tensor=arg_1, axis=(0,))
        # e.g. F T F F F F

        # Store the steps until end of the episode(s) determined by the input terminal signals (True starts new count).
        arg_13 = tf.scan(fn=len_, elems=arg_1, initializer=0)
        # e.g. 1 1 2 3 4 5
        arg_14 = tf.greater(arg_13, tf.fill(dims=tf.shape(arg_13), value=arg_5))
        # e.g. F F F F T T

        # Calculate the horizon-subtraction value for each step.
        if arg_5 > 0:
            arg_15 = tf.map_fn(lambda x: (arg_3 ** arg_5) * x, arg_2, dtype=tf.float32)
            # Shift right by size of horizon (fill rest with 0.0).
            arg_15 = tf.concat([np.zeros(shape=(arg_5,)), arg_15], axis=0)
            arg_15 = tf.slice(arg_15, begin=(0,), size=tf.shape(arg_2))
            # e.g. 0.0, 0.0, 0.0, -1.0*g^3, 1.0*g^3, 0.5*g^3
        # all 0.0 if infinite horizon (special case: horizon=0)
        else:
            arg_15 = tf.zeros(shape=tf.shape(arg_2))

        # Now do the scan, each time summing up the previous step (discounted by gamma) and
        # subtracting the respective `horizon_subtraction`.
        arg_2 = tf.scan(
            fn=cumulate,
            elems=(arg_2, arg_1, arg_14, arg_15),
            initializer=arg_4 if arg_5 != 1 else 0.0
        )
        # Re-reverse again to match input sequences.
        return tf.reverse(tensor=arg_2, axis=(0,))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5,
                             arg_6, arg_7, arg_8, arg_9=None):
        """
        Creates the TensorFlow operations for calculating the loss per batch instance.

        Args:
            states: Dict of state tensors.
            internals: Dict of prior internal state tensors.
            actions: Dict of action tensors.
            terminal: Terminal boolean tensor.
            reward: Reward tensor.
            next_states: Dict of successor state tensors.
            next_internals: List of posterior internal state tensors.
            update: Boolean tensor indicating whether this call happens during an update.
            reference: Optional reference tensor(s), in case of a comparative loss.

        Returns:
            Loss per instance tensor.
        """
        raise NotImplementedError


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9=None):
        """
        Creates the TensorFlow operations for calculating the full loss of a batch.

        Args:
            states: Dict of state tensors.
            internals: List of prior internal state tensors.
            actions: Dict of action tensors.
            terminal: Terminal boolean tensor.
            reward: Reward tensor.
            next_states: Dict of successor state tensors.
            next_internals: List of posterior internal state tensors.
            update: Boolean tensor indicating whether this call happens during an update.
            reference: Optional reference tensor(s), in case of a comparative loss.

        Returns:
            Loss tensor.
        """
        # Mean loss per instance
        arg_10 = arg_0.fn_loss_per_instance(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7,
            arg_8=arg_8,
            arg_9=arg_9
        )

        # Returns no-op.
        arg_11 = arg_0.memory.update_batch(arg_10=arg_10)
        with tf.control_dependencies(control_inputs=(arg_11,)):
            arg_12 = tf.reduce_mean(input_tensor=arg_10, axis=0)

            # Loss without regularization summary.
            if 'losses' in arg_0.summary_labels:
                tf.contrib.summary.scalar(arg_14='loss-without-regularization', tensor=arg_12)

            # Regularization losses.
            arg_13 = arg_0.fn_regularization_losses(arg_1=arg_1, arg_2=arg_2, arg_8=arg_8)
            if len(arg_13) > 0:
                arg_12 += tf.add_n(inputs=[arg_13[arg_14] for arg_14 in sorted(arg_13)])
                if 'regularization' in arg_0.summary_labels:
                    for arg_14 in sorted(arg_13):
                        tf.contrib.summary.scalar(arg_14=('regularization/' + arg_14), tensor=arg_13[arg_14])

            # Total loss summary.
            if 'losses' in arg_0.summary_labels or 'total-loss' in arg_0.summary_labels:
                tf.contrib.summary.scalar(arg_14='total-loss', tensor=arg_12)

            return arg_12


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6=None, arg_7=None):
        """
        Creates the TensorFlow operations for performing an optimization update step based
        on the given input states and actions batch.

        Args:
            states: Dict of state tensors.
            internals: List of prior internal state tensors.
            actions: Dict of action tensors.
            terminal: Terminal boolean tensor.
            reward: Reward tensor.
            next_states: Dict of successor state tensors.
            next_internals: List of posterior internal state tensors.

        Returns:
            The optimization operation.
        """
        arg_8 = arg_0.optimizer_arguments(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7
        )
        return arg_0.optimizer.minimize(**arg_8)


def Func(arg_0, arg_1=None):
        """
        Creates a distribution from a specification dict.
        """
        arg_2 = util.get_object(
            obj=arg_0,
            predefined_objects=tensorforce.core.distributions.distributions,
            arg_1=arg_1
        )
        assert isinstance(arg_2, Distribution)
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """
        Utility method for unbuffered observing where each tuple is inserted into TensorFlow via
        a single session call, thus avoiding race conditions in multi-threaded mode.

        Observe full experience  tuplefrom the environment to learn from. Optionally pre-processes rewards
        Child classes should call super to get the processed reward
        EX: terminal, reward = super()...

        Args:
            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.
            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.
            internals (any): Internal list.
            terminal (bool): boolean indicating if the episode terminated after the observation.
            reward (float): scalar reward that resulted from executing the action.
        """
        # TODO probably unnecessary here.
        arg_0.current_terminal = arg_5
        arg_0.current_reward = arg_4
        # print('action = {}'.format(actions))
        if arg_0.unique_state:
            arg_1 = dict(state=arg_1)
        if arg_0.unique_action:
            arg_2 = dict(action=arg_2)

        arg_0.episode = arg_0.model.Func(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_5=arg_0.current_terminal,
            arg_4=arg_0.current_reward
        )


def Func(arg_0, arg_1):
        """
        Returns a named tensor if available.

        Returns:
            valid: True if named tensor found, False otherwise
            tensor: If valid, will be a tensor, otherwise None
        """
        if arg_1 in arg_0.named_tensors:
            return True, arg_0.named_tensors[arg_1]
        else:
            return False, None


def Func(arg_0, arg_1, arg_2=None):
        """
        Stores a transition in replay memory.

        If the memory is full, the oldest entry is replaced.
        """
        if not arg_0._isfull():
            arg_0._memory.append(None)
        arg_3 = arg_0._next_position_then_increment()
        arg_4 = 0 if arg_0._memory[arg_3] is None \
            else (arg_0._memory[arg_3].priority or 0)
        arg_5 = _SumRow(arg_1, arg_2)
        arg_0._memory[arg_3] = arg_5
        arg_0._update_internal_nodes(
            arg_3, (arg_5.priority or 0) - arg_4)


def Func(arg_0, arg_1, arg_2):
        """
        Change the priority of a leaf node
        """
        arg_3 = arg_1 + (arg_0._capacity - 1)
        return arg_0._Func(arg_3, arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Change the priority of a leaf node.
        """
        arg_3, arg_4 = arg_0._memory[arg_1]
        arg_4 = arg_4 or 0
        arg_0._memory[arg_1] = _SumRow(arg_3, arg_2)
        arg_0._update_internal_nodes(arg_1, arg_2 - arg_4)


def Func(arg_0):
        """
        Similar to position++.
        """
        arg_1 = arg_0._capacity - 1
        arg_2 = arg_1 + arg_0._position
        arg_0._position = (arg_0._position + 1) % arg_0._capacity
        return arg_2


def Func(arg_0, arg_1):
        """
        Sample random element with priority greater than p.
        """
        arg_2 = 0
        while True:
            arg_3 = 2 * arg_2 + 1
            if arg_3 >= len(arg_0._memory):
                # parent points to a leaf node already.
                return arg_2

            arg_4 = arg_0._memory[arg_3] if arg_3 < arg_0._capacity - 1 \
                else (arg_0._memory[arg_3].priority or 0)
            if arg_1 <= arg_4:
                arg_2 = arg_3
            else:
                if arg_3 + 1 >= len(arg_0._memory):
                    raise RuntimeError('Right child is expected to exist.')
                arg_1 -= arg_4
                arg_2 = arg_3 + 1


def Func(arg_0, arg_1):
        """
        Sample minibatch of size batch_size.
        """
        arg_2 = len(arg_0)
        if arg_2 == 0:
            return []

        arg_3 = arg_0._memory[0] / arg_1
        arg_4 = []
        # if all priorities sum to ~0  choose randomly otherwise random sample
        if abs(arg_0._memory[0]) < util.epsilon:
            arg_4 = np.random.randint(arg_0._capacity - 1, arg_0._capacity - 1 + len(arg_0), size=arg_1).tolist()
        else:
            for arg_5 in xrange(arg_1):
                arg_6 = max(arg_5 * arg_3, 0)
                arg_7 = min((arg_5 + 1) * arg_3, arg_0._memory[0])
                arg_8 = random.uniform(arg_6, arg_7)
                arg_4.append(arg_0._sample_with_priority(arg_8))
        return [(arg_5, arg_0._memory[arg_5]) for arg_5 in arg_4]


def Func(arg_0, arg_1):
        """
        Computes priorities according to loss.

        Args:
            loss_per_instance:

        """
        if arg_0.batch_indices is None:
            raise TensorForceError("Need to call get_batch before each Func call.")
        # if len(loss_per_instance) != len(self.batch_indices):
        #     raise TensorForceError("For all instances a loss value has to be provided.")

        for arg_2, arg_3 in zip(arg_0.batch_indices, arg_1):
            # Sampling priority is proportional to the largest absolute temporal difference error.
            arg_4 = (np.abs(arg_3) + arg_0.prioritization_constant) ** arg_0.prioritization_weight
            arg_0.observations._move(arg_2, arg_4)
            arg_0.none_priority_index += 1


def Func(arg_0):
        """
        Ends our server tcp connection.
        """
        # If we are not connected, return error.
        if not arg_0.socket:
            logging.warning("No active socket to close!")
            return
        # Close our socket.
        arg_0.socket.close()
        arg_0.socket = None


def Func(arg_0, arg_1):
        """Determines whether action is available.
        That is, executing it would change the state.
        """

        arg_2 = np.rot90(arg_0._state, arg_1)
        return arg_0._Func_left(arg_2)


def Func(arg_0, arg_1):
        """Determines whether action 'Left' is available."""

        # True if any field is 0 (empty) on the left of a tile or two tiles can
        # be merged.
        for arg_2 in range(4):
            arg_3 = False
            for arg_4 in range(4):
                arg_3 |= arg_1[arg_2, arg_4] == 0
                if arg_1[arg_2, arg_4] != 0 and arg_3:
                    return True
                if (arg_1[arg_2, arg_4] != 0 and arg_4 > 0 and
                        arg_1[arg_2, arg_4] == arg_1[arg_2, arg_4 - 1]):
                    return True

        return False


def Func(arg_0, arg_1):
        """Execute action, add a new tile, update the score & return the reward."""

        arg_2 = np.rot90(arg_0._state, arg_1)
        arg_3 = arg_0._Func_left(arg_2)
        arg_0._state = np.rot90(arg_2, -arg_1)
        arg_0._score += arg_3

        arg_0.add_random_tile()

        return arg_3


def Func(arg_0, arg_1):
        """Executes action 'Left'."""

        arg_2 = 0

        for arg_3 in range(4):
            # Always the rightmost tile in the current row that was already moved
            arg_4 = -1
            arg_5 = np.zeros((4,), dtype=np.bool)

            for arg_6 in range(4):
                if arg_1[arg_3, arg_6] == 0:
                    continue

                if (arg_4 != -1 and
                        not arg_5[arg_4] and
                        arg_1[arg_3, arg_4] == arg_1[arg_3, arg_6]):
                    # Merge tile with merge_candidate
                    arg_1[arg_3, arg_6] = 0
                    arg_5[arg_4] = True
                    arg_1[arg_3, arg_4] += 1
                    arg_2 += 2 ** arg_1[arg_3, arg_4]

                else:
                    # Move tile to the left
                    arg_4 += 1
                    if arg_6 != arg_4:
                        arg_1[arg_3, arg_4] = arg_1[arg_3, arg_6]
                        arg_1[arg_3, arg_6] = 0

        return arg_2


def Func(arg_0):
        """Adds a random tile to the grid. Assumes that it has empty fields."""

        arg_1, arg_2 = np.where(arg_0._state == 0)
        assert len(arg_1) != 0
        arg_3 = np.random.choice(len(arg_1))
        arg_4 = np.random.choice([1, 2], p=[0.9, 0.1])

        arg_0._state[arg_1[arg_3], arg_2[arg_3]] = arg_4


def Func(arg_0):
        """
        Creates the tf.train.Saver object and stores it in self.saver.
        """
        if arg_0.execution_type == "single":
            arg_1 = arg_0.get_variables(include_submodules=True, include_nontrainable=True)
        else:
            arg_1 = arg_0.global_model.get_variables(include_submodules=True, include_nontrainable=True)

        # global_variables += [self.global_episode, self.global_timestep]

        for arg_2 in arg_0.get_savable_components():
            arg_2.register_saver_ops()

        # TensorFlow saver object
        # TODO potentially make other options configurable via saver spec.
        arg_0.saver = tf.train.Saver(
            var_list=arg_1,  # should be given?
            reshape=False,
            sharded=False,
            max_to_keep=5,
            keep_checkpoint_every_n_hours=10000.0,
            name=None,
            restore_sequentially=False,
            saver_def=None,
            builder=None,
            defer_build=False,
            allow_empty=True,
            write_version=tf.train.SaverDef.V2,
            pad_step_number=False,
            save_relative_paths=True
            # filename=None
        )


def Func(arg_0):
        """
        Creates and returns a list of hooks to use in a session. Populates self.saver_directory.

        Returns: List of hooks to use in a session.
        """
        arg_1 = list()

        # Checkpoint saver hook
        if arg_0.saver_spec is not None and (arg_0.execution_type == 'single' or arg_0.distributed_spec['task_index'] == 0):
            arg_0.saver_directory = arg_0.saver_spec['directory']
            arg_1.append(tf.train.CheckpointSaverHook(
                checkpoint_dir=arg_0.saver_directory,
                save_secs=arg_0.saver_spec.get('seconds', None if 'steps' in arg_0.saver_spec else 600),
                save_steps=arg_0.saver_spec.get('steps'),  # Either one or the other has to be set.
                saver=None,  # None since given via 'scaffold' argument.
                checkpoint_basename=arg_0.saver_spec.get('basename', 'model.ckpt'),
                scaffold=arg_0.scaffold,
                listeners=None
            ))
        else:
            arg_0.saver_directory = None

        # Stop at step hook
        # hooks.append(tf.train.StopAtStepHook(
        #     num_steps=???,  # This makes more sense, if load and continue training.
        #     last_step=None  # Either one or the other has to be set.
        # ))

        # # Step counter hook
        # hooks.append(tf.train.StepCounterHook(
        #     every_n_steps=counter_config.get('steps', 100),  # Either one or the other has to be set.
        #     every_n_secs=counter_config.get('secs'),  # Either one or the other has to be set.
        #     output_dir=None,  # None since given via 'summary_writer' argument.
        #     summary_writer=summary_writer
        # ))

        # Other available hooks:
        # tf.train.FinalOpsHook(final_ops, final_ops_feed_dict=None)
        # tf.train.GlobalStepWaiterHook(wait_until_step)
        # tf.train.LoggingTensorHook(tensors, every_n_iter=None, every_n_secs=None)
        # tf.train.NanTensorHook(loss_tensor, fail_on_nan_loss=True)
        # tf.train.ProfilerHook(save_steps=None, save_secs=None, output_dir='', show_dataflow=True, show_memory=False)

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """
        Returns the tf op to fetch when unbuffered observations are passed in.

        Args:
            states (any): One state (usually a value tuple) or dict of states if multiple states are expected.
            actions (any): One action (usually a value tuple) or dict of states if multiple actions are expected.
            internals (any): Internal list.
            terminal (bool): boolean indicating if the episode terminated after the observation.
            reward (float): scalar reward that resulted from executing the action.

        Returns: Tf op to fetch when `observe()` is called.
        """
        # Increment episode
        arg_7 = tf.count_nonzero(input_tensor=arg_4, dtype=util.tf_dtype('int'))
        arg_8 = tf.assign_add(ref=arg_0.episode, value=tf.to_int64(x=arg_7))
        arg_9 = tf.assign_add(ref=arg_0.global_episode, value=tf.to_int64(x=arg_7))

        with tf.control_dependencies(control_inputs=(arg_8, arg_9)):
            # Stop gradients
            # Not using buffers here.
            arg_1 = util.map_tensors(fn=tf.stop_gradient, tensors=arg_1)
            arg_3 = util.map_tensors(fn=tf.stop_gradient, tensors=arg_3)
            arg_2 = util.map_tensors(fn=tf.stop_gradient, tensors=arg_2)
            arg_4 = tf.stop_gradient(input=arg_4)
            arg_5 = tf.stop_gradient(input=arg_5)

            # Observation
            arg_10 = arg_0.fn_observe_timestep(
                arg_1=arg_1,
                arg_3=arg_3,
                arg_2=arg_2,
                arg_4=arg_4,
                arg_5=arg_5
            )

        with tf.control_dependencies(control_inputs=(arg_10,)):
            # Trivial operation to enforce control dependency.
            arg_0.unbuffered_episode_output = arg_0.global_episode + 0


def Func(arg_0):
        """
        Returns the list of all of the components this model consists of that can be individually saved and restored.
        For instance the network or distribution.

        Returns:
            List of util.SavableComponent
        """
        arg_1 = arg_0.get_components()
        arg_1 = [arg_1[name] for name in sorted(arg_1)]
        return set(filter(lambda x: isinstance(x, util.SavableComponent), arg_1))


def Func(arg_0, arg_1, arg_2):
        """
        Saves a component of this model to the designated location.

        Args:
            component_name: The component to save.
            save_path: The location to save to.
        Returns:
            Checkpoint path where the component was saved.
        """
        arg_3 = arg_0.get_component(arg_1=arg_1)
        arg_0._validate_savable(arg_3=arg_3, arg_1=arg_1)
        return arg_3.save(sess=arg_0.session, arg_2=arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Restores a component's parameters from a save location.

        Args:
            component_name: The component to restore.
            save_path: The save location.
        """
        arg_3 = arg_0.get_component(arg_1=arg_1)
        arg_0._validate_savable(arg_3=arg_3, arg_1=arg_1)
        arg_3.restore(sess=arg_0.session, arg_2=arg_2)


def Func(arg_0):
        """
        Return the state space. Might include subdicts if multiple Func are
        available simultaneously.

        Returns: dict of state properties (shape and type).

        """
        arg_1 = arg_0.env.getScreenRGB()
        return dict(shape=arg_1.shape, type='int')


def Func(arg_0):
    """
    Sanity checks an actions dict, used to define the action space for an MDP.
    Throws an error or warns if mismatches are found.

    Args:
        actions_spec (Union[None,dict]): The spec-dict to check (or None).

    Returns: Tuple of 1) the action space desc and 2) whether there is only one component in the action space.
    """
    # Leave incoming spec-dict intact.
    arg_1 = copy.deepcopy(arg_0)

    # Unique action shortform.
    arg_2 = ('type' in arg_1)
    if arg_2:
        arg_1 = dict(arg_4=arg_1)

    # Normalize actions.
    for arg_3, arg_4 in arg_1.items():
        # Set default type to int
        if 'type' not in arg_4:
            arg_4['type'] = 'int'

        # Check required values
        if arg_4['type'] == 'int':
            if 'num_actions' not in arg_4:
                raise TensorForceError("Action requires value 'num_actions' set!")
        elif arg_4['type'] == 'float':
            if ('min_value' in arg_4) != ('max_value' in arg_4):
                raise TensorForceError("Action requires both values 'min_value' and 'max_value' set!")

        # Set default shape to empty tuple (single-int, discrete action space)
        if 'shape' not in arg_4:
            arg_4['shape'] = ()

        # Convert int to unary tuple
        if isinstance(arg_4['shape'], int):
            arg_4['shape'] = (arg_4['shape'],)

    return arg_1, arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Handles the behaviour of visible bolts flying toward Marauders."""
    # Disappear if we've hit a Marauder or a bunker.
    if (arg_0.character in arg_4['bunker_hitters'] or
        arg_0.character in arg_4['marauder_hitters']):
      return arg_0._teleport((-1, -1))
    # Otherwise, northward!
    arg_0._north(arg_1, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Handles the behaviour of visible bolts flying toward the player."""
    # Disappear if we've hit a bunker.
    if arg_0.character in arg_4['bunker_hitters']:
      return arg_0._teleport((-1, -1))
    # End the game if we've hit the player.
    if arg_0.position == arg_3['P'].position: arg_4.terminate_episode()
    arg_0._south(arg_1, arg_4)


def Func(arg_0, arg_1, arg_2):
    """Launches a new bolt from a random Marauder."""
    # We don't fire if another Marauder fired a bolt just now.
    if arg_2.get('last_marauder_shot') == arg_2.frame: return
    arg_2['last_marauder_shot'] = arg_2.frame
    # Which Marauder should fire the laser bolt?
    arg_3 = np.random.choice(np.nonzero(arg_1['X'].sum(axis=0))[0])
    arg_4 = np.nonzero(arg_1['X'][:, arg_3])[0][-1] + 1
    # Move ourselves just below that Marauder.
    arg_0._teleport((arg_4, arg_3))


def Func(arg_0, arg_1=None):
        """
        Creates and stores Network and Distribution objects.
        Generates and stores all template functions.
        """
        # Create network before super-call, since non-empty internals_spec attribute (for RNN) is required subsequently.
        arg_0.network = Network.from_spec(
            spec=arg_0.network_spec,
            kwargs=dict(summary_labels=arg_0.summary_labels)
        )

        # Now that we have the network component: We can create the internals placeholders.
        assert len(arg_0.internals_spec) == 0
        arg_0.internals_spec = arg_0.network.internals_spec()
        for arg_4 in sorted(arg_0.internals_spec):
            arg_5 = arg_0.internals_spec[arg_4]
            arg_0.internals_input[arg_4] = tf.placeholder(
                dtype=util.tf_dtype(arg_5['type']),
                shape=(None,) + tuple(arg_5['shape']),
                arg_4=('internal-' + arg_4)
            )
            if arg_5['initialization'] == 'zeros':
                arg_0.internals_init[arg_4] = np.zeros(shape=arg_5['shape'])
            else:
                raise TensorForceError("Invalid internal initialization value.")

        # And only then call super.
        arg_1 = super(DistributionModel, arg_0).Func(arg_1)

        # Distributions
        arg_0.distributions = arg_0.create_distributions()

        # KL divergence function
        arg_0.fn_kl_divergence = tf.make_template(
            name_='kl-divergence',
            func_=arg_0.tf_kl_divergence,
            custom_getter_=arg_1
        )

        return arg_1


def Func(arg_0):
        """
        Creates and returns the Distribution objects based on self.distributions_spec.

        Returns: Dict of distributions according to self.distributions_spec.
        """
        arg_1 = dict()
        for arg_2 in sorted(arg_0.actions_spec):
            arg_3 = arg_0.actions_spec[arg_2]

            if arg_0.distributions_spec is not None and arg_2 in arg_0.distributions_spec:
                arg_4 = dict(arg_3)
                arg_4['scope'] = arg_2
                arg_4['summary_labels'] = arg_0.summary_labels
                arg_1[arg_2] = Distribution.from_spec(
                    spec=arg_0.distributions_spec[arg_2],
                    arg_4=arg_4
                )

            elif arg_3['type'] == 'bool':
                arg_1[arg_2] = Bernoulli(
                    shape=arg_3['shape'],
                    scope=arg_2,
                    summary_labels=arg_0.summary_labels
                )

            elif arg_3['type'] == 'int':
                arg_1[arg_2] = Categorical(
                    shape=arg_3['shape'],
                    num_actions=arg_3['num_actions'],
                    scope=arg_2,
                    summary_labels=arg_0.summary_labels
                )

            elif arg_3['type'] == 'float':
                if 'min_value' in arg_3:
                    arg_1[arg_2] = Beta(
                        shape=arg_3['shape'],
                        min_value=arg_3['min_value'],
                        max_value=arg_3['max_value'],
                        scope=arg_2,
                        summary_labels=arg_0.summary_labels
                    )

                else:
                    arg_1[arg_2] = Gaussian(
                        shape=arg_3['shape'],
                        scope=arg_2,
                        summary_labels=arg_0.summary_labels
                    )

        return arg_1


def Func(arg_0, arg_1=None):
        """
        Creates a memory from a specification dict.
        """
        arg_2 = util.get_object(
            obj=arg_0,
            predefined_objects=tensorforce.core.memories.memories,
            arg_1=arg_1
        )
        assert isinstance(arg_2, Memory)
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Initialization step preparing the arguments for the first iteration of the loop body.

        Args:
            x_init: Initial solution guess $x_0$.
            base_value: Value $f(x')$ at $x = x'$.
            target_value: Value $f(x_0)$ at $x = x_0$.
            estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None.

        Returns:
            Initial arguments for tf_step.
        """
        arg_0.base_value = arg_2

        if arg_4 is None:  # TODO: Is this a good alternative?
            arg_4 = tf.abs(x=arg_2)

        arg_5 = super(LineSearch, arg_0).Func(arg_1)

        arg_6 = tf.divide(
            x=(arg_3 - arg_0.base_value),
            y=tf.maximum(x=arg_4, y=util.epsilon)
        )

        arg_7 = arg_6 - 1.0

        if arg_0.mode == 'linear':
            arg_8 = [-t * arg_0.parameter for t in arg_1]
            arg_0.estimated_incr = -arg_4 * arg_0.parameter

        elif arg_0.mode == 'exponential':
            arg_8 = [-t * arg_0.parameter for t in arg_1]

        return arg_5 + (arg_8, arg_6, arg_7, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6):
        """
        Iteration loop body of the line search algorithm.

        Args:
            x: Current solution estimate $x_t$.
            iteration: Current iteration counter $t$.
            deltas: Current difference $x_t - x'$.
            improvement: Current improvement $(f(x_t) - f(x')) / v'$.
            last_improvement: Last improvement $(f(x_{t-1}) - f(x')) / v'$.
            estimated_improvement: Current estimated value $v'$.

        Returns:
            Updated arguments for next iteration.
        """
        arg_1, arg_7, arg_3, arg_4, arg_5, arg_6 = super(LineSearch, arg_0).Func(
            arg_1, arg_2, arg_3, arg_4, arg_5, arg_6
        )

        arg_8 = [t + delta for t, delta in zip(arg_1, arg_3)]

        if arg_0.mode == 'linear':
            arg_9 = arg_3
            arg_10 = arg_6 + arg_0.estimated_incr

        elif arg_0.mode == 'exponential':
            arg_9 = [delta * arg_0.parameter for delta in arg_3]
            arg_10 = arg_6 * arg_0.parameter

        arg_11 = arg_0.fn_x(arg_9)

        arg_12 = tf.divide(
            arg_1=(arg_11 - arg_0.base_value),
            y=tf.maximum(arg_1=arg_10, y=util.epsilon)
        )

        return arg_8, arg_7, arg_9, arg_12, arg_4, arg_10


def Func(arg_0, arg_1=True, **arg_2):
    """Render Func formatted text to html.

    :param text: Func formatted text content.
    :param escape: if set to False, all html tags will not be escaped.
    :param use_xhtml: output with xhtml tags.
    :param hard_wrap: if set to True, it will use the GFM line breaks feature.
    :param parse_block_html: parse text only in block level html.
    :param parse_inline_html: parse text only in inline level html.
    """
    return Markdown(arg_1=arg_1, **arg_2)(arg_0)


def Func(arg_0, arg_1):
        """Parse setext heading."""
        arg_0.tokens.append({
            'type': 'heading',
            'level': 1 if arg_1.group(2) == '=' else 2,
            'text': arg_1.group(1),
        })


def Func(arg_0):
        """Grammar for hard wrap linebreak. You don't need to add two
        spaces at the end of a line.
        """
        arg_0.linebreak = re.compile(r'^ *\n(?!\s*$)')
        arg_0.text = re.compile(
            r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)'
        )


def Func(arg_0, arg_1, arg_2=None):
        """Rendering block level code. ``pre > code``.

        :param code: text content of the code block.
        :param lang: language of the given code.
        """
        arg_1 = arg_1.rstrip('\n')
        if not arg_2:
            arg_1 = escape(arg_1, smart_amp=False)
            return '
%s\n
\n' % arg_1
        arg_1 = escape(arg_1, quote=True, smart_amp=False)
        return '
%s\n
\n' % (arg_2, arg_1)


def Func(arg_0, arg_1):
        """Rendering block level pure html content.

        :param html: text content of the html snippet.
        """
        if arg_0.options.get('skip_style') and \
           arg_1.lower().startswith('<style'):
            return ''
        if arg_0.options.get('escape'):
            return escape(arg_1)
        return arg_1


def Func(arg_0, arg_1, arg_2):
        """Rendering the ref anchor of a footnote.

        :param key: identity key for the footnote.
        :param index: the index count of current footnote.
        """
        arg_3 = (
            ''
            '%d'
        ) % (escape(arg_1), escape(arg_1), arg_2)
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """Rendering a footnote item.

        :param key: identity key for the footnote.
        :param text: text content of the footnote.
        """
        arg_3 = (
            '↩'
        ) % escape(arg_1)
        arg_2 = arg_2.rstrip()
        if arg_2.endswith('
'):
            arg_2 = re.sub(r'<\/p>$', r'%s
' % arg_3, arg_2)
        else:
            arg_2 = '%s
%s
' % (arg_2, arg_3)
        arg_4 = '
%s
\n' % (escape(arg_1), arg_2)
        return arg_4


def Func(arg_0):
        """
        Convert MetaParams into TF Summary Format and create summary_op.

        Returns:
            Merged TF Op for TEXT summary elements, should only be executed once to reduce data duplication.

        """
        arg_1 = []

        arg_0.ignore_unknown_dtypes = True
        for arg_3 in sorted(arg_0.meta_params):
            arg_4 = arg_0.convert_data_to_string(arg_0.meta_params[arg_3])

            if len(arg_4) == 0:
                continue
            if isinstance(arg_4, str):
                arg_1.append(tf.contrib.summary.generic(name=arg_3, tensor=tf.convert_to_tensor(str(arg_4))))
            else:
                arg_1.append(tf.contrib.summary.generic(name=arg_3, tensor=tf.as_string(tf.convert_to_tensor(arg_4))))

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=None):
        """
        Creates the TensorFlow operations for calculating the baseline loss of a batch.

        Args:
            states: Dict of state tensors.
            internals: List of prior internal state tensors.
            reward: Reward tensor.
            update: Boolean tensor indicating whether this call happens during an update.
            reference: Optional reference tensor(s), in case of a comparative loss.

        Returns:
            Loss tensor.
        """
        if arg_0.baseline_mode == 'states':
            arg_6 = arg_0.baseline.loss(
                arg_1=arg_1,
                arg_2=arg_2,
                arg_3=arg_3,
                arg_4=arg_4,
                arg_5=arg_5
            )

        elif arg_0.baseline_mode == 'network':
            arg_6 = arg_0.baseline.loss(
                arg_1=arg_0.network.apply(x=arg_1, arg_2=arg_2, arg_4=arg_4),
                arg_2=arg_2,
                arg_3=arg_3,
                arg_4=arg_4,
                arg_5=arg_5
            )

        arg_7 = arg_0.baseline.regularization_loss()
        if arg_7 is not None:
            arg_6 += arg_7

        return arg_6


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Creates the TensorFlow operations for performing an optimization step on the given variables, including
        actually changing the values of the variables.

        Args:
            time: Time tensor. Not used for this optimizer.
            variables: List of variables to optimize.
            **kwargs:
                fn_loss : loss function tensor to differentiate.

        Returns:
            List of delta tensors corresponding to the updates for each optimized variable.
        """
        arg_4 = arg_3["fn_loss"]
        if arg_2 is None:
            arg_2 = tf.trainable_variables
        return tf.gradients(arg_4, arg_2)


def Func(arg_0, arg_1=None):
        """
        Constructs the extra Replay memory.
        """
        arg_1 = super(QDemoModel, arg_0).Func(arg_1)

        arg_0.demo_memory = Replay(
            states=arg_0.states_spec,
            internals=arg_0.internals_spec,
            actions=arg_0.actions_spec,
            include_next_states=True,
            capacity=arg_0.demo_memory_capacity,
            scope='demo-replay',
            summary_labels=arg_0.summary_labels
        )

        # Import demonstration optimization.
        arg_0.fn_import_demo_experience = tf.make_template(
            name_='import-demo-experience',
            func_=arg_0.tf_import_demo_experience,
            custom_getter_=arg_1
        )

        # Demonstration loss.
        arg_0.fn_demo_loss = tf.make_template(
            name_='demo-loss',
            func_=arg_0.tf_demo_loss,
            custom_getter_=arg_1
        )

        # Combined loss.
        arg_0.fn_combined_loss = tf.make_template(
            name_='combined-loss',
            func_=arg_0.tf_combined_loss,
            custom_getter_=arg_1
        )

        # Demonstration optimization.
        arg_0.fn_demo_optimization = tf.make_template(
            name_='demo-optimization',
            func_=arg_0.tf_demo_optimization,
            custom_getter_=arg_1
        )

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7=None):
        """
        Extends the q-model loss via the dqfd large-margin loss.
        """
        arg_8 = arg_0.network.apply(x=arg_1, arg_5=arg_5, arg_6=arg_6)
        arg_9 = list()

        for arg_10 in sorted(arg_2):
            arg_11 = arg_2[arg_10]
            arg_12 = arg_0.distributions[arg_10].parameterize(x=arg_8)
            arg_13 = arg_0.distributions[arg_10].state_action_value(arg_12=arg_12, arg_11=arg_11)

            # Create the supervised margin loss
            # Zero for the action taken, one for all other actions, now multiply by expert margin
            if arg_0.actions_spec[arg_10]['type'] == 'bool':
                arg_14 = 2
                arg_11 = tf.cast(x=arg_11, dtype=util.tf_dtype('int'))
            else:
                arg_14 = arg_0.actions_spec[arg_10]['num_actions']

            arg_15 = tf.one_hot(indices=arg_11, depth=arg_14)
            arg_16 = tf.ones_like(tensor=arg_15, dtype=tf.float32)
            arg_17 = arg_16 - arg_15

            # max_a([Q(s,a) + l(s,a_E,a)], l(s,a_E, a) is 0 for expert action and margin value for others
            arg_18 = arg_0.distributions[arg_10].state_action_value(arg_12=arg_12)
            arg_18 = arg_18 + arg_17 * arg_0.expert_margin
            arg_19 = tf.reduce_max(input_tensor=arg_18, axis=-1)

            # J_E(Q) = max_a([Q(s,a) + l(s,a_E,a)] - Q(s,a_E)
            arg_20 = arg_19 - arg_13

            arg_21 = util.prod(arg_0.actions_spec[arg_10]['shape'])
            arg_20 = tf.reshape(tensor=arg_20, shape=(-1, arg_21))
            arg_9.append(arg_20)

        arg_22 = tf.reduce_mean(input_tensor=tf.concat(values=arg_9, axis=1), axis=1)
        arg_22 = tf.square(x=arg_22)

        return tf.reduce_mean(input_tensor=arg_22, axis=0)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9=None):
        """
        Combines Q-loss and demo loss.
        """
        arg_10 = arg_0.fn_loss(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=arg_6,
            arg_7=arg_7,
            arg_8=arg_8,
            arg_9=arg_9
        )

        arg_11 = arg_0.fn_demo_loss(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_8=arg_8,
            arg_9=arg_9
        )

        return arg_10 + arg_0.supervised_weight * arg_11


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """
        Stores demonstrations in the demo memory.
        """
        arg_6 = arg_0.Func_output

        arg_7 = arg_0.get_feed_dict(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5
        )

        arg_0.monitored_session.run(arg_6=arg_6, arg_7=arg_7)


def Func(arg_0):
        """
        Performs a demonstration update by calling the demo optimization operation.
        Note that the batch data does not have to be fetched from the demo memory as this is now part of
        the TensorFlow operation of the demo update.
        """
        arg_1 = arg_0.demo_optimization_output

        arg_0.monitored_session.run(arg_1=arg_1)


def Func(arg_0):
    '''Ensures tasks have an action key and strings are converted to python objects'''

    arg_1 = dict()
    arg_2 = ModuleArgsParser(arg_0)
    try:
        arg_3, arg_4, arg_1['delegate_to'] = arg_2.parse()
    except AnsibleParserError as e:
        try:
            arg_5 = "%s:%s" % (arg_0[FILENAME_KEY], arg_0[LINE_NUMBER_KEY])
            del arg_0[FILENAME_KEY]
            del arg_0[LINE_NUMBER_KEY]
        except KeyError:
            arg_5 = "Unknown"
        try:
            import pprint
            arg_6 = pprint.PrettyPrinter(indent=2)
            arg_7 = arg_6.pformat(arg_0)
        except ImportError:
            arg_7 = arg_0
        raise SystemExit("Couldn't parse task at %s (%s)\n%s" % (arg_5, e.message, arg_7))

    # denormalize shell -> command conversion
    if '_uses_shell' in arg_4:
        arg_3 = 'shell'
        del(arg_4['_uses_shell'])

    for (arg_8, arg_9) in list(arg_0.items()):
        if arg_8 in ('action', 'local_action', 'args', 'delegate_to') or arg_8 == arg_3:
            # we don't want to re-assign these values, which were
            # determined by the ModuleArgsParser() above
            continue
        else:
            arg_1[arg_8] = arg_9

    arg_1['action'] = dict(__ansible_module__=arg_3)

    if '_raw_params' in arg_4:
        arg_1['action']['__ansible_arguments__'] = arg_4['_raw_params'].split(' ')
        del(arg_4['_raw_params'])
    else:
        arg_1['action']['__ansible_arguments__'] = list()

    if 'argv' in arg_4 and not arg_1['action']['__ansible_arguments__']:
        arg_1['action']['__ansible_arguments__'] = arg_4['argv']
        del(arg_4['argv'])

    arg_1['action'].update(arg_4)
    return arg_1


def Func(arg_0, arg_1):
    """Parses yaml as ansible.utils.parse_yaml but with linenumbers.

    The line numbers are stored in each node's LINE_NUMBER_KEY key.
    """

    def arg_13(arg_2, arg_3):
        # the line number where the previous token has ended (plus empty lines)
        arg_4 = arg_11.line
        arg_5 = Composer.compose_node(arg_11, arg_2, arg_3)
        arg_5.__line__ = arg_4 + 1
        return arg_5

    def arg_14(arg_5, arg_7=False):
        if ANSIBLE_VERSION < 2:
            arg_8 = Constructor.construct_mapping(arg_11, arg_5, arg_7=arg_7)
        else:
            arg_8 = AnsibleConstructor.construct_mapping(arg_11, arg_5, arg_7=arg_7)
        if hasattr(arg_5, '__line__'):
            arg_8[arg_9] = arg_5.__line__
        else:
            arg_8[arg_9] = arg_8._line_number
        arg_8[arg_10] = arg_1
        return arg_8

    try:
        if ANSIBLE_VERSION < 2:
            arg_11 = yaml.Loader(arg_0)
        else:
            import inspect
            arg_12 = {}
            if 'vault_password' in inspect.getargspec(AnsibleLoader.__init__).args:
                arg_12['vault_password'] = DEFAULT_VAULT_PASSWORD
            arg_11 = AnsibleLoader(arg_0, **arg_12)
        arg_11.compose_node = arg_13
        arg_11.construct_mapping = arg_14
        arg_0 = arg_11.get_single_data()
    except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
        raise SystemExit("Failed to parse YAML in %s: %s" % (arg_1, str(e)))
    return arg_0


def Func(arg_0, arg_1):
        """Add additional requirements from setup.cfg to file metadata_path"""
        arg_2 = list(arg_0.setupcfg_requirements())
        if not arg_2: return
        arg_3 = read_pkg_info(arg_1)
        if 'Provides-Extra' in arg_3 or 'Requires-Dist' in arg_3:
            warnings.warn('setup.cfg requirements overwrite values from setup.py')
            del arg_3['Provides-Extra']
            del arg_3['Requires-Dist']
        for arg_4, arg_5 in arg_2:
            arg_3[arg_4] = arg_5
        write_pkg_info(arg_1, arg_3)


def Func(arg_0, arg_1, arg_2):
        """Convert an .egg-info directory into a .dist-info directory"""
        def adios(arg_3):
            """Appropriately delete directory, file or link."""
            if os.path.exists(arg_3) and not os.path.islink(arg_3) and os.path.isdir(arg_3):
                shutil.rmtree(arg_3)
            elif os.path.exists(arg_3):
                os.unlink(arg_3)

        adios(arg_2)

        if not os.path.exists(arg_1):
            # There is no egg-info. This is probably because the egg-info
            # file/directory is not named matching the distribution name used
            # to name the archive file. Check for this case and report
            # accordingly.
            import glob
            arg_4 = os.path.join(os.path.dirname(arg_1), '*.egg-info')
            arg_5 = glob.glob(arg_4)
            arg_6 = "Egg metadata expected at %s but not found" % (arg_1,)
            if arg_5:
                arg_7 = os.path.basename(arg_5[0])
                arg_6 += " (%s found - possible misnamed archive file?)" % (arg_7,)

            raise ValueError(arg_6)

        if os.path.isfile(arg_1):
            # .egg-info is a single file
            arg_8 = arg_1
            arg_9 = arg_0._pkginfo_to_metadata(arg_1, arg_1)
            os.mkdir(arg_2)
        else:
            # .egg-info is a directory
            arg_8 = os.path.join(arg_1, 'PKG-INFO')
            arg_9 = arg_0._pkginfo_to_metadata(arg_1, arg_8)

            # ignore common egg metadata that is useless to wheel
            shutil.copytree(arg_1, arg_2,
                            ignore=lambda x, y: set(('PKG-INFO',
                                                     'requires.txt',
                                                     'SOURCES.txt',
                                                     'not-zip-safe',)))

            # delete dependency_links if it is only whitespace
            arg_10 = os.path.join(arg_2, 'dependency_links.txt')
            with open(arg_10, 'r') as dependency_links_file:
                arg_11 = dependency_links_file.read().strip()
            if not arg_11:
                adios(arg_10)

        write_pkg_info(os.path.join(arg_2, 'METADATA'), arg_9)

        # XXX deprecated. Still useful for current distribute/setuptools.
        arg_12 = os.path.join(arg_2, 'METADATA')
        arg_0.add_requirements(arg_12)

        # XXX intentionally a different path than the PEP.
        arg_13 = os.path.join(arg_2, 'metadata.json')
        arg_14 = pkginfo_to_dict(arg_12,
                                 distribution=arg_0.distribution)

        if 'description' in arg_14:
            arg_15 = 'DESCRIPTION.rst'
            arg_16 = arg_14.pop('description')
            arg_17 = os.path.join(arg_2,
                                            arg_15)
            with open(arg_17, "wb") as description_file:
                description_file.write(arg_16.encode('utf-8'))
            arg_14['extensions']['python.details']['document_names']['description'] = arg_15

        # XXX heuristically copy any LICENSE/LICENSE.txt?
        arg_18 = arg_0.license_file()
        if arg_18:
            arg_19 = 'LICENSE.txt'
            shutil.copy(arg_18, os.path.join(arg_0.distinfo_dir, arg_19))
            arg_14['extensions']['python.details']['document_names']['license'] = arg_19

        with open(arg_13, "w") as metadata_json:
            json.dump(arg_14, metadata_json, sort_keys=True)

        adios(arg_1)


def Func(arg_0: arg_1[arg_2], arg_3: arg_4 = None, arg_5: arg_4 = None,
                          arg_6: arg_7[arg_8, arg_4] = arg_8.accepting_input) -> Activity:
        """
        Returns a message that includes a set of suggested actions and optional text.

        :Example:
        message = MessageFactory.Func([CardAction(title='a', type=ActionTypes.im_back, value='a'),
                                                    CardAction(title='b', type=ActionTypes.im_back, value='b'),
                                                    CardAction(title='c', type=ActionTypes.im_back, value='c')], 'Choose a color')
        await context.send_activity(message)

        :param actions:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        arg_0 = SuggestedActions(arg_0=arg_0)
        arg_10 = Activity(type=ActivityTypes.message, arg_6=arg_6, Func=arg_0)
        if arg_3:
            arg_10.text = arg_3
        if arg_5:
            arg_10.speak = arg_5
        return arg_10


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_1 = None, arg_4: arg_1 = None, arg_5: arg_1 = None,
                    arg_6: arg_7[arg_8, arg_1] = None):
        """
        Returns a message that will display a single image or video to a user.

        :Example:
        message = MessageFactory.Func('https://example.com/hawaii.jpg', 'image/jpeg',
                                             'Hawaii Trip', 'A photo from our family vacation.')
        await context.send_activity(message)

        :param url:
        :param content_type:
        :param name:
        :param text:
        :param speak:
        :param input_hint:
        :return:
        """
        arg_9 = Attachment(arg_2=arg_2, Func=arg_0)
        if arg_3:
            arg_9.name = arg_3
        return attachment_activity(AttachmentLayoutTypes.list, [arg_9], arg_4, arg_5, arg_6)


async def Func(arg_0, arg_1: arg_2[arg_3]) -> dict:
        """Read storeitems from storage.

        :param keys:
        :return dict:
        """
        try:
            # check if the database and container exists and if not create
            if not arg_0.__container_exists:
                arg_0.__create_db_and_container()
            if len(arg_1) > 0:
                # create the parameters object
                arg_4 = [
                    {'name': f'@id{i}', 'value': f'{self.__sanitize_key(key)}'}
                    for i, key in enumerate(arg_1)
                    ]
                # get the names of the params
                arg_5 = ','.join(param.get('name')
                                              for param in arg_4)
                # create the query
                arg_6 = {
                    "query":
                    f"SELECT c.id, c.realId, c.document, c._etag \
FROM c WHERE c.id in ({parameter_sequence})",
                    "parameters": arg_4
                    }
                arg_7 = {'enableCrossPartitionQuery': True}
                # run the query and store the results as a list
                arg_8 = list(
                    arg_0.client.QueryItems(
                        arg_0.__container_link, arg_6, arg_7)
                    )
                # return a dict with a key and a StoreItem
                return {
                    arg_9.get('realId'): arg_0.__create_si(arg_9) for arg_9 in arg_8
                    }
            else:
                raise Exception('cosmosdb_storage.Func(): \
provide at least one key')
        except TypeError as e:
            raise e


async def Func(arg_0, arg_1: arg_2[arg_3, arg_4]):
        """Save storeitems to storage.

        :param changes:
        :return:
        """
        try:
            # check if the database and container exists and if not create
            if not arg_0.__container_exists:
                arg_0.__create_db_and_container()
                # iterate over the changes
            for (arg_5, arg_6) in arg_1.items():
                # store the e_tag
                arg_7 = arg_6.e_tag
                # create the new document
                arg_8 = {'id': arg_0.__sanitize_key(arg_5),
                       'realId': arg_5,
                       'document': arg_0.__create_dict(arg_6)
                       }
                # the e_tag will be * for new docs so do an insert
                if (arg_7 == '*' or not arg_7):
                    arg_0.client.UpsertItem(
                        database_or_Container_link=arg_0.__container_link,
                        document=arg_8,
                        options={'disableAutomaticIdGeneration': True}
                        )
                # if we have an etag, do opt. concurrency replace
                elif(len(arg_7) > 0):
                    arg_9 = {'type': 'IfMatch', 'condition': arg_7}
                    arg_0.client.ReplaceItem(
                        document_link=arg_0.__item_link(
                            arg_0.__sanitize_key(arg_5)),
                        new_document=arg_8,
                        options={'accessCondition': arg_9}
                        )
                # error when there is no e_tag
                else:
                    raise Exception('cosmosdb_storage.Func(): etag missing')
        except Exception as e:
            raise e


def Func(arg_0, arg_1) -> str:
        """Return the sanitized key.

        Replace characters that are not allowed in keys in Cosmos.

        :param key:
        :return str:
        """
        # forbidden characters
        arg_2 = ['\\', '?', '/', '#', '\t', '\n', '\r']
        # replace those with with '*' and the
        # Unicode code point of the character and return the new string
        return ''.join(
            map(
                lambda x: '*'+str(ord(x)) if x in arg_2 else x, arg_1
                )
            )


def Func(arg_0):
        """Call the get or create methods."""
        arg_1 = arg_0.config.database
        arg_2 = arg_0.config.container
        arg_0.db = arg_0.__get_or_create_database(arg_0.client, arg_1)
        arg_0.container = arg_0.__get_or_create_container(
            arg_0.client, arg_2
            )


def Func(arg_0, arg_1, arg_2) -> str:
        """Return the database link.

        Check if the database exists or create the db.

        :param doc_client:
        :param id:
        :return str:
        """
        # query CosmosDB for a database with that name/id
        arg_3 = list(arg_1.QueryDatabases({
            "query": "SELECT * FROM r WHERE r.id=@id",
            "parameters": [
                {"name": "@id", "value": arg_2}
            ]
        }))
        # if there are results, return the first (db names are unique)
        if len(arg_3) > 0:
            return arg_3[0]['id']
        else:
            # create the database if it didn't exist
            arg_4 = arg_1.CreateDatabase({'id': arg_2})
            return arg_4['id']


def Func(
        arg_0,
        arg_1: [arg_2],
        arg_3: arg_4,
        arg_5: arg_6[arg_7,arg_7] = None,
        arg_8: arg_6[arg_7,arg_9] = None
    ) -> EventData:
        """
        Fills the event properties and metrics for the QnaMessage event for telemetry.

        :return: A tuple of event data properties and metrics that will be sent to the BotTelemetryClient.track_event() method for the QnAMessage event. The properties and metrics returned the standard properties logged with any properties passed from the get_answers() method.

        :rtype: EventData
        """

        arg_10: arg_6[arg_7,arg_7] = dict()
        arg_11: arg_6[arg_7, arg_9] = dict()

        arg_10[arg_12.knowledge_base_id_property] = arg_0._endpoint.knowledge_base_id

        arg_14: arg_7 = arg_3.activity.text
        arg_15: arg_7 = arg_3.activity.from_property.name

        # Use the LogPersonalInformation flag to toggle logging PII data; text and username are common examples.
        if arg_0.log_personal_information:
            if arg_14:
                arg_10[arg_12.question_property] = arg_14

            if arg_15:
                arg_10[arg_12.username_property] = arg_15

        # Fill in Qna Results (found or not).
        if len(arg_1) > 0:
            arg_18 = arg_1[0]

            arg_19 = {
                arg_12.matched_question_property: json.dumps(arg_18.questions),
                arg_12.question_id_property: arg_7(arg_18.id),
                arg_12.answer_property: arg_18.answer,
                arg_12.score_metric: arg_18.score,
                arg_12.article_found_property: 'true'
            }

            arg_10.update(arg_19)
        else:
            arg_20 = {
                arg_12.matched_question_property : 'No Qna Question matched',
                arg_12.question_id_property : 'No Qna Question Id matched',
                arg_12.answer_property : 'No Qna Answer matched',
                arg_12.article_found_property : 'false'
            }

            arg_10.update(arg_20)

        # Additional Properties can override "stock" properties.
        if arg_5:
            arg_10.update(arg_5)

        # Additional Metrics can override "stock" metrics.
        if arg_8:
            arg_11.update(arg_8)

        return EventData(arg_10=arg_10, arg_11=arg_11)


def Func(arg_0: arg_1) -> ConversationReference:
        """
        Returns the conversation reference for an activity. This can be saved as a plain old JSON
        object and then later used to message the user proactively.

        Usage Example:
        reference = TurnContext.Func(context.request)
        :param activity:
        :return:
        """
        return ConversationReference(activity_id=arg_0.id,
                                     user=copy(arg_0.from_property),
                                     bot=copy(arg_0.recipient),
                                     conversation=copy(arg_0.conversation),
                                     channel_id=arg_0.channel_id,
                                     service_url=arg_0.service_url)


def Func(arg_0, arg_1: arg_2) -> str:
        """
        Give the waterfall step a unique name
        """
        arg_3 = arg_0._steps[arg_1].__qualname__

        if not arg_3 or ">" in arg_3 :
            arg_3 = f"Step{index + 1}of{len(self._steps)}"

        return arg_3


def Func(arg_0: arg_1, arg_2: arg_3 = 100) -> bool:
        """Determine if a number of Suggested Actions are supported by a Channel.

        Args:
            channel_id (str): The Channel to check the if Suggested Actions are supported in.
            button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel.

        Returns:
            bool: True if the Channel supports the button_cnt total Suggested Actions, False if the Channel does not support that number of Suggested Actions.
        """

        arg_4 = {
            # https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies
            Channels.facebook: 10,
            Channels.skype: 10,
            # https://developers.line.biz/en/reference/messaging-api/#items-object
            Channels.line: 13,
            # https://dev.kik.com/#/docs/messaging#text-response-object
            Channels.kik: 20,
            Channels.telegram: 100,
            Channels.slack: 100,
            Channels.emulator: 100,
            Channels.direct_line: 100,
            Channels.webchat: 100,
        }
        return arg_2 <= arg_4[arg_0] if arg_0 in arg_4 else False


def Func(arg_0: arg_1) -> bool:
        """ Determines if a given Auth header is from the Bot Framework Emulator

        :param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
        :type auth_header: str

        :return: True, if the token was issued by the Emulator. Otherwise, false.
        """
        # The Auth Header generally looks like this:
        # "Bearer eyJ0e[...Big Long String...]XAiO"
        if not arg_0:
            # No token. Can't be an emulator token.
            return False

        arg_2 = arg_0.split(' ')
        if len(arg_2) != 2:
            # Emulator tokens MUST have exactly 2 parts.
            # If we don't have 2 parts, it's not an emulator token
            return False

        arg_3 = arg_2[0]
        arg_4 = arg_2[1]

        # We now have an array that should be:
        # [0] = "Bearer"
        # [1] = "[Big Long String]"
        if arg_3 != 'Bearer':
            # The scheme from the emulator MUST be "Bearer"
            return False

        # Parse the Big Long String into an actual token.
        arg_5 = jwt.decode(arg_4, verify=False)
        if not arg_5:
            return False

        # Is there an Issuer?
        arg_6 = arg_5['iss']
        if not arg_6:
            # No Issuer, means it's not from the Emulator.
            return False

        # Is the token issues by a source we consider to be the emulator?
        arg_7 = EmulatorValidation.TO_BOT_FROM_EMULATOR_TOKEN_VALIDATION_PARAMETERS.issuer
        if arg_7 and not arg_6 in arg_7:
            # Not a Valid Issuer. This is NOT a Bot Framework Emulator Token.
            return False

        # The Token is from the Bot Framework Emulator. Success!
        return True


def Func(arg_0: arg_1) -> Attachment:
        """
        Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard.

        Hero cards tend to have one dominant full width image and the cards text & buttons can
        usually be found below the image.
        :return:
        """
        if not isinstance(arg_0, arg_1):
            raise TypeError('CardFactory.Func(): `card` argument is not an instance of an HeroCard, '
                            'unable to prepare attachment.')

        return Attachment(content_type=CardFactory.content_types.Func,
                          content=arg_0)


def Func(arg_0: arg_1) -> bool:
    """
    Return bool, True if succeed otherwise False.
    """
    if ctypes.windll.user32.OpenClipboard(0):
        ctypes.windll.user32.EmptyClipboard()
        arg_2 = (len(arg_0) + 1) * 2
        arg_3 = ctypes.windll.kernel32.GlobalAlloc(0, arg_2)  # GMEM_FIXED=0
        arg_4 = ctypes.windll.kernel32.GlobalLock(arg_3)
        ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(arg_4), ctypes.c_wchar_p(arg_0), arg_2 // 2)
        ctypes.windll.kernel32.GlobalUnlock(arg_3)
        # system owns hClipboardData after calling SetClipboardData,
        # application can not write to or free the data once ownership has been transferred to the system
        ctypes.windll.user32.SetClipboardData(13, arg_3)  # CF_TEXT=1, CF_UNICODETEXT=13
        ctypes.windll.user32.CloseClipboard()
        return True
    return False


def Func() -> bool:
    """
    Reset to the default text color on console window.
    Return bool, True if succeed otherwise False.
    """
    if sys.stdout:
        sys.stdout.flush()
    bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))


def Func(arg_0: arg_1, arg_2: arg_1) -> arg_1:
    """
    Func from Win32.
    Return int, a native window handle.
    """
    return ctypes.windll.user32.Func(ctypes.wintypes.POINT(arg_0, arg_2))


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_1, arg_4: arg_1) -> None:
    """Func from Win32."""
    ctypes.windll.user32.Func(arg_0, arg_2, arg_3, arg_4)


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_1, arg_4: arg_1) -> bool:
    """
    Func from Win32.
    Return bool, True if succeed otherwise False.
    """
    return bool(ctypes.windll.user32.FuncW(ctypes.c_void_p(arg_0), arg_2, arg_3, arg_4))


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_1, arg_4: arg_1) -> arg_1:
    """
    Func from Win32.
    Return int, the return value specifies the result of the message processing;
                it depends on the message sent.
    """
    return ctypes.windll.user32.FuncW(ctypes.c_void_p(arg_0), arg_2, arg_3, arg_4)


def Func() -> str:
    """
    Func from Win32.
    Return str.
    """
    arg_0 = ctypes.c_wchar * MAX_PATH
    arg_1 = arg_0()
    ctypes.windll.kernel32.FuncW(arg_1, MAX_PATH)
    return arg_1.value


def Func() -> bool:
    """
    Check if desktop is locked.
    Return bool.
    Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
    """
    arg_0 = False
    arg_1 = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), 0, 0, 0x0100)  # DESKTOP_SWITCHDESKTOP = 0x0100
    if arg_1:
        arg_0 = not ctypes.windll.user32.SwitchDesktop(arg_1)
        ctypes.windll.user32.CloseDesktop(arg_1)
    return arg_0


def Func(arg_0) -> INPUT:
    """
    Create Win32 struct `INPUT` for `SendInput`.
    Return `INPUT`.
    """
    if isinstance(arg_0, MOUSEINPUT):
        return INPUT(InputType.Mouse, _INPUTUnion(mi=arg_0))
    if isinstance(arg_0, KEYBDINPUT):
        return INPUT(InputType.Keyboard, _INPUTUnion(ki=arg_0))
    if isinstance(arg_0, HARDWAREINPUT):
        return INPUT(InputType.Hardware, _INPUTUnion(hi=arg_0))
    raise TypeError('Cannot create INPUT structure!')


def Func(arg_0: arg_1, arg_2: arg_1, arg_3: arg_1 = arg_4.KeyDown, arg_6: arg_1 = 0) -> INPUT:
    """Create Win32 struct `KEYBDINPUT` for `SendInput`."""
    return _CreateInput(KEYBDINPUT(arg_0, arg_2, arg_3, arg_6, None))


def Func(arg_0: arg_1, arg_2: arg_1 = 0) -> INPUT:
    """Create Win32 struct `HARDWAREINPUT` for `SendInput`."""
    return _CreateInput(HARDWAREINPUT(arg_0, arg_2 & 0xFFFF, arg_2 >> 16 & 0xFFFF))


def Func(arg_0: arg_1, arg_2: arg_1) -> Control:
    """
    Call IUIAutomation ElementFromPoint x,y. May return None if mouse is over cmd's title bar icon.
    Return `Control` subclass or None.
    """
    arg_3 = _AutomationClient.instance().IUIAutomation.ElementFromPoint(ctypes.wintypes.POINT(arg_0, arg_2))
    return Control.CreateControlFromElement(arg_3)


def Func(arg_0: arg_1, arg_2: arg_1) -> Control:
    """
    Get a native handle from point x,y and call IUIAutomation.ElementFromHandle.
    Return `Control` subclass.
    """
    return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(arg_0, arg_2)))


def Func() -> None:
        """Delete log file."""
        if os.path.exists(Logger.FileName):
            os.remove(Logger.FileName)


def Func(arg_0) -> ctypes.Array:
        """
        Return `ctypes.Array`, an iterable array of int values in argb.
        """
        return arg_0.GetPixelColorsOfRect(0, 0, arg_0.Width, arg_0.Height)


def Func(arg_0) -> list:
        """
        Return list, a list of `Control` subclasses.
        """
        arg_1 = []
        arg_2 = arg_0.GetFirstChildControl()
        while arg_2:
            arg_1.append(arg_2)
            arg_2 = arg_2.GetNextSiblingControl()
        return arg_1


def Func(arg_0, arg_1: arg_2) -> bool:
        """
        Call native Func if control has a valid native handle.
        """
        arg_3 = arg_0.NativeWindowHandle
        if arg_3:
            return Func(arg_3, arg_1)
        return False


def Func(arg_0) -> bool:
        """Determine whether current control is top level."""
        arg_1 = arg_0.NativeWindowHandle
        if arg_1:
            return GetAncestor(arg_1, GAFlag.Root) == arg_1
        return False


def Func(arg_0) -> 'Control':
        """
        Get the top level control which current control lays.
        If current control is top level, return self.
        If current control is root control, return None.
        Return `PaneControl` or `WindowControl` or None.
        """
        arg_1 = arg_0.NativeWindowHandle
        if arg_1:
            arg_2 = GetAncestor(arg_1, GAFlag.Root)
            if arg_2:
                if arg_2 == arg_1:
                    return arg_0
                else:
                    return ControlFromHandle(arg_2)
            else:
                #self is root control
                pass
        else:
            arg_3 = arg_0
            while True:
                arg_3 = arg_3.GetParentControl()
                arg_1 = arg_3.NativeWindowHandle
                if arg_1:
                    arg_2 = GetAncestor(arg_1, GAFlag.Root)
                    return ControlFromHandle(arg_2)


def Func(arg_0, arg_1: arg_2 = arg_3) -> bool:
        """
        Set top level window maximize.
        """
        if arg_0.IsTopLevel():
            return arg_0.ShowWindow(SW.ShowFuncd, arg_1)
        return False


def Func(arg_0) -> bool:
        """
        Move window to screen center.
        """
        if arg_0.IsTopLevel():
            arg_1 = arg_0.BoundingRectangle
            arg_2, arg_3 = GetScreenSize()
            arg_4, arg_5 = (arg_2 - arg_1.width()) // 2, (arg_3 - arg_1.height()) // 2
            if arg_4 < 0: arg_4 = 0
            if arg_5 < 0: arg_5 = 0
            return SetWindowPos(arg_0.NativeWindowHandle, SWP.HWND_Top, arg_4, arg_5, 0, 0, SWP.SWP_NoSize)
        return False


def Func(arg_0, arg_1: arg_2 = arg_3) -> bool:
        """Set top level window active."""
        if arg_0.IsTopLevel():
            arg_4 = arg_0.NativeWindowHandle
            if IsIconic(arg_4):
                arg_5 = ShowWindow(arg_4, SW.Restore)
            elif not IsWindowVisible(arg_4):
                arg_5 = ShowWindow(arg_4, SW.Show)
            arg_5 = SetForegroundWindow(arg_4)  # may fail if foreground windows's process is not python
            time.sleep(arg_1)
            return arg_5
        return False


def Func(arg_0):
        """For a composite instruction, reverse the order of sub-gates.

        This is done by recursively Funcing all sub-instructions.
        It does not invert any gate.

        Returns:
            Instruction: a fresh gate with sub-gates reversed
        """
        if not arg_0._definition:
            return arg_0.copy()

        arg_1 = arg_0.copy(name=arg_0.name + '_Func')
        arg_1.definition = []
        for arg_3, arg_4, arg_5 in reversed(arg_0._definition):
            arg_1._definition.append((arg_3.Func(), arg_4, arg_5))
        return arg_1


def Func(arg_0):
        """Invert this instruction.

        If the instruction is composite (i.e. has a definition),
        then its definition will be recursively inverted.

        Special instructions inheriting from Instruction can
        implement their own Func (e.g. T and Tdg, Barrier, etc.)

        Returns:
            Instruction: a fresh instruction for the Func

        Raises:
            QiskitError: if the instruction is not composite
                and an Func has not been implemented for it.
        """
        if not arg_0.definition:
            raise QiskitError("Func() not implemented for %s." % arg_0.name)
        arg_1 = arg_0.copy(name=arg_0.name + '_dg')
        arg_1._definition = []
        for arg_3, arg_4, arg_5 in reversed(arg_0._definition):
            arg_1._definition.append((arg_3.Func(), arg_4, arg_5))
        return arg_1


def Func(arg_0, arg_1, arg_2):
        """Add classical control on register classical and value val."""
        if not isinstance(arg_1, ClassicalRegister):
            raise QiskitError("Func must be used with a classical register")
        if arg_2 < 0:
            raise QiskitError("control value should be non-negative")
        arg_0.control = (arg_1, arg_2)
        return arg_0


def Func(arg_0, arg_1):
        """Run all the passes on a QuantumCircuit

        Args:
            circuit (QuantumCircuit): circuit to transform via all the registered passes

        Returns:
            QuantumCircuit: Transformed circuit.
        """
        arg_2 = arg_1.name
        arg_3 = circuit_to_dag(arg_1)
        del arg_1
        for arg_4 in arg_0.working_list:
            for arg_5 in arg_4:
                arg_3 = arg_0._do_pass(arg_5, arg_3, arg_4.options)
        arg_1 = dag_to_circuit(arg_3)
        arg_1.name = arg_2
        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
        """Do a pass and its "requires".

        Args:
            pass_ (BasePass): Pass to do.
            dag (DAGCircuit): The dag on which the pass is ran.
            options (dict): PassManager options.
        Returns:
            DAGCircuit: The transformed dag in case of a transformation pass.
            The same input dag in case of an analysis pass.
        Raises:
            TranspilerError: If the pass is not a proper pass instance.
        """

        # First, do the requires of pass_
        if not arg_3["ignore_requires"]:
            for arg_4 in arg_1.requires:
                arg_2 = arg_0.Func(arg_4, arg_2, arg_3)

        # Run the pass itself, if not already run
        if arg_1 not in arg_0.valid_passes:
            if arg_1.is_transformation_pass:
                arg_1.property_set = arg_0.fenced_property_set
                arg_6 = arg_1.run(arg_2)
                if not isinstance(arg_6, DAGCircuit):
                    raise TranspilerError("Transformation passes should return a transformed dag."
                                          "The pass %s is returning a %s" % (type(arg_1).__name__,
                                                                             type(arg_6)))
                arg_2 = arg_6
            elif arg_1.is_analysis_pass:
                arg_1.property_set = arg_0.property_set
                arg_1.run(FencedDAGCircuit(arg_2))
            else:
                raise TranspilerError("I dont know how to handle this type of pass")

            # update the valid_passes property
            arg_0._update_valid_passes(arg_1, arg_3['ignore_preserves'])

        return arg_2


def Func(arg_0):
        """
        Returns a list structure of the appended Func and its options.

        Returns (list): The appended Func.
        """
        arg_1 = []
        for arg_2 in arg_0.working_list:
            arg_1.append(arg_2.dump_Func())
        return arg_1


def Func(arg_0):
        """
        Fetches the passes added to this flow controller.

        Returns (dict): {'options': self.options, 'passes': [passes], 'type': type(self)}
        """
        arg_1 = {'options': arg_0.options, 'passes': [], 'type': type(arg_0)}
        for arg_2 in arg_0._passes:
            if isinstance(arg_2, FlowController):
                arg_1['passes'].append(arg_2.Func())
            else:
                arg_1['passes'].append(arg_2)
        return arg_1


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Constructs a flow controller based on the partially evaluated controller arguments.

        Args:
            passes (list[BasePass]): passes to add to the flow controller.
            options (dict): PassManager options.
            **partial_controller (dict): Partially evaluated controller arguments in the form
                `{name:partial}`

        Raises:
            TranspilerError: When partial_controller is not well-formed.

        Returns:
            FlowController: A FlowController instance.
        """
        if None in arg_3.values():
            raise TranspilerError('The controller needs a condition.')

        if arg_3:
            for arg_4 in arg_0.registered_controllers.keys():
                if arg_4 in arg_3:
                    return arg_0.registered_controllers[arg_4](arg_1, arg_2,
                                                                             **arg_3)
            raise TranspilerError("The controllers for %s are not registered" % arg_3)
        else:
            return FlowControllerLinear(arg_1, arg_2)


def Func(arg_0, arg_1=None):
    """Apply a single qubit gate to the qubit.

    Args:
        gate(str): the single qubit gate name
        params(list): the operation parameters op['params']
    Returns:
        tuple: a tuple of U gate parameters (theta, phi, lam)
    Raises:
        QiskitError: if the gate name is not valid
    """
    if arg_0 in ('U', 'u3'):
        return arg_1[0], arg_1[1], arg_1[2]
    elif arg_0 == 'u2':
        return np.pi / 2, arg_1[0], arg_1[1]
    elif arg_0 == 'u1':
        return 0, 0, arg_1[0]
    elif arg_0 == 'id':
        return 0, 0, 0
    raise QiskitError('Gate is not among the valid types: %s' % arg_0)


def Func(arg_0, arg_1=None):
    """Get the matrix for a single qubit.

    Args:
        gate(str): the single qubit gate name
        params(list): the operation parameters op['params']
    Returns:
        array: A numpy array representing the matrix
    """

    # Converting sym to floats improves the performance of the simulator 10x.
    # This a is a probable a FIXME since it might show bugs in the simulator.
    (arg_2, arg_3, arg_4) = map(float, single_gate_params(arg_0, arg_1))

    return np.array([[np.cos(arg_2 / 2),
                      -np.exp(1j * arg_4) * np.sin(arg_2 / 2)],
                     [np.exp(1j * arg_3) * np.sin(arg_2 / 2),
                      np.exp(1j * arg_3 + 1j * arg_4) * np.cos(arg_2 / 2)]])


def Func(arg_0, arg_1):
    """Return the index string for Numpy.eignsum matrix-vector multiplication.

    The returned indices are to perform a matrix multiplication A.v where
    the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
    M <= N, and identity matrices are implied on the subsystems where A has no
    support on v.

    Args:
        gate_indices (list[int]): the indices of the right matrix subsystems
                                  to contract with the left matrix.
        number_of_qubits (int): the total number of qubits for the right matrix.

    Returns:
        str: An indices string for the Numpy.einsum function.
    """

    arg_2, arg_3, arg_4, arg_5 = _einsum_matmul_index_helper(arg_0,
                                                                    arg_1)

    # Combine indices into matrix multiplication string format
    # for numpy.einsum function
    return "{mat_l}{mat_r}, ".format(arg_2=arg_2, arg_3=arg_3) + \
           "{tens_lin}->{tens_lout}".format(arg_4=arg_4,
                                            arg_5=arg_5)


def Func(arg_0, arg_1):
    """Return the index string for Numpy.eignsum matrix multiplication.

    The returned indices are to perform a matrix multiplication A.v where
    the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
    M <= N, and identity matrices are implied on the subsystems where A has no
    support on v.

    Args:
        gate_indices (list[int]): the indices of the right matrix subsystems
                                   to contract with the left matrix.
        number_of_qubits (int): the total number of qubits for the right matrix.

    Returns:
        tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for
        that may be combined into a Numpy.einsum function string.

    Raises:
        QiskitError: if the total number of qubits plus the number of
        contracted indices is greater than 26.
    """

    # Since we use ASCII alphabet for einsum index labels we are limited
    # to 26 total free left (lowercase) and 26 right (uppercase) indexes.
    # The rank of the contracted tensor reduces this as we need to use that
    # many characters for the contracted indices
    if len(arg_0) + arg_1 > 26:
        raise QiskitError("Total number of free indexes limited to 26")

    # Indicies for N-qubit input tensor
    arg_2 = ascii_lowercase[:arg_1]

    # Indices for the N-qubit output tensor
    arg_3 = list(arg_2)

    # Left and right indices for the M-qubit multiplying tensor
    arg_4 = ""
    arg_5 = ""

    # Update left indices for mat and output
    for arg_6, arg_7 in enumerate(reversed(arg_0)):
        arg_4 += ascii_lowercase[-1 - arg_6]
        arg_5 += arg_2[-1 - arg_7]
        arg_3[-1 - arg_7] = ascii_lowercase[-1 - arg_6]
    arg_3 = "".join(arg_3)

    # Combine indices into matrix multiplication string format
    # for numpy.einsum function
    return arg_4, arg_5, arg_2, arg_3


def Func(arg_0):
    """Build a ``DAGCircuit`` object from a ``QuantumCircuit``.

    Args:
        circuit (QuantumCircuit): the input circuit.

    Return:
        DAGCircuit: the DAG representing the input circuit.
    """
    arg_1 = DAGCircuit()
    arg_1.name = arg_0.name
    for arg_3 in arg_0.qregs:
        arg_1.add_qreg(arg_3)
    for arg_3 in arg_0.cregs:
        arg_1.add_creg(arg_3)

    for arg_4, arg_5, arg_6 in arg_0.data:
        # Get arguments for classical control (if any)
        if arg_4.control is None:
            arg_7 = None
        else:
            arg_7 = (arg_4.control[0], arg_4.control[1])

        arg_1.apply_operation_back(arg_4.copy(),
                                        arg_5, arg_6, arg_7)

    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
    """Function used to fit the decay cosine."""
    # pylint: disable=invalid-name
    return arg_1 * np.exp(-arg_0 / arg_2) * np.cos(2 * np.pi * arg_3 * arg_0 + arg_4) + arg_5


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6,
                   arg_7):
    """Plot coherence data.

    Args:
        xdata
        ydata
        std_error
        fit
        fit_function
        xunit
        exp_str
        qubit_label
    Raises:
        ImportError: If matplotlib is not installed.
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('The function Func needs matplotlib. '
                          'Run "pip install matplotlib" before.')
    plt.errorbar(arg_0, arg_1, arg_2, marker='.',
                 markersize=9, c='b', linestyle='')
    plt.plot(arg_0, arg_4(arg_0, *arg_3), c='r', linestyle='--',
             label=(arg_6 + '= %s %s' % (str(round(arg_3[1])), arg_5)))
    plt.xticks(fontsize=14, rotation=70)
    plt.yticks(fontsize=14)
    plt.xlabel('time [%s]' % (arg_5), fontsize=16)
    plt.ylabel('P(1)', fontsize=16)
    plt.title(arg_6 + ' measurement of Q$_{%s}$' % (str(arg_7)), fontsize=18)
    plt.legend(fontsize=12)
    plt.grid(True)
    plt.show()


def Func(arg_0):
    """Take the raw rb data and convert it into averages and std dev

    Args:
        raw_rb (numpy.array): m x n x l list where m is the number of seeds, n
            is the number of Clifford sequences and l is the number of qubits

    Return:
        numpy_array: 2 x n x l list where index 0 is the mean over seeds, 1 is
            the std dev overseeds
    """
    arg_1 = []
    arg_1.append(np.mean(arg_0, 0))
    arg_1.append(np.std(arg_0, 0))

    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6=None,
                 arg_7=True):
    """Plot randomized benchmarking data.

    Args:
        xdata (list): list of subsequence lengths
        ydatas (list): list of lists of survival probabilities for each
            sequence
        yavg (list): mean of the survival probabilities at each sequence
            length
        yerr (list): error of the survival
        fit (list): fit parameters
        survival_prob (callable): function that computes survival probability
        ax (Axes or None): plot axis (if passed in)
        show_plt (bool): display the plot.

    Raises:
        ImportError: If matplotlib is not installed.
    """
    # pylint: disable=invalid-name

    if not HAS_MATPLOTLIB:
        raise ImportError('The function Func needs matplotlib. '
                          'Run "pip install matplotlib" before.')
    if arg_6 is None:
        plt.figure()
        arg_6 = plt.gca()

    # Plot the result for each sequence
    for arg_8 in arg_1:
        arg_6.plot(arg_0, arg_8, color='gray', linestyle='none', marker='x')
    # Plot the mean with error bars
    arg_6.errorbar(arg_0, arg_2, arg_3=arg_3, color='r', linestyle='--', linewidth=3)

    # Plot the fit
    arg_6.plot(arg_0, arg_5(arg_0, *arg_4), color='blue', linestyle='-', linewidth=2)
    arg_6.tick_params(labelsize=14)
    # ax.tick_params(axis='x',labelrotation=70)

    arg_6.set_xlabel('Clifford Length', fontsize=16)
    arg_6.set_ylabel('Z', fontsize=16)
    arg_6.grid(True)

    if arg_7:
        plt.show()


def Func(arg_0):
    """Validates the input to state visualization functions.

    Args:
        quantum_state (ndarray): Input state / density matrix.
    Returns:
        rho: A 2d numpy array for the density matrix.
    Raises:
        VisualizationError: Invalid input.
    """
    arg_1 = np.asarray(arg_0)
    if arg_1.ndim == 1:
        arg_1 = np.outer(arg_1, np.conj(arg_1))
    # Check the shape of the input is a square matrix
    arg_2 = np.shape(arg_1)
    if len(arg_2) != 2 or arg_2[0] != arg_2[1]:
        raise VisualizationError("Input is not a valid quantum state.")
    # Check state is an n-qubit state
    arg_3 = int(np.log2(arg_1.shape[0]))
    if 2 ** arg_3 != arg_1.shape[0]:
        raise VisualizationError("Input is not a multi-qubit quantum state.")
    return arg_1


def Func(arg_0):
    """Trim a PIL image and remove white space."""
    arg_1 = PIL.Image.new(arg_0.mode, arg_0.size, arg_0.getpixel((0, 0)))
    arg_2 = PIL.ImageChops.difference(arg_0, arg_1)
    arg_2 = PIL.ImageChops.add(arg_2, arg_2, 2.0, -100)
    arg_3 = arg_2.getbbox()
    if arg_3:
        arg_0 = arg_0.crop(arg_3)
    return arg_0


def Func(arg_0, arg_1):
    """Get the list of qubits drawing this gate would cover"""

    arg_2 = len(arg_0)
    arg_3 = 0
    for arg_4 in arg_1.qargs:
        arg_5 = arg_0.index(arg_4)

        if arg_5 < arg_2:
            arg_2 = arg_5
        if arg_5 > arg_3:
            arg_3 = arg_5

    if arg_1.cargs:
        return arg_0[arg_2:]

    return arg_0[arg_2:arg_3 + 1]


def Func(arg_0):
    """Build an ``Instruction`` object from a ``QuantumCircuit``.

    The instruction is anonymous (not tied to a named quantum register),
    and so can be inserted into another circuit. The instruction will
    have the same string name as the circuit.

    Args:
        circuit (QuantumCircuit): the input circuit.

    Return:
        Instruction: an instruction equivalent to the action of the
            input circuit. Upon decomposition, this instruction will
            yield the components comprising the original circuit.
    """
    arg_1 = Instruction(name=arg_0.name,
                              num_qubits=sum([qreg.size for qreg in arg_0.qregs]),
                              num_clbits=sum([creg.size for creg in arg_0.cregs]),
                              params=[])
    arg_1.control = None

    def find_bit_position(arg_3):
        """find the index of a given bit (Register, int) within
        a flat ordered list of bits of the circuit
        """
        if isinstance(arg_3[0], QuantumRegister):
            arg_4 = arg_0.qregs
        else:
            arg_4 = arg_0.cregs
        arg_5 = arg_4.index(arg_3[0])
        return sum([arg_6.size for arg_6 in arg_4[:arg_5]]) + arg_3[1]

    arg_7 = arg_0.data.copy()

    if arg_1.num_qubits > 0:
        arg_8 = QuantumRegister(arg_1.num_qubits, 'q')
    if arg_1.num_clbits > 0:
        arg_9 = ClassicalRegister(arg_1.num_clbits, 'c')

    arg_7 = list(map(lambda x:
                          (x[0],
                           list(map(lambda y: (arg_8, find_bit_position(y)), x[1])),
                           list(map(lambda y: (arg_9, find_bit_position(y)), x[2]))), arg_7))
    arg_1.definition = arg_7

    return arg_1


def Func(arg_0, arg_1):
        """
        Pick a convenient layout depending on the best matching
        qubit connectivity, and set the property `layout`.

        Args:
            dag (DAGCircuit): DAG to find layout for.

        Raises:
            TranspilerError: if dag wider than self.coupling_map
        """
        arg_2 = sum([arg_6.size for arg_6 in arg_1.qregs.values()])
        if arg_2 > arg_0.coupling_map.size():
            raise TranspilerError('Number of qubits greater than device.')
        arg_3 = arg_0._best_subset(arg_2)
        arg_4 = Layout()
        arg_5 = 0
        for arg_6 in arg_1.qregs.values():
            for arg_7 in range(arg_6.size):
                arg_4[(arg_6, arg_7)] = int(arg_3[arg_5])
                arg_5 += 1
        arg_0.property_set['layout'] = arg_4


def Func(arg_0, arg_1):
        """Computes the qubit mapping with the best connectivity.

        Args:
            n_qubits (int): Number of subset qubits to consider.

        Returns:
            ndarray: Array of qubits to use for best connectivity mapping.
        """
        if arg_1 == 1:
            return np.array([0])

        arg_2 = arg_0.coupling_map.size()

        arg_3 = np.asarray(arg_0.coupling_map.get_edges())
        arg_4 = np.ones_like(arg_3[:, 0])
        arg_5 = sp.coo_matrix((arg_4, (arg_3[:, 0], arg_3[:, 1])),
                                shape=(arg_2, arg_2)).tocsr()
        arg_6 = 0
        arg_7 = None
        # do bfs with each node as starting point
        for arg_8 in range(arg_5.shape[0]):
            arg_9 = cs.breadth_first_order(arg_5, i_start=arg_8, directed=False,
                                         return_predecessors=False)

            arg_10 = 0
            arg_11 = []
            for arg_12 in range(arg_1):
                arg_13 = arg_9[arg_12]
                for arg_14 in range(arg_5.indptr[arg_13],
                               arg_5.indptr[arg_13 + 1]):
                    arg_15 = arg_5.indices[arg_14]
                    for arg_16 in range(arg_1):
                        if arg_15 == arg_9[arg_16]:
                            arg_10 += 1
                            arg_11.append([arg_13, arg_15])
                            break

            if arg_10 > arg_6:
                arg_6 = arg_10
                arg_7 = arg_9[0:arg_1]
                # Return a best mapping that has reduced bandwidth
                arg_17 = {}
                for arg_18 in range(arg_7.shape[0]):
                    arg_17[arg_7[arg_18]] = arg_18
                arg_19 = [[arg_17[c[0]], arg_17[c[1]]] for c in arg_11]
                arg_20 = [arg_18[0] for arg_18 in arg_19]
                arg_21 = [arg_18[1] for arg_18 in arg_19]
                arg_4 = [1]*len(arg_20)
                arg_22 = sp.coo_matrix((arg_4, (arg_20, arg_21)),
                                             shape=(arg_1, arg_1)).tocsr()
                arg_23 = cs.reverse_cuthill_mckee(arg_22)
                arg_7 = arg_7[arg_23]
        return arg_7


def Func(arg_0, *arg_1):
    """Apply Func to circuit.
    If qargs is None, applies to all the qbits.
    Args is a list of QuantumRegister or single qubits.
    For QuantumRegister, applies Func to all the qubits in that register."""
    arg_2 = []

    arg_1 = _convert_to_bits(arg_1, [qbit for arg_3 in arg_0.qregs for qbit in arg_3])

    if not arg_1:  # None
        for arg_3 in arg_0.qregs:
            for arg_4 in range(arg_3.size):
                arg_2.append((arg_3, arg_4))

    for arg_5 in arg_1:
        if isinstance(arg_5, (QuantumRegister, list)):
            if isinstance(arg_5, QuantumRegister):
                arg_2.extend([(arg_5, arg_4) for arg_4 in range(arg_5.size)])
            else:
                arg_2.extend(arg_5)
        else:
            arg_2.append(arg_5)

    return arg_0.append(Barrier(len(arg_2)), arg_2, [])


def Func(arg_0, arg_1):
        """Process an Id or IndexedId node as a bit or register type.

        Return a list of tuples (Register,index).
        """
        # pylint: disable=inconsistent-return-statements
        arg_2 = None
        if arg_1.name in arg_0.dag.qregs:
            arg_2 = arg_0.dag.qregs[arg_1.name]
        elif arg_1.name in arg_0.dag.cregs:
            arg_2 = arg_0.dag.cregs[arg_1.name]
        else:
            raise QiskitError("expected qreg or creg name:",
                              "line=%s" % arg_1.line,
                              "file=%s" % arg_1.file)

        if arg_1.type == "indexed_id":
            # An indexed bit or qubit
            return [(arg_2, arg_1.index)]
        elif arg_1.type == "id":
            # A qubit or qreg or creg
            if not arg_0.bit_stack[-1]:
                # Global scope
                return [(arg_2, arg_3) for arg_3 in range(arg_2.size)]
            else:
                # local scope
                if arg_1.name in arg_0.bit_stack[-1]:
                    return [arg_0.bit_stack[-1][arg_1.name]]
                raise QiskitError("expected local bit name:",
                                  "line=%s" % arg_1.line,
                                  "file=%s" % arg_1.file)
        return None


def Func(arg_0, arg_1, arg_2=False):
        """Process a gate node.

        If opaque is True, process the node as an opaque gate node.
        """
        arg_0.gates[arg_1.name] = {}
        arg_5 = arg_0.gates[arg_1.name]
        arg_5["print"] = True  # default
        arg_5["opaque"] = arg_2
        arg_5["n_args"] = arg_1.n_args()
        arg_5["n_bits"] = arg_1.n_bits()
        if arg_1.n_args() > 0:
            arg_5["args"] = [element.name for element in arg_1.arguments.children]
        else:
            arg_5["args"] = []
        arg_5["bits"] = [c.name for c in arg_1.bitlist.children]
        if arg_2:
            arg_5["body"] = None
        else:
            arg_5["body"] = arg_1.body


def Func(arg_0, arg_1):
        """Process a CNOT gate node."""
        arg_2 = arg_0._process_bit_id(arg_1.children[0])
        arg_3 = arg_0._process_bit_id(arg_1.children[1])
        if not(len(arg_2) == len(arg_3) or len(arg_2) == 1 or len(arg_3) == 1):
            raise QiskitError("internal error: qreg size mismatch",
                              "line=%s" % arg_1.line, "file=%s" % arg_1.file)
        arg_4 = max([len(arg_2), len(arg_3)])
        for arg_5 in range(arg_4):
            if len(arg_2) > 1 and len(arg_3) > 1:
                arg_0.dag.apply_operation_back(CXBase(), [arg_2[arg_5], arg_3[arg_5]], [], arg_0.condition)
            elif len(arg_2) > 1:
                arg_0.dag.apply_operation_back(CXBase(), [arg_2[arg_5], arg_3[0]], [], arg_0.condition)
            else:
                arg_0.dag.apply_operation_back(CXBase(), [arg_2[0], arg_3[arg_5]], [], arg_0.condition)


def Func(arg_0, arg_1):
        """Process a measurement node."""
        arg_2 = arg_0._process_bit_id(arg_1.children[0])
        arg_3 = arg_0._process_bit_id(arg_1.children[1])
        if len(arg_2) != len(arg_3):
            raise QiskitError("internal error: reg size mismatch",
                              "line=%s" % arg_1.line, "file=%s" % arg_1.file)
        for arg_4, arg_5 in zip(arg_2, arg_3):
            arg_0.dag.apply_operation_back(Measure(), [arg_4], [arg_5], arg_0.condition)


def Func(arg_0, arg_1):
        """Process an if node."""
        arg_2 = arg_1.children[0].name
        arg_3 = arg_0.dag.cregs[arg_2]
        arg_4 = arg_1.children[1].value
        arg_0.condition = (arg_3, arg_4)
        arg_0._process_node(arg_1.children[2])
        arg_0.condition = None