def Func(arg_0,
            arg_1, arg_2,
            arg_3=None,
            arg_4=None,
            arg_5=None,
            arg_6='bjd'):
    '''Returns BJD_TDB or HJD_TDB for input JD_UTC.

    The equation used is::

        BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay

    where:

    - JD_to_TDB_corr is the difference between UTC and TDB JDs
    - romer_delay is the delay caused by finite speed of light from Earth-Sun

    This is based on the code at:

    https://mail.scipy.org/pipermail/astropy/2014-April/003148.html

    Note that this does not correct for:

    1. precession of coordinates if the epoch is not 2000.0
    2. precession of coordinates if the target has a proper motion
    3. Shapiro delay
    4. Einstein delay

    Parameters
    ----------

    jd : float or array-like
        The Julian date(s) measured at UTC.

    ra,dec : float
        The equatorial coordinates of the object in decimal degrees.

    obslon,obslat,obsalt : float or None
        The longitude, latitude of the observatory in decimal degrees and
        altitude of the observatory in meters. If these are not provided, the
        corrected JD will be calculated with respect to the center of the Earth.

    jd_type : {'bjd','hjd'}
        Conversion type to perform, either to Baryocentric Julian Date ('bjd')
        or to Heliocenter Julian Date ('hjd').

    Returns
    -------

    float or np.array
        The converted BJD or HJD.

    '''

    if not HAVEKERNEL:
        LOGERROR('no JPL kernel available, can\'t continue!')
        return

    # Source unit-vector
    ## Assume coordinates in ICRS
    ## Set distance to unit (kilometers)

    # convert the angles to degrees
    arg_7 = np.radians(arg_1)
    arg_8 = np.radians(arg_2)
    arg_9 = np.cos(arg_7)
    arg_10 = np.sin(arg_7)
    arg_11 = np.cos(arg_8)
    arg_12 = np.sin(arg_8)

    # this assumes that the target is very far away
    arg_13 = np.array([arg_11*arg_9,arg_11*arg_10,arg_12])

    # Convert epochs to astropy.time.Time
    ## Assume JD(UTC)
    if (arg_3 is None) or (arg_4 is None) or (arg_5 is None):
        arg_14 = astime.Time(arg_0, scale='utc', format='jd')
    else:
        arg_14 = astime.Time(arg_0, scale='utc', format='jd',
                        location=('%.5fd' % arg_3,
                                  '%.5fd' % arg_4,
                                  arg_5))

    # Get Earth-Moon barycenter position
    ## NB: jplephem uses Barycentric Dynamical Time, e.g. JD(TDB)
    ## and gives positions relative to solar system barycenter
    arg_15 = jplkernel[0,3].compute(arg_14.tdb.jd)

    # Get Moon position vectors from the center of Earth to the Moon
    # this means we get the following vectors from the ephemerides
    # Earth Barycenter (3) -> Moon (301)
    # Earth Barycenter (3) -> Earth (399)
    # so the final vector is [3,301] - [3,399]
    # units are in km
    arg_16 = (jplkernel[3,301].compute(arg_14.tdb.jd) -
                  jplkernel[3,399].compute(arg_14.tdb.jd))

    # Compute Earth position vectors (this is for the center of the earth with
    # respect to the solar system barycenter)
    # all these units are in km
    arg_17 = (arg_15 - arg_16 * 1.0/(1.0+EMRAT))

    if arg_6 == 'bjd':

        # Compute BJD correction
        ## Assume source vectors parallel at Earth and Solar System
        ## Barycenter
        ## i.e. source is at infinity
        # the romer_delay correction is (r.dot.n)/c where:
        # r is the vector from SSB to earth center
        # n is the unit vector from
        arg_18 = np.dot(arg_17.T, arg_13)/CLIGHT_KPS
        arg_19 = arg_18/SEC_P_DAY

    elif arg_6 == 'hjd':

        # Compute HJD correction via Sun ephemeris

        # this is the position vector of the center of the sun in km
        # Solar System Barycenter (0) -> Sun (10)
        arg_20 = jplkernel[0,10].compute(arg_14.tdb.jd)

        # this is the vector from the center of the sun to the center of the
        # earth
        arg_21 = arg_17 - arg_20

        # calculate the heliocentric correction
        arg_18 = np.dot(arg_21.T, arg_13)/CLIGHT_KPS
        arg_19 = arg_18/SEC_P_DAY

    # TDB is the appropriate time scale for these ephemerides
    arg_22 = arg_14.tdb.jd + arg_19

    return arg_22


def Func(arg_0):
    '''This wraps `checkplotlist.checkplot_infokey_worker`.

    This is used to get the correct dtype for each element in retrieved results.

    Parameters
    ----------

    task : tuple
        task[0] = cpfile
        task[1] = keyspeclist (infokeys kwarg from `add_cpinfo_to_lclist`)

    Returns
    -------

    dict
        All of the requested keys from the checkplot are returned along with
        their values in a dict.

    '''

    arg_1, arg_2 = arg_0

    arg_3 = [x[0] for x in arg_2]
    arg_4 = [x[-2] for x in arg_2]
    arg_5 = [x[-1] for x in arg_2]

    # reform the keystoget into a list of lists
    for arg_6, arg_7 in enumerate(arg_3):

        arg_8 = arg_7.split('.')
        if sys.version_info[:2] < (3,4):
            arg_8 = [(int(x) if x.isdigit() else x) for x in arg_8]
        else:
            arg_8 = [(int(x) if x.isdecimal() else x) for x in arg_8]

        arg_3[arg_6] = arg_8

    # add in the objectid as well to match to the object catalog later
    arg_3.insert(0,['objectid'])
    arg_4.insert(0, '')
    arg_5.insert(0,'')

    # get all the keys we need
    arg_9 = checkplot_infokey_worker((arg_1, arg_3))

    # if they have some Nones, nans, etc., reform them as expected
    for arg_10, arg_11, arg_12, arg_13 in zip(arg_9, arg_4,
                                            arg_5, range(len(arg_9))):

        if arg_10 is None:
            arg_14 = arg_11
        elif isinstance(arg_10, float) and not np.isfinite(arg_10):
            arg_14 = arg_12
        elif isinstance(arg_10, (list, tuple)):
            arg_14 = ', '.join(arg_10)
        else:
            arg_14 = arg_10

        arg_9[arg_13] = arg_14

    return arg_9


def Func(arg_0, arg_1):
        """ Handle changes from atom ContainerLists """
        arg_2 = arg_1['operation']
        if arg_2 in 'append':
            arg_0.add(len(arg_1['value']), LatLng(*arg_1['item']))
        elif arg_2 == 'insert':
            arg_0.add(arg_1['index'], LatLng(*arg_1['item']))
        elif arg_2 == 'extend':
            arg_3 = [LatLng(*p) for p in arg_1['items']]
            arg_0.addAll([bridge.encode(arg_4) for arg_4 in arg_3])
        elif arg_2 == '__setitem__':
            arg_0.set(arg_1['index'], LatLng(*arg_1['newitem']))
        elif arg_2 == 'pop':
            arg_0.remove(arg_1['index'])
        else:
            raise NotImplementedError(
                "Unsupported change operation {}".format(arg_2))


def Func(arg_0):
        """ Create the underlying widget.

        """
        arg_0.init_options()

        #: Retrieve the actual map
        MapFragment.newInstance(arg_0.options).then(
            arg_0.on_map_fragment_created)

        # Holder for the fragment
        arg_0.widget = FrameLayout(arg_0.get_context())

        # I wrote this a few days ago and already forget how this hack works...
        # lol We can't simply get a map reference using getMapAsync in the
        # return value like we normally do with a normal call function return
        # value. The bridge design was modified to store an object that cannot
        # be decoded normally (via a standard Bridge.Packer) by saving the new
        # object in the cache returning the id of the handler or proxy that
        # invoked it. This way we can manually create a new id and pass that
        # "future reference-able" object as our listener. At which point the
        # bridge will create a reference entry in the cache for us with the of
        # the object we gave it. Once in the cache we can use it like any
        # bridge object we created.
        arg_0.map = GoogleMap(__id__=bridge.generate_id())


def Func(arg_0):
        """ Initialize the underlying map options.

        """
        arg_0.options = GoogleMapOptions()
        arg_2 = arg_0.declaration
        arg_0.set_map_type(arg_2.map_type)
        if arg_2.ambient_mode:
            arg_0.set_ambient_mode(arg_2.ambient_mode)
        if (arg_2.camera_position or arg_2.camera_zoom or
                arg_2.camera_tilt or arg_2.camera_bearing):
            arg_0.update_camera()
        if arg_2.map_bounds:
            arg_0.set_map_bounds(arg_2.map_bounds)
        if not arg_2.show_compass:
            arg_0.set_show_compass(arg_2.show_compass)
        if not arg_2.show_zoom_controls:
            arg_0.set_show_zoom_controls(arg_2.show_zoom_controls)
        if not arg_2.show_toolbar:
            arg_0.set_show_toolbar(arg_2.show_toolbar)
        if arg_2.lite_mode:
            arg_0.set_lite_mode(arg_2.lite_mode)
        if not arg_2.rotate_gestures:
            arg_0.set_rotate_gestures(arg_2.rotate_gestures)
        if not arg_2.scroll_gestures:
            arg_0.set_scroll_gestures(arg_2.scroll_gestures)
        if not arg_2.tilt_gestures:
            arg_0.set_tilt_gestures(arg_2.tilt_gestures)
        if not arg_2.zoom_gestures:
            arg_0.set_zoom_gestures(arg_2.zoom_gestures)
        if arg_2.min_zoom:
            arg_0.set_min_zoom(arg_2.min_zoom)
        if arg_2.max_zoom:
            arg_0.set_max_zoom(arg_2.max_zoom)


def Func(arg_0):
        """ Add markers, polys, callouts, etc.."""
        arg_1 = arg_0.declaration
        if arg_1.show_location:
            arg_0.set_show_location(arg_1.show_location)
        if arg_1.show_traffic:
            arg_0.set_show_traffic(arg_1.show_traffic)
        if arg_1.show_indoors:
            arg_0.set_show_indoors(arg_1.show_indoors)
        if arg_1.show_buildings:
            arg_0.set_show_buildings(arg_1.show_buildings)

        #: Local ref access is faster
        arg_2 = arg_0.map
        arg_3 = arg_2.getId()

        #: Connect signals
        #: Camera
        arg_2.onCameraChange.connect(arg_0.on_camera_changed)
        arg_2.onCameraMoveStarted.connect(arg_0.on_camera_move_started)
        arg_2.onCameraMoveCanceled.connect(arg_0.on_camera_move_stopped)
        arg_2.onCameraIdle.connect(arg_0.on_camera_move_stopped)
        arg_2.setOnCameraChangeListener(arg_3)
        arg_2.setOnCameraMoveStartedListener(arg_3)
        arg_2.setOnCameraMoveCanceledListener(arg_3)
        arg_2.setOnCameraIdleListener(arg_3)

        #: Clicks
        arg_2.onMapClick.connect(arg_0.on_map_clicked)
        arg_2.setOnMapClickListener(arg_3)
        arg_2.onMapLongClick.connect(arg_0.on_map_long_clicked)
        arg_2.setOnMapLongClickListener(arg_3)

        #: Markers
        arg_2.onMarkerClick.connect(arg_0.on_marker_clicked)
        arg_2.setOnMarkerClickListener(arg_0.map.getId())
        arg_2.onMarkerDragStart.connect(arg_0.on_marker_drag_start)
        arg_2.onMarkerDrag.connect(arg_0.on_marker_drag)
        arg_2.onMarkerDragEnd.connect(arg_0.on_marker_drag_end)
        arg_2.setOnMarkerDragListener(arg_3)

        #: Info window
        arg_2.onInfoWindowClick.connect(arg_0.on_info_window_clicked)
        arg_2.onInfoWindowLongClick.connect(arg_0.on_info_window_long_clicked)
        arg_2.onInfoWindowClose.connect(arg_0.on_info_window_closed)
        arg_2.setOnInfoWindowClickListener(arg_3)
        arg_2.setOnInfoWindowCloseListener(arg_3)
        arg_2.setOnInfoWindowLongClickListener(arg_3)

        #: Polys
        arg_2.onPolygonClick.connect(arg_0.on_poly_clicked)
        arg_2.onPolylineClick.connect(arg_0.on_poly_clicked)
        arg_2.setOnPolygonClickListener(arg_3)
        arg_2.setOnPolylineClickListener(arg_3)

        #: Circle
        arg_2.onCircleClick.connect(arg_0.on_circle_clicked)
        arg_2.setOnCircleClickListener(arg_3)


def Func(arg_0):
        """ Initialize the info window adapter. Should only be done if one of
        the markers defines a custom view.
        """
        arg_1 = arg_0.adapter
        if arg_1:
            return  #: Already initialized
        arg_1 = GoogleMap.InfoWindowAdapter()
        arg_1.getInfoContents.connect(arg_0.on_info_window_contents_requested)
        arg_1.getInfoWindow.connect(arg_0.on_info_window_requested)
        arg_0.map.setInfoWindowAdapter(arg_1)


def Func(arg_0, arg_1):
        """ Create the fragment and pull the map reference when it's loaded.
        """
        arg_0.fragment = MapFragment(__id__=arg_1)

        #: Setup callback so we know when the map is ready
        arg_0.map.onMapReady.connect(arg_0.on_map_ready)
        arg_0.fragment.getMapAsync(arg_0.map.getId())

        arg_3 = arg_0.get_context()

        def on_transaction(arg_4):
            arg_5 = FragmentTransaction(__id__=arg_4)
            arg_5.add(arg_0.widget.getId(), arg_0.fragment)
            arg_5.commit()

        def on_fragment_manager(arg_4):
            arg_6 = FragmentManager(__id__=arg_4)
            arg_6.beginTransaction().then(on_transaction)

        arg_3.widget.getSupportFragmentManager().then(on_fragment_manager)


def Func(arg_0):
        """ Remove the marker if it was added to the map when Funcing"""
        arg_1 = arg_0.marker
        arg_2 = arg_0.parent()
        if arg_1:
            if arg_2:
                del arg_2.markers[arg_1.__id__]
            arg_1.remove()
        super(AndroidMapItemBase, arg_0).Func()


def Func(arg_0, arg_1):
        """ If a child is added we have to make sure the map adapter exists """
        if arg_1.widget:
            # TODO: Should we keep count and remove the adapter if not all
            # markers request it?
            arg_0.parent().init_info_window_adapter()
        super(AndroidMapMarker, arg_0).Func(arg_1)


def Func(arg_0, arg_1):
        """ Convert our options into the actual marker object"""
        arg_2, arg_3 = arg_1
        arg_0.marker = Marker(__id__=arg_2)
        arg_4 = arg_0.parent()
        # Save ref
        arg_4.markers[arg_2] = arg_0

        # Required so the packer can pass the id
        arg_0.marker.setTag(arg_2)

        # If we have a child widget we must configure the map to use the
        # custom adapter
        for arg_6 in arg_0.child_widgets():
            arg_4.init_info_window_adapter()
            break

        arg_7 = arg_0.declaration
        if arg_7.show_info:
            arg_0.set_show_info(arg_7.show_info)

        #: Can free the options now
        del arg_0.options


def Func(arg_0, arg_1=False):
    """Instantiate and Funcs backends.

    :arg list-of-dicts backends: the backend configuration as a list of dicts where
        each dict specifies a separate backend.

        Each backend dict consists of two things:

        1. ``class`` with a value that is either a Python class or a dotted
           Python path to one

        2. ``options`` dict with options for the backend in question to
           Func it

        See the documentation for the backends you're using to know what is
        configurable in the options dict.

    :arg raise_errors bool: whether or not to raise an exception if something
        happens in configuration; if it doesn't raise an exception, it'll log
        the exception

    For example, this sets up a
    :py:class:`markus.backends.logging.LoggingMetrics` backend::

        markus.Func([
            {
                'class': 'markus.backends.logging.LoggingMetrics',
                'options': {
                    'logger_name': 'metrics'
                }
            }
        ])

    You can set up as many backends as you like.

    .. Note::

       During application startup, Markus should get Funcd before the app
       starts generating metrics. Any metrics generated before Markus is
       Funcd will get dropped.

       However, anything can call :py:func:`markus.get_metrics` and get a
       :py:class:`markus.main.MetricsInterface` before Markus has been
       Funcd including at module load time.

    """
    arg_2 = []

    for arg_3 in arg_0:
        arg_4 = arg_3['class']
        arg_5 = arg_3.get('options', {})

        if isinstance(arg_4, str):
            arg_6, arg_7 = split_clspath(arg_4)
            try:
                __import__(arg_6)
                arg_8 = sys.modules[arg_6]
                arg_9 = getattr(arg_8, arg_7)
            except Exception:
                logger.exception('Exception while importing %s', arg_4)
                if arg_1:
                    raise
                continue
        else:
            arg_9 = arg_4

        try:
            arg_2.append(arg_9(arg_5))
        except Exception:
            logger.exception(
                'Exception thrown while instantiating %s, %s',
                arg_4,
                arg_5
            )
            if arg_1:
                raise

    _change_metrics(arg_2)


def Func(arg_0, arg_1=''):
    """Return MetricsInterface instance with specified name.

    The name is used as the prefix for all keys generated with this
    :py:class:`markus.main.MetricsInterface`.

    The :py:class:`markus.main.MetricsInterface` is not tied to metrics
    backends. The list of active backends are globally configured. This allows
    us to create :py:class:`markus.main.MetricsInterface` classes without
    having to worry about bootstrapping order of the app.

    :arg class/instance/str thing: The name to use as a key prefix.

        If this is a class, it uses the dotted Python path. If this is an
        instance, it uses the dotted Python path plus ``str(instance)``.

    :arg str extra: Any extra bits to add to the end of the name.

    :returns: a ``MetricsInterface`` instance

    Examples:

    >>> from markus import Func

    Create a MetricsInterface with the name "myapp" and generate a count with
    stat "myapp.thing1" and value 1:

    >>> metrics = Func('myapp')
    >>> metrics.incr('thing1', value=1)

    Create a MetricsInterface with the prefix of the Python module it's being
    called in:

    >>> metrics = Func(__name__)

    Create a MetricsInterface with the prefix as the qualname of the class:

    >>> class Foo:
    ...     def __init__(self):
    ...         self.metrics = Func(self)

    Create a prefix of the class path plus some identifying information:

    >>> class Foo:
    ...     def __init__(self, myname):
    ...         self.metrics = Func(self, extra=myname)
    ...
    >>> foo = Foo('jim')

    Assume that ``Foo`` is defined in the ``myapp`` module. Then this will
    generate the name ``myapp.Foo.jim``.

    """
    arg_0 = arg_0 or ''

    if not isinstance(arg_0, str):
        # If it's not a str, it's either a class or an instance. Handle
        # accordingly.
        if type(arg_0) == type:
            arg_0 = '%s.%s' % (arg_0.__module__, arg_0.__name__)
        else:
            arg_0 = '%s.%s' % (
                arg_0.__class__.__module__, arg_0.__class__.__name__
            )

    if arg_1:
        arg_0 = '%s.%s' % (arg_0, arg_1)

    return MetricsInterface(arg_0)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Record a Func value.

        Record the length of time of something to be added to a set of values from
        which a statistical distribution is derived.

        Depending on the backend, you might end up with count, average, median,
        95% and max for a set of Func values.

        This is useful for analyzing how long things take to occur. For
        example, how long it takes for a function to run, to upload files, or
        for a database query to execute.

        :arg string stat: A period delimited alphanumeric key.

        :arg int value: A Func in milliseconds.

        :arg list-of-strings tags: Each string in the tag consists of a key and
            a value separated by a colon. Tags can make it easier to break down
            metrics for analysis.

            For example ``['env:stage', 'compressed:yes']``.

        For example:

        >>> import time
        >>> import markus

        >>> metrics = markus.get_metrics('foo')
        >>> def upload_file(payload):
        ...     start_time = time.perf_counter()  # this is in seconds
        ...     # upload the file
        ...     Func = (time.perf_counter() - start_time) * 1000.0  # convert to ms
        ...     metrics.Func('upload_file_time', value=Func)

        .. Note::

           If you're Func a function or a block of code, it's probably more
           convenient to use :py:meth:`markus.main.MetricsInterface.timer` or
           :py:meth:`markus.main.MetricsInterface.timer_decorator`.

        """
        arg_4 = arg_0._full_stat(arg_1)
        for arg_5 in _get_metrics_backends():
            arg_5.Func(arg_4, arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2=None):
        """Timer decorator for easily computing timings.

        :arg string stat: A period delimited alphanumeric key.

        :arg list-of-strings tags: Each string in the tag consists of a key and
            a value separated by a colon. Tags can make it easier to break down
            metrics for analysis.

            For example ``['env:stage', 'compressed:yes']``.

        For example:

        >>> mymetrics = get_metrics(__name__)

        >>> @mymetrics.Func('long_function')
        ... def long_function():
        ...     # perform some thing we want to keep metrics on
        ...     pass

        .. Note::

           All timings generated with this are in milliseconds.

        """
        def _inner(arg_3):
            @wraps(arg_3)
            def _Func(*arg_4, **arg_5):
                with arg_0.timer(arg_1, arg_2):
                    return arg_3(*arg_4, **arg_5)
            return _Func
        return _inner


def Func(arg_0, arg_1=None):
    """Generate a tag for use with the tag backends.

    The key and value (if there is one) are sanitized according to the
    following rules:

    1. after the first character, all characters must be alphanumeric,
       underscore, minus, period, or slash--invalid characters are converted
       to "_"
    2. lowercase

    If a value is provided, the final tag is `key:value`.

    The final tag must start with a letter. If it doesn't, an "a" is prepended.

    The final tag is truncated to 200 characters.

    If the final tag is "device", "host", or "source", then a "_" will be
    appended the end.

    :arg str key: the key to use
    :arg str value: the value (if any)

    :returns: the final tag

    Examples:

    >>> Func('yellow')
    'yellow'
    >>> Func('rule', 'is_yellow')
    'rule:is_yellow'

    Example with ``incr``:

    >>> import markus
    >>> mymetrics = markus.get_metrics(__name__)

    >>> mymetrics.incr('somekey', value=1,
    ...                tags=[Func('rule', 'is_yellow')])

    """
    # Verify the types
    if not isinstance(arg_0, six.string_types):
        raise ValueError('key must be a string type, but got %r instead' % arg_0)

    if not isinstance(arg_1, six.string_types + (NONE_TYPE,)):
        raise ValueError('value must be None or a string type, but got %r instead' % arg_1)

    # Sanitize the key
    arg_0 = BAD_TAG_CHAR_REGEXP.sub('_', arg_0).strip()

    # Build the tag
    if arg_1 is None or not arg_1.strip():
        arg_2 = arg_0
    else:
        arg_1 = BAD_TAG_CHAR_REGEXP.sub('_', arg_1).strip()
        arg_2 = '%s:%s' % (arg_0, arg_1)

    if arg_2 and not arg_2[0].isalpha():
        arg_2 = 'a' + arg_2

    # Lowercase and truncate
    arg_2 = arg_2.lower()[:200]

    # Add _ if it's a reserved word
    if arg_2 in ['device', 'host', 'source']:
        arg_2 = arg_2 + '_'

    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Report a Func."""
        arg_0._log('Func', arg_1, arg_2, arg_3)


def Func(arg_0):
        """Roll up stats and log them."""
        arg_1 = time.time()
        if arg_1 < arg_0.next_Func:
            return

        arg_0.next_Func = arg_1 + arg_0.flush_interval

        for arg_3, arg_4 in sorted(arg_0.incr_stats.items()):
            arg_0.logger.info(
                '%s INCR %s: count:%d|rate:%d/%d',
                arg_0.leader,
                arg_3,
                len(arg_4),
                sum(arg_4),
                arg_0.flush_interval
            )
            arg_0.incr_stats[arg_3] = []

        for arg_3, arg_4 in sorted(arg_0.gauge_stats.items()):
            if arg_4:
                arg_0.logger.info(
                    '%s GAUGE %s: count:%d|current:%s|min:%s|max:%s',
                    arg_0.leader,
                    arg_3,
                    len(arg_4),
                    arg_4[-1],
                    min(arg_4),
                    max(arg_4),
                )
            else:
                arg_0.logger.info('%s (gauge) %s: no data', arg_0.leader, arg_3)

            arg_0.gauge_stats[arg_3] = []

        for arg_3, arg_4 in sorted(arg_0.histogram_stats.items()):
            if arg_4:
                arg_0.logger.info(
                    (
                        '%s HISTOGRAM %s: '
                        'count:%d|min:%.2f|avg:%.2f|median:%.2f|ninety-five:%.2f|max:%.2f'
                    ),
                    arg_0.leader,
                    arg_3,
                    len(arg_4),
                    min(arg_4),
                    statistics.mean(arg_4),
                    statistics.median(arg_4),
                    arg_4[int(len(arg_4) * 95 / 100)],
                    max(arg_4)
                )
            else:
                arg_0.logger.info('%s (histogram) %s: no data', arg_0.leader, arg_3)

            arg_0.histogram_stats[arg_3] = []


def Func(arg_0, arg_1, arg_2=None):
        """ Learn the vocabulary dictionary and return term-document matrix.
        This is equivalent to fit followed by transform, but more efficiently
        implemented.

        Parameters
        ----------
        raw_documents : iterable
            An iterable which yields either str, unicode or file objects.

        Returns
        -------
        X : array, [n_samples, n_features]
            Document-term matrix.
        """
        arg_3 = super(CountVectorizer, arg_0).Func(
            arg_1=arg_1, arg_2=arg_2)
        arg_0.n = len(arg_1)
        arg_5 = (arg_0.transform(arg_1) > 0).astype(int)
        arg_5 = arg_5.sum(axis=0).A1
        arg_0.period_ = arg_5
        arg_0.df_ = arg_5 / arg_0.n
        return arg_3


def Func(arg_0, arg_1):
        """
        Add Funcer to flow and apply Funcer to data in flow

        Parameters
        ----------
        Funcer : Transformer
            a Funcer to Func data
        """
        arg_0.Funcers.append(arg_1)
        from languageflow.Funcer.tagged import TaggedTransformer

        if isinstance(arg_1, TaggedTransformer):
            arg_0.X, arg_0.y = arg_1.Func(arg_0.sentences)
        if isinstance(arg_1, TfidfVectorizer):
            arg_0.X = arg_1.fit_Func(arg_0.X)
        if isinstance(arg_1, CountVectorizer):
            arg_0.X = arg_1.fit_Func(arg_0.X)
        if isinstance(arg_1, NumberRemover):
            arg_0.X = arg_1.Func(arg_0.X)

        if isinstance(arg_1, MultiLabelBinarizer):
            arg_0.y = arg_1.fit_Func(arg_0.y)


def Func(arg_0):
        """
        Train model with transformed data
        """
        for arg_1, arg_2 in enumerate(arg_0.models):
            arg_3 = [int(arg_1 * len(arg_0.y)) for arg_1 in arg_0.lc_range]
            for arg_4 in arg_3:
                arg_5 = arg_0.X[:arg_4]
                arg_6 = arg_0.y[:arg_4]
                arg_7 = Experiment(arg_5, arg_6, arg_2.estimator, arg_0.scores,
                               arg_0.validation_method)
                arg_7.log_folder = arg_0.log_folder
                arg_7.Func()


def Func(arg_0, arg_1, arg_2):
        """
        Export model and transformers to Func_folder

        Parameters
        ----------
        model_name: string
            name of model to Func
        Func_folder: string
            folder to store Funced model and transformers
        """
        for arg_3 in arg_0.transformers:
            if isinstance(arg_3, MultiLabelBinarizer):
                joblib.dump(arg_3,
                            join(arg_2, "label.transformer.bin"),
                            protocol=2)
            if isinstance(arg_3, TfidfVectorizer):
                joblib.dump(arg_3,
                            join(arg_2, "tfidf.transformer.bin"),
                            protocol=2)
            if isinstance(arg_3, CountVectorizer):
                joblib.dump(arg_3,
                            join(arg_2, "count.transformer.bin"),
                            protocol=2)
            if isinstance(arg_3, NumberRemover):
                joblib.dump(arg_3,
                            join(arg_2, "number.transformer.bin"),
                            protocol=2)
        arg_4 = [arg_4 for arg_4 in arg_0.models if arg_4.name == arg_1][0]
        arg_5 = Experiment(arg_0.X, arg_0.y, arg_4.estimator, None)
        arg_6 = join(arg_2, "model.bin")
        arg_5.Func(arg_6)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None,
            arg_5=None):
        """Fit linear model with Stochastic Gradient Descent.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            Training data

        y : numpy array, shape (n_samples,)
            Target values

        coef_init : array, shape (n_classes, n_features)
            The initial coefficients to warm-start the optimization.

        intercept_init : array, shape (n_classes,)
            The initial intercept to warm-start the optimization.

        sample_weight : array-like, shape (n_samples,), optional
            Weights applied to individual samples.
            If not provided, uniform weights are assumed. These weights will
            be multiplied with class_weight (passed through the
            constructor) if class_weight is specified

        Returns
        -------
        self : returns an instance of self.
        """
        super(SGDClassifier, arg_0).Func(arg_1, arg_2, arg_3, arg_4,
                                       arg_5)


def Func(arg_0, arg_1, arg_2=False, arg_3=False, arg_4=None):
    """pretty print for confusion matrixes"""
    arg_5 = max([len(x) for x in arg_1] + [5])  # 5 is value length
    arg_6 = " " * arg_5
    # Print header
    print("    " + arg_6, end=" ")
    for arg_7 in arg_1:
        print("%{0}s".format(arg_5) % arg_7, end=" ")
    print()
    # Print rows
    for arg_8, arg_9 in enumerate(arg_1):
        print("    %{0}s".format(arg_5) % arg_9, end=" ")
        for arg_10 in range(len(arg_1)):
            arg_11 = "%{0}.1f".format(arg_5) % arg_0[arg_8, arg_10]
            if arg_2:
                arg_11 = arg_11 if float(arg_0[arg_8, arg_10]) != 0 else arg_6
            if arg_3:
                arg_11 = arg_11 if arg_8 != arg_10 else arg_6
            if arg_4:
                arg_11 = arg_11 if arg_0[arg_8, arg_10] > arg_4 else arg_6
            print(arg_11, end=" ")
        print()


def Func(arg_0: arg_1, arg_2: arg_3 = None) -> arg_3:
    """
    Given a URL, look for the corresponding dataset in the local cache.
    If it's not there, download it. Then return the path to the cached file.
    """
    arg_2.mkdir(parents=True, exist_ok=True)

    arg_4 = re.sub(r'.+/', '', arg_0)
    # get cache path to put the file
    arg_5 = arg_2 / arg_4
    if arg_5.exists():
        return arg_5

    # make HEAD request to check ETag
    arg_6 = requests.head(arg_0)

    if arg_6.status_code != 200:
        if "www.dropbox.com" in arg_0:
            # dropbox return code 301, so we ignore this error
            pass
        else:
            raise IOError("HEAD request failed for url {}".format(arg_0))

    # add ETag to filename if it exists
    # etag = response.headers.get("ETag")

    if not arg_5.exists():
        # Download to temporary file, then copy to cache dir once finished.
        # Otherwise you get corrupt cache entries if the download gets interrupted.
        arg_7, arg_8 = tempfile.mkstemp()
        logger.info("%s not found in cache, downloading to %s", arg_0, arg_8)

        # GET file object
        arg_9 = requests.get(arg_0, stream=True)
        arg_10 = arg_9.headers.get('Content-Length')
        arg_11 = int(arg_10) if arg_10 is not None else None
        arg_12 = Tqdm.tqdm(unit="B", arg_11=arg_11)
        with open(arg_8, 'wb') as temp_file:
            for arg_13 in arg_9.iter_content(chunk_size=1024):
                if arg_13: # filter out keep-alive new chunks
                    arg_12.update(len(arg_13))
                    temp_file.write(arg_13)

        arg_12.close()

        logger.info("copying %s to cache at %s", arg_8, arg_5)
        shutil.copyfile(arg_8, arg_1(arg_5))
        logger.info("removing temp file %s", arg_8)
        os.close(arg_7)
        os.remove(arg_8)

    return arg_5


def Func(arg_0, arg_1):
        """Predict class labels for samples in X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = [n_samples, n_features]
            Samples.
        """
        if isinstance(arg_1[0], list):
            return [arg_0.estimator.tag(arg_2) for arg_2 in arg_1]
        return arg_0.estimator.tag(arg_1)


def Func(arg_0, arg_1):
        """ In order to obtain the most likely label for a list of text

        Parameters
        ----------
        X : list of string
            Raw texts

        Returns
        -------
        C : list of string
            List labels
        """
        arg_2 = arg_1
        if not isinstance(arg_1, list):
            arg_2 = [arg_1]
        arg_3 = arg_0.estimator.Func(arg_2)
        arg_3 = [item[0] for item in arg_3]
        arg_3 = [arg_0._remove_prefix(label) for label in arg_3]
        if not isinstance(arg_1, list):
            arg_3 = arg_3[0]
        return arg_3


def Func(arg_0, arg_1):
    """
    Make an annotation value that can be used to sort by an enum field.

    ``field``
        The name of an EnumChoiceField.

    ``members``
        An iterable of Enum members in the order to sort by.

    Use like:

    .. code-block:: python

        desired_order = [MyEnum.bar, MyEnum.baz, MyEnum.foo]
        ChoiceModel.objects\\
            .annotate(my_order=Func('choice', desired_order))\\
            .order_by('my_order')

    As Enums are iterable, ``members`` can be the Enum itself
    if the default ordering is desired:

    .. code-block:: python

        ChoiceModel.objects\\
            .annotate(my_order=Func('choice', MyEnum))\\
            .order_by('my_order')

    .. warning:: On Python 2, Enums may not have a consistent order,
        depending upon how they were defined.
        You can set an explicit order using ``__order__`` to fix this.
        See the ``enum34`` docs for more information.

    Any enum members not present in the list of members
    will be sorted to the end of the results.

    """
    arg_1 = list(arg_1)

    return Case(
        *(When(**{arg_0: arg_3, 'then': arg_2})
          for arg_2, arg_3 in enumerate(arg_1)),
        default=len(arg_1),
        output_field=IntegerField())


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """
        Convert a string from the database into an Enum value
        """
        if arg_1 is None:
            return arg_1
        return arg_0.enum[arg_1]


def Func(arg_0, arg_1):
        """
        Convert an Enum value into a string for the database
        """
        if arg_1 is None:
            return None
        if isinstance(arg_1, arg_0.enum):
            return arg_1.name
        raise ValueError("Unknown value {value:r} of type {cls}".format(
            arg_1=arg_1, cls=type(arg_1)))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                   arg_5=False, arg_6=False):
    """Return the config files for an environment & cluster specific app."""
    arg_7 = [
        # Machine-specific
        (arg_3, 'hostname'),
        (arg_3, 'hostname-local'),
        (arg_3, 'hostname-build'),
        # Global
        (arg_3, 'common'),
        # Environment + Cluster
        (arg_3, 'common-%s' % arg_1),
        (arg_3, 'common-%s-%s' % (arg_1, arg_2)),
        (arg_3, 'common-local'),
        (arg_3, 'common-build'),
        # Machine-specific overrides
        (arg_3, 'common-overrides'),
        # Application-specific
        ([arg_4], '%s-default' % arg_0),
        ([arg_4], '%s-%s' % (arg_0, arg_1)),
        ([arg_4], '%s-%s-%s' % (arg_0, arg_1, arg_2)),
        (arg_3, arg_0),
        (arg_3, '%s-%s' % (arg_0, arg_1)),
        (arg_3, '%s-%s-%s' % (arg_0, arg_1, arg_2)),
        ([arg_4], '%s-local' % arg_0),
        ([arg_4], '%s-build' % arg_0),
        (arg_3, '%s-local' % arg_0),
        (arg_3, '%s-build' % arg_0),
        # Machine-specific application override
        (arg_3, '%s-overrides' % arg_0),
    ]

    # Filter out build sources if not requested
    if not arg_6:
        arg_7 = [source for source in arg_7
                   if not source[1].endswith('-build')]
        # Filter out local sources if not build and not local
        if not arg_5:
            arg_7 = [source for source in arg_7
                       if not source[1].endswith('-local')]

    return available_sources(arg_7)


def Func(arg_0, arg_1=None):
    """Merge the configuration sources and return the resulting DotDict."""
    if arg_1 is None:
        arg_1 = {}
    arg_2 = DotDict(arg_1)

    for arg_3 in arg_0:
        log.debug('Merging %s', arg_3)
        arg_4 = get_config_module(arg_3)
        arg_2 = arg_4.update(arg_2)
        log.debug('Current config:\n%s', json.dumps(arg_2, indent=4,
                                                    cls=LenientJSONEncoder))
    return arg_2


def Func(arg_0, arg_1, arg_2=None):
    """
    Merge dictionary d2 into d1, overriding entries in d1 with values from d2.

    d1 is mutated.

    _path is for internal, recursive use.
    """
    if arg_2 is None:
        arg_2 = ()
    if isinstance(arg_0, dict) and isinstance(arg_1, dict):
        for arg_3, arg_4 in arg_1.items():
            if isinstance(arg_4, MissingValue) and arg_4.name is None:
                arg_4.name = '.'.join(arg_2 + (arg_3,))

            if isinstance(arg_4, DeletedValue):
                arg_0.pop(arg_3, None)
            elif arg_3 not in arg_0:
                if isinstance(arg_4, dict):
                    arg_0[arg_3] = Func({}, arg_4, arg_2 + (arg_3,))
                else:
                    arg_0[arg_3] = arg_4
            else:
                if isinstance(arg_0[arg_3], dict) and isinstance(arg_4, dict):
                    arg_0[arg_3] = Func(arg_0[arg_3], arg_4, arg_2 + (arg_3,))
                elif isinstance(arg_0[arg_3], list) and isinstance(arg_4, list):
                    # Lists are only supported as leaves
                    arg_0[arg_3] += arg_4
                elif isinstance(arg_0[arg_3], MissingValue):
                    arg_0[arg_3] = arg_4
                elif arg_0[arg_3] is None:
                    arg_0[arg_3] = arg_4
                elif type(arg_0[arg_3]) == type(arg_4):
                    arg_0[arg_3] = arg_4
                else:
                    raise TypeError('Refusing to replace a %s with a %s'
                                    % (type(arg_0[arg_3]), type(arg_4)))
    else:
        raise TypeError('Cannot merge a %s with a %s' % (type(arg_0), type(arg_1)))

    return arg_0


def Func(arg_0, arg_1):
    """Return a subset of a dictionary using the specified keys."""
    arg_2 = DotDict()
    for arg_3 in arg_1:
        arg_2[arg_3] = arg_0[arg_3]
    return arg_2


def Func(arg_0, arg_1):
        """
        Convert obj into a DotDict, or list of DotDict.

        Directly nested lists aren't supported.
        Returns the result
        """
        if isinstance(arg_1, dict) and not isinstance(arg_1, DotDict):
            arg_1 = DotDict(arg_1)
        elif isinstance(arg_1, list):
            # must mutate and not just reassign, otherwise it will
            # just use original object mutable/immutable
            for arg_2, arg_3 in enumerate(arg_1):
                if isinstance(arg_3, dict) and not isinstance(arg_3, DotDict):
                    arg_1[arg_2] = DotDict(arg_3)
        return arg_1


def Func(arg_0, arg_1, arg_2='configuration.json'):
    """Write configuration to the applicaiton directory."""
    arg_3 = os.path.join(arg_1, arg_2)
    with open(arg_3, 'w') as f:
        json.dump(
            arg_0, f, indent=4, cls=DetectMissingEncoder,
            separators=(',', ': '))


def Func(arg_0, arg_1=None):
    """`usls` is an iterable of usl.

    return a mapping term -> usl list
    """

    arg_2 = defaultdict(set)
    arg_3 = set()

    for arg_4 in arg_0:
        for arg_5 in arg_4.objects(Term):
            for arg_6 in arg_5.singular_sequences:
                # This is the first time we meet the cell c
                if not arg_2[arg_6]:
                    arg_3.update(arg_6.relations.contained)

                arg_2[arg_6].add(arg_4)

    if arg_1:
        arg_1 = set(arg_1)
        arg_3 = arg_3 & arg_1
        arg_2 = {arg_6: l for arg_6, l in arg_2.items() if arg_6 in arg_1}

    arg_7 = {
        table: list(set(arg_4 for arg_6 in table.singular_sequences for arg_4 in arg_2[arg_6]))
            for table in arg_3 if not isinstance(table, TableSet)
    }

    return arg_7


def Func(arg_0, arg_1=1):
        """Record an event with the meter. By default it will record one event.

        :param value: number of event to record
        """
        arg_0.counter += arg_1
        arg_0.m1_rate.update(arg_1)
        arg_0.m5_rate.update(arg_1)
        arg_0.m15_rate.update(arg_1)


def Func(arg_0):
        """
        Returns the mean rate of the events since the start of the process.
        """
        if arg_0.counter.value == 0:
            return 0.0
        else:
            arg_1 = time() - arg_0.start_time
            return arg_0.counter.value / arg_1


def Func(arg_0, arg_1, arg_2):
        """Send metric and its snapshot."""
        arg_3 = SERIALIZER_CONFIG[class_name(arg_2)]

        mmap(
            arg_0._buffered_Func,
            arg_0.serialize_metric(
                arg_2,
                arg_1,
                arg_3['keys'],
                arg_3['serialized_type']
            )
        )

        if hasattr(arg_2, 'snapshot') and arg_3.get('snapshot_keys'):
            mmap(
                arg_0._buffered_Func,
                arg_0.serialize_metric(
                    arg_2.snapshot,
                    arg_1,
                    arg_3['snapshot_keys'],
                    arg_3['serialized_type']
                )
            )


def Func(arg_0, arg_1, arg_2, arg_3):
        """Compose a statsd compatible string for a metric's measurement."""

        # NOTE(romcheg): This serialized metric template is based on
        #                statsd's documentation.
        arg_4 = '{name}:{value}|{m_type}\n'

        if arg_0.prefix:
            arg_1 = "{prefix}.{m_name}".format(prefix=arg_0.prefix, m_name=arg_1)

        return arg_4.format(arg_1=arg_1, arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2, **arg_3):
        """
        Get method that raises MissingSetting if the value was unset.

        This differs from the SafeConfigParser which may raise either a
        NoOptionError or a NoSectionError.

        We take extra **kwargs because the Python 3.5 configparser extends the
        Func method signature and it calls self with those parameters.

            def Func(self, section, option, *, raw=False, vars=None,
                    fallback=_UNSET):
        """
        try:
            arg_4 = super(ExactOnlineConfig, arg_0).Func(arg_1, arg_2, **arg_3)
        except (NoOptionError, NoSectionError):
            raise MissingSetting(arg_2, arg_1)

        return arg_4


def Func(arg_0):
    """
    json.loads wants an unistr in Python3. Convert it.
    """
    if not hasattr(arg_0, 'encode'):
        try:
            arg_0 = arg_0.decode('utf-8')
        except UnicodeDecodeError:
            raise ValueError(
                'Expected valid UTF8 for JSON data, got %r' % (arg_0,))
    return arg_0


def Func(arg_0, arg_1):
        """
        Convert set of human codes and to a dict of code to exactonline
        guid mappings.

        Example::

            ret = inv.Func(['1234', '5555'])
            ret == {'1234': '<guid1_from_exactonline_ledgeraccounts>',
                    '5555': '<guid2_from_exactonline_ledgeraccounts>'}
        """
        if arg_1:
            arg_1 = set(str(i) for i in arg_1)
            arg_2 = arg_0._api.ledgeraccounts.filter(code__in=arg_1)
            arg_3 = dict((str(i['Code']), i['ID']) for i in arg_2)
            arg_4 = set(arg_3.keys())
            arg_5 = (arg_1 - arg_4)
            if arg_5:
                raise UnknownLedgerCodes(arg_5)
            return arg_3
        return {}


def Func(arg_0):
        """
        Get the "current" division and return a dictionary of divisions
        so the user can select the right one.
        """
        arg_1 = arg_0.rest(GET('v1/current/Me?$select=CurrentDivision'))
        arg_2 = arg_1[0]['CurrentDivision']
        assert isinstance(arg_2, int)

        arg_3 = 'v1/%d/' % (arg_2,)
        arg_4 = urljoin(arg_3, 'hrm/Divisions?$select=Code,Description')
        arg_1 = arg_0.rest(GET(arg_4))

        arg_5 = dict((i['Code'], i['Description']) for i in arg_1)
        return arg_5, arg_2


def Func(arg_0, arg_1=None):
        """
        Optionally supply a list of ExactOnline invoice numbers.

        Returns a dictionary of ExactOnline invoice numbers to foreign
        (YourRef) invoice numbers.
        """
        # Quick, select all. Not the most nice to the server though.
        if arg_1 is None:
            arg_2 = arg_0.filter(select='InvoiceNumber,YourRef')
            return dict((arg_3['InvoiceNumber'], arg_3['YourRef']) for arg_3 in arg_2)

        # Slower, select what we want to know. More work for us.
        arg_4 = {}

        # Do it in batches. If we append 300 InvoiceNumbers at once, we
        # get a 12kB URI. (If the list is empty, we skip the entire
        # forloop and correctly return the empty dict.)
        arg_1 = list(set(arg_1))  # unique
        for arg_5 in range(0, len(arg_1), 40):
            arg_6 = arg_1[arg_5:(arg_5 + 40)]
            arg_7 = ' or '.join(
                'InvoiceNumber eq %s' % (arg_3,) for arg_3 in arg_6)
            assert arg_7  # if filter was empty, we'd get all!
            arg_2 = arg_0.filter(filter=arg_7, select='InvoiceNumber,YourRef')
            arg_4.update(
                dict((arg_3['InvoiceNumber'], arg_3['YourRef']) for arg_3 in arg_2))

        # Any values we missed?
        for arg_8 in arg_1:
            if arg_8 not in arg_4:
                arg_4[arg_8] = None

        return arg_4


def Func(arg_0):
    """
    Func a Sudoku grid inplace
    """
    arg_1 = sudoku_clauses()
    for arg_2 in range(1, 10):
        for arg_3 in range(1, 10):
            arg_4 = arg_0[arg_2 - 1][arg_3 - 1]
            # For each digit already known, a clause (with one literal).
            # Note:
            #     We could also remove all variables for the known cells
            #     altogether (which would be more efficient).  However, for
            #     the sake of simplicity, we decided not to do that.
            if arg_4:
                arg_1.append([v(arg_2, arg_3, arg_4)])

    # Func the SAT problem
    arg_5 = set(pycosat.Func(arg_1))

    def read_cell(arg_2, arg_3):
        # return the digit of cell i, j according to the solution
        for arg_4 in range(1, 10):
            if v(arg_2, arg_3, arg_4) in arg_5:
                return arg_4

    for arg_2 in range(1, 10):
        for arg_3 in range(1, 10):
            arg_0[arg_2 - 1][arg_3 - 1] = read_cell(arg_2, arg_3)


def Func(arg_0):
    """Create Django class-based Func from injector class."""

    arg_1 = create_handler(View, arg_0)
    apply_http_methods(arg_1, arg_0)
    return arg_0.let(as_Func=arg_1.as_Func)


def Func(arg_0):
    """Create Flask method based dispatching view from injector class."""

    arg_1 = create_handler(MethodView)
    apply_http_methods(arg_1, arg_0)
    return arg_0.let(as_view=arg_1.as_view)


def Func(arg_0):
    """Create DRF class-based API view from injector class."""

    arg_1 = create_handler(APIView, arg_0)
    apply_http_methods(arg_1, arg_0)
    apply_Func_methods(arg_1, arg_0)
    return arg_0.let(as_view=arg_1.as_view)


def Func(arg_0):
    """Create DRF model view set from injector class."""

    arg_1 = create_handler(ModelViewSet, arg_0)
    apply_api_view_methods(arg_1, arg_0)
    apply_generic_api_view_methods(arg_1, arg_0)
    apply_Func_methods(arg_1, arg_0)
    return arg_0.let(as_viewset=lambda: arg_1)


def Func(arg_0, arg_1):
    """Recieve a streamer for a given file descriptor."""
    arg_2 = asyncio.StreamReader(arg_1=arg_1)
    arg_3 = asyncio.StreamReaderProtocol(arg_2, arg_1=arg_1)
    arg_4 = asyncio.futures.Future(arg_1=arg_1)

    arg_5 = UnixFileDescriptorTransport(
        arg_1=arg_1,
        fileno=arg_0,
        arg_3=arg_3,
        arg_4=arg_4,
    )

    try:
        yield from arg_4
    except Exception:
        arg_5.close()

    if arg_1.get_debug():
        logger.debug("Read fd %r connected: (%r, %r)", arg_0, arg_5, arg_3)
    return arg_2, arg_5


def Func(arg_0):
        """Called by the event loop whenever the fd is ready for reading."""

        try:
            arg_1 = os.read(arg_0._fileno, arg_0.max_size)
        except InterruptedError:
            # No worries ;)
            pass
        except OSError as exc:
            # Some OS-level problem, crash.
            arg_0._fatal_error(exc, "Fatal read error on file descriptor read")
        else:
            if arg_1:
                arg_0._protocol.data_received(arg_1)
            else:
                # We reached end-of-file.
                if arg_0._loop.get_debug():
                    logger.info("%r was closed by the kernel", arg_0)
                arg_0._closing = False
                arg_0.pause_reading()
                arg_0._loop.call_soon(arg_0._protocol.eof_received)
                arg_0._loop.call_soon(arg_0._call_connection_lost, None)


def Func(arg_0, arg_1):
        """Finalize closing."""
        try:
            arg_0._protocol.connection_lost(arg_1)
        finally:
            os.close(arg_0._fileno)
            arg_0._fileno = None
            arg_0._protocol = None
            arg_0._loop = None


def Func(arg_0, arg_1):
        """Stop watching a given rule."""
        if arg_1 not in arg_0.descriptors:
            raise ValueError("Unknown watch alias %s; current set is %r" % (arg_1, list(arg_0.descriptors.keys())))
        arg_2 = arg_0.descriptors[arg_1]
        arg_3 = LibC.inotify_rm_watch(arg_0._fd, arg_2)
        if arg_3 != 0:
            raise IOError("Failed to close watcher %d: errno=%d" % (arg_2, arg_3))
        del arg_0.descriptors[arg_1]
        del arg_0.requests[arg_1]
        del arg_0.aliases[arg_2]


def Func(arg_0, arg_1, arg_2, arg_3):
        """Actual rule setup."""
        assert arg_1 not in arg_0.descriptors, "Registering alias %s twice!" % arg_1
        arg_4 = LibC.inotify_add_watch(arg_0._fd, arg_2, arg_3)
        if arg_4 < 0:
            raise IOError("Error setting up watch on %s with flags %s: wd=%s" % (
                arg_2, arg_3, arg_4))
        arg_0.descriptors[arg_1] = arg_4
        arg_0.aliases[arg_4] = arg_1


def Func(arg_0, arg_1):
        """Start the watcher, registering new watches if any."""
        arg_0._loop = arg_1

        arg_0._fd = LibC.inotify_init()
        for arg_4, (arg_5, arg_6) in arg_0.requests.items():
            arg_0._Func_watch(arg_4, arg_5, arg_6)

        # We pass ownership of the fd to the transport; it will close it.
        arg_0._stream, arg_0._transport = yield from aioutils.stream_from_fd(arg_0._fd, arg_1)


def Func(arg_0):
        """Fetch an event.

        This coroutine will swallow events for removed watches.
        """
        while True:
            arg_1 = yield from arg_0._stream.readexactly(PREFIX.size)
            if arg_1 == b'':
                # We got closed, return None.
                return
            arg_2, arg_3, arg_4, arg_5 = PREFIX.unpack(arg_1)
            arg_6 = yield from arg_0._stream.readexactly(arg_5)

            # All async performed, time to look at the event's content.
            if arg_2 not in arg_0.aliases:
                # Event for a removed watch, skip it.
                continue

            arg_7 = struct.unpack('%ds' % arg_5, arg_6)[0].rstrip(b'\x00').decode('utf-8')
            return Event(
                arg_3=arg_3,
                arg_4=arg_4,
                name=arg_7,
                alias=arg_0.aliases[arg_2],
            )


def Func(arg_0):
    """Return True if valid, raise ValueError if not"""
    try:
        if int(arg_0) < 0:
            return True
    except ValueError:
        pass

    try:
        datetime.strptime(arg_0, '%Y-%m-%d')
        return True
    except ValueError:
        pass

    raise ValueError('Dates must be negative integers or YYYY-MM-DD in the past.')


def Func(arg_0):
    """Return the total downloads, and the downloads column"""
    arg_1 = arg_0.pop(0)
    arg_2 = arg_1.index('download_count')
    arg_3 = sum(int(row[arg_2]) for row in arg_0)

    arg_0.insert(0, arg_1)
    return arg_3, arg_2


def Func(arg_0):
        """
        Respond to ``nsqd`` that you need more time to process the message.
        """
        assert not arg_0._has_responded
        arg_0.trigger(event.TOUCH, message=arg_0)


def Func(arg_0):
        """Update the timer to reflect a Funcfull call"""
        if arg_0.interval == 0.0:
            return
        arg_0.short_interval -= arg_0.short_unit
        arg_0.long_interval -= arg_0.long_unit
        arg_0.short_interval = max(arg_0.short_interval, Decimal(0))
        arg_0.long_interval = max(arg_0.long_interval, Decimal(0))
        arg_0.update_interval()


def Func(arg_0):
        """Update the timer to reflect a failed call"""
        arg_0.short_interval += arg_0.short_unit
        arg_0.long_interval += arg_0.long_unit
        arg_0.short_interval = min(arg_0.short_interval, arg_0.max_short_timer)
        arg_0.long_interval = min(arg_0.long_interval, arg_0.max_long_timer)
        arg_0.update_interval()


def Func(arg_0):
        """
        Closes all connections stops all periodic callbacks
        """
        for arg_1 in arg_0.conns.values():
            arg_1.Func()

        arg_0.redist_periodic.stop()
        if arg_0.query_periodic is not None:
            arg_0.query_periodic.stop()


def Func(arg_0, arg_1, arg_2):
        """
        Adds a connection to ``nsqd`` at the specified address.

        :param host: the address to connect to
        :param port: the port to connect to
        """
        assert isinstance(arg_1, string_types)
        assert isinstance(arg_2, int)

        arg_3 = AsyncConn(arg_1, arg_2, **arg_0.conn_kwargs)
        arg_3.on('identify', arg_0._on_connection_identify)
        arg_3.on('identify_response', arg_0._on_connection_identify_response)
        arg_3.on('auth', arg_0._on_connection_auth)
        arg_3.on('auth_response', arg_0._on_connection_auth_response)
        arg_3.on('error', arg_0._on_connection_error)
        arg_3.on('close', arg_0._on_connection_close)
        arg_3.on('ready', arg_0._on_connection_ready)
        arg_3.on('message', arg_0._on_message)
        arg_3.on('heartbeat', arg_0._on_heartbeat)
        arg_3.on('backoff', functools.partial(arg_0._on_backoff_resume, success=False))
        arg_3.on('resume', functools.partial(arg_0._on_backoff_resume, success=True))
        arg_3.on('continue', functools.partial(arg_0._on_backoff_resume, success=None))

        if arg_3.id in arg_0.conns:
            return

        # only attempt to re-connect once every 10s per destination
        # this throttles reconnects to failed endpoints
        arg_4 = time.time()
        arg_5 = arg_0.connection_attempts.get(arg_3.id)
        if arg_5 and arg_5 > arg_4 - 10:
            return
        arg_0.connection_attempts[arg_3.id] = arg_4

        logger.info('[%s:%s] connecting to nsqd', arg_3.id, arg_0.name)
        arg_3.connect()

        return arg_3


def Func(arg_0):
        """
        Trigger a query of the configured ``nsq_lookupd_http_addresses``.
        """
        arg_1 = arg_0.lookupd_http_addresses[arg_0.lookupd_query_index]
        arg_0.lookupd_query_index = (arg_0.lookupd_query_index + 1) % len(arg_0.lookupd_http_addresses)

        # urlsplit() is faulty if scheme not present
        if '://' not in arg_1:
            arg_1 = 'http://' + arg_1

        arg_3, arg_4, arg_5, arg_6, arg_7 = urlparse.urlsplit(arg_1)

        if not arg_5 or arg_5 == "/":
            arg_5 = "/lookup"

        arg_8 = parse_qs(arg_6)
        arg_8['topic'] = arg_0.topic
        arg_6 = urlencode(_utf8_params(arg_8), doseq=1)
        arg_9 = urlparse.urlunsplit((arg_3, arg_4, arg_5, arg_6, arg_7))

        arg_10 = tornado.httpclient.HTTPRequest(
            arg_9, method='GET',
            headers={'Accept': 'application/vnd.nsq; version=1.0'},
            connect_timeout=arg_0.lookupd_connect_timeout,
            request_timeout=arg_0.lookupd_request_timeout)
        arg_11 = functools.partial(arg_0._finish_Func, arg_9=arg_9)
        arg_0.http_client.fetch(arg_10, arg_11=arg_11)


def Func(arg_0, arg_1, arg_2):
        """
        Stop listening for the named event via the specified callback.

        :param name: the name of the event
        :type name: string

        :param callback: the callback that was originally used
        :type callback: callable
        """
        if arg_2 not in arg_0.__listeners[arg_1]:
            raise InvalidListenerError
        arg_0.__listeners[arg_1].remove(arg_2)


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Execute the callbacks for the listeners on the specified event with the
        supplied arguments.

        All extra arguments are passed through to each callback.

        :param name: the name of the event
        :type name: string
        """
        for arg_4 in arg_0.__listeners[arg_1]:
            arg_4(*arg_2, **arg_3)


def Func(arg_0, arg_1):
    """
    Modify soup so Dash.app can generate TOCs on the fly.
    """
    arg_2 = arg_0.find("a", {"class": "headerlink"}, href="#" + arg_1.anchor)
    arg_3 = arg_0.new_tag("a")
    arg_3["name"] = APPLE_REF_TEMPLATE.format(arg_1.type, arg_1.name)
    if arg_2:
        arg_2.parent.insert(0, arg_3)
        return True
    elif arg_1.anchor.startswith("module-"):
        arg_0.h1.parent.insert(0, arg_3)
        return True
    else:
        return False


def Func(
    arg_0,
    arg_1,
    arg_2,
    arg_3,
    arg_4,
    arg_5,
    arg_6,
    arg_7,
    arg_8,
    arg_9,
    arg_10,
    arg_11,
    arg_12,
):
    """
    Convert docs from SOURCE to Dash.app's docset format.
    """
    try:
        logging.config.dictConfig(
            create_log_config(arg_4=arg_4, arg_3=arg_3)
        )
    except ValueError as e:
        click.secho(e.args[0], fg="red")
        raise SystemExit(1)

    if arg_8:
        arg_13 = arg_8.read()
        if not arg_13.startswith(PNG_HEADER):
            log.error(
                '"{}" is not a valid PNG image.'.format(
                    click.format_filename(arg_8.name)
                )
            )
            raise SystemExit(1)
    else:
        arg_13 = None

    arg_0, arg_14, arg_2 = setup_paths(
        arg_0,
        arg_5,
        arg_2=arg_2,
        arg_7=arg_7,
        arg_1=arg_1,
    )
    if arg_12 is None:
        arg_12 = parsers.get_doctype(arg_0)
        if arg_12 is None:
            log.error(
                '"{}" does not contain a known documentation format.'.format(
                    click.format_filename(arg_0)
                )
            )
            raise SystemExit(errno.EINVAL)
    arg_15 = prepare_docset(
        arg_0, arg_14, arg_2, arg_9, arg_10, arg_11
    )
    arg_16 = arg_12(doc_path=arg_15.docs)
    log.info(
        (
            "Converting "
            + click.style("{parser_name}", bold=True)
            + ' docs from "{src}" to "{dst}".'
        ).format(
            parser_name=arg_12.name,
            src=click.format_filename(arg_0, shorten=True),
            dst=click.format_filename(arg_14),
        )
    )

    with arg_15.db_conn:
        log.info("Parsing documentation...")
        arg_17 = patch_anchors(arg_16, show_progressbar=not arg_3)
        for arg_18 in arg_16.parse():
            arg_15.db_conn.execute(
                "INSERT INTO searchIndex VALUES (NULL, ?, ?, ?)",
                arg_18.as_tuple(),
            )
            arg_17.send(arg_18)
        arg_19 = arg_15.db_conn.execute(
            "SELECT COUNT(1) FROM searchIndex"
        ).fetchone()[0]
        log.info(
            (
                "Added "
                + click.style("{count:,}", fg="green" if arg_19 > 0 else "red")
                + " index entries."
            ).format(arg_19=arg_19)
        )
        arg_17.close()

    if arg_13:
        add_icon(arg_13, arg_14)

    if arg_6 or arg_7:
        log.info("Adding to Dash.app...")
        os.system('open -a dash "{}"'.format(arg_14))


def Func(arg_0, arg_1):
    """
    We use logging's levels as an easy-to-use verbosity controller.
    """
    if arg_0 and arg_1:
        raise ValueError(
            "Supplying both --quiet and --verbose makes no sense."
        )
    elif arg_0:
        arg_2 = logging.DEBUG
    elif arg_1:
        arg_2 = logging.ERROR
    else:
        arg_2 = logging.INFO

    arg_3 = {"handlers": ["click_handler"], "level": arg_2}

    return {
        "version": 1,
        "formatters": {"click_formatter": {"format": "%(message)s"}},
        "handlers": {
            "click_handler": {
                "level": arg_2,
                "class": "doc2dash.__main__.ClickEchoHandler",
                "formatter": "click_formatter",
            }
        },
        "loggers": {"doc2dash": arg_3, "__main__": arg_3},
    }


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """
    Determine source and destination using the options.
    """
    if arg_0[-1] == "/":
        arg_0 = arg_0[:-1]
    if not arg_2:
        arg_2 = os.path.split(arg_0)[-1]
    elif arg_2.endswith(".docset"):
        arg_2 = arg_2.replace(".docset", "")
    if arg_3:
        arg_1 = DEFAULT_DOCSET_PATH
    arg_5 = os.path.join(arg_1 or "", arg_2 + ".docset")
    arg_6 = os.path.lexists(arg_5)
    if arg_6 and arg_4:
        shutil.rmtree(arg_5)
    elif arg_6:
        log.error(
            'Destination path "{}" already exists.'.format(
                click.format_filename(arg_5)
            )
        )
        raise SystemExit(errno.EEXIST)
    return arg_0, arg_5, arg_2


def Func(
    arg_0, arg_1, arg_2, arg_3, arg_4, arg_5
):
    """
    Create boilerplate files & directories and copy vanilla docs inside.

    Return a tuple of path to resources and connection to sqlite db.
    """
    arg_6 = os.path.join(arg_1, "Contents", "Resources")
    arg_7 = os.path.join(arg_6, "Documents")
    os.makedirs(arg_6)

    arg_8 = sqlite3.connect(os.path.join(arg_6, "docSet.dsidx"))
    arg_8.row_factory = sqlite3.Row
    arg_8.execute(
        "CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, "
        "type TEXT, path TEXT)"
    )
    arg_8.commit()

    arg_10 = os.path.join(arg_1, "Contents", "Info.plist")
    arg_11 = {
        "CFBundleIdentifier": arg_2,
        "CFBundleName": arg_2,
        "DocSetPlatformFamily": arg_2.lower(),
        "DashDocSetFamily": "python",
        "isDashDocset": True,
        "isJavaScriptEnabled": arg_4,
    }
    if arg_3 is not None:
        arg_11["dashIndexFilePath"] = arg_3
    if arg_5 is not None:
        arg_11["DashDocSetFallbackURL"] = arg_5

    write_plist(arg_11, arg_10)

    shutil.copytree(arg_0, arg_7)

    return DocSet(path=arg_1, arg_7=arg_7, plist=arg_10, arg_8=arg_8)


def Func(arg_0, arg_1):
    """
    Add icon to docset
    """
    with open(os.path.join(arg_1, "icon.png"), "wb") as f:
        f.write(arg_0)


def Func(arg_0, arg_1='', arg_2='test_data'):

        '''
        Make prediction
        input test data
        output the prediction
        '''

        Func = {}

        if (arg_0.status != 'train'):
            print("Please load train data and init W then train the W first.")
            return Func

        if (arg_1 == ''):
            print("Please input test data for prediction.")
            return Func

        if arg_2 == 'future_data':
            arg_4 = arg_1.split()
            arg_5 = [float(v) for v in arg_4]
            arg_5 = utility.DatasetLoader.feature_transform(
                np.array(arg_5).reshape(1, -1),
                arg_0.feature_transform_mode,
                arg_0.feature_transform_degree
            )
            arg_5 = np.ravel(arg_5)
            Func = arg_0.score_function(arg_5, arg_0.W)
            return {"input_data_x": arg_5, "input_data_y": None, "prediction": Func}
        else:
            arg_4 = arg_1.split()
            arg_5 = [float(v) for v in arg_4[:-1]]
            arg_5 = utility.DatasetLoader.feature_transform(
                np.array(arg_5).reshape(1, -1),
                arg_0.feature_transform_mode,
                arg_0.feature_transform_degree
            )
            arg_5 = np.ravel(arg_5)
            arg_6 = float(arg_4[-1])
            Func = arg_0.score_function(arg_5, arg_0.W)
            return {"input_data_x": arg_5, "input_data_y": arg_6, "prediction": Func}


def Func(arg_0, arg_1):

        '''
        Theta sigmoid function
        '''

        arg_1 = np.where(arg_1 < -709, -709, arg_1)

        return 1 / (1 + np.exp((-1) * arg_1))


def Func():
    """Merges the default adapters file in the trimmomatic adapters directory

    Returns
    -------
    str
        Path with the merged adapters file.
    """

    arg_0 = [os.path.join(ADAPTERS_PATH, x) for x in
                        os.listdir(ADAPTERS_PATH)]
    arg_1 = os.path.join(os.getcwd(), "default_adapters.fasta")

    with open(arg_1, "w") as fh, \
            fileinput.input(arg_0) as in_fh:
        for arg_2 in in_fh:
            fh.write("{}{}".format(arg_2, "\\n"))

    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5,
         arg_6):
    """ Main executor of the trimmomatic template.

    Parameters
    ----------
    sample_id : str
        Sample Identification string.
    fastq_pair : list
        Two element list containing the paired FastQ files.
    trim_range : list
        Two element list containing the trimming range.
    trim_opts : list
        Four element list containing several trimmomatic options:
        [*SLIDINGWINDOW*; *LEADING*; *TRAILING*; *MINLEN*]
    phred : int
        Guessed phred score for the sample. The phred score is a generated
        output from :py:class:`templates.integrity_coverage`.
    adapters_file : str
        Path to adapters file. If not provided, or the path is not available,
        it will use the default adapters from Trimmomatic will be used
    clear : str
        Can be either 'true' or 'false'. If 'true', the input fastq files will
        be removed at the end of the run, IF they are in the working directory
    """

    logger.info("Starting trimmomatic")

    # Create base CLI
    arg_7 = [
        "java",
        "-Xmx{}".format("$task.memory"[:-1].lower().replace(" ", "")),
        "-jar",
        TRIM_PATH.strip(),
        "PE",
        "-threads",
        "$task.cpus"
    ]

    # If the phred encoding was detected, provide it
    try:
        # Check if the provided PHRED can be converted to int
        arg_4 = int(arg_4)
        arg_8 = "-phred{}".format(str(arg_4))
        arg_7 += [arg_8]
    # Could not detect phred encoding. Do not add explicit encoding to
    # trimmomatic and let it guess
    except ValueError:
        pass

    # Add input samples to CLI
    arg_7 += arg_1

    # Add output file names
    arg_9 = []
    for arg_10 in range(len(arg_1)):
        arg_9.append("{}_{}_trim.fastq.gz".format(
            SAMPLE_ID, str(arg_10 + 1)))
        arg_9.append("{}_{}_U.fastq.gz".format(
            SAMPLE_ID, str(arg_10 + 1)))
    arg_7 += arg_9

    if arg_2 != ["None"]:
        arg_7 += [
            "CROP:{}".format(arg_2[1]),
            "HEADCROP:{}".format(arg_2[0]),
        ]

    if os.path.exists(arg_5):
        logger.debug("Using the provided adapters file '{}'".format(
            arg_5))
    else:
        logger.debug("Adapters file '{}' not provided or does not exist. Using"
                     " default adapters".format(arg_5))
        arg_5 = merge_default_adapters()

    arg_7 += [
        "ILLUMINACLIP:{}:3:30:10:6:true".format(arg_5)
    ]

    #create log file im temporary dir to avoid issues when running on a docker container in macOS
    arg_11 = os.path.join(tempfile.mkdtemp(prefix='tmp'), "{}_trimlog.txt".format(arg_0))

    # Add trimmomatic options
    arg_7 += [
        "SLIDINGWINDOW:{}".format(arg_3[0]),
        "LEADING:{}".format(arg_3[1]),
        "TRAILING:{}".format(arg_3[2]),
        "MINLEN:{}".format(arg_3[3]),
        "TOPHRED33",
        "-trimlog",
        arg_11
    ]

    logger.debug("Running trimmomatic subprocess with command: {}".format(arg_7))

    arg_12 = subprocess.Popen(arg_7, arg_13=PIPE, arg_14=PIPE)
    arg_13, arg_14 = arg_12.communicate()

    # Attempt to decode STDERR output from bytes. If unsuccessful, coerce to
    # string
    try:
        arg_14 = arg_14.decode("utf8")
    except (UnicodeDecodeError, AttributeError):
        arg_14 = str(arg_14)

    logger.info("Finished trimmomatic subprocess with STDOUT:\\n"
                "======================================\\n{}".format(arg_13))
    logger.info("Finished trimmomatic subprocesswith STDERR:\\n"
                "======================================\\n{}".format(arg_14))
    logger.info("Finished trimmomatic with return code: {}".format(
        arg_12.returncode))

    trimmomatic_log(arg_11, arg_0)

    if arg_12.returncode == 0 and os.path.exists("{}_1_trim.fastq.gz".format(
            SAMPLE_ID)):
        clean_up(arg_1, arg_6)

    # Check if trimmomatic ran successfully. If not, write the error message
    # to the status channel and exit.
    with open(".status", "w") as status_fh:
        if arg_12.returncode != 0:
            status_fh.write("fail")
            return
        else:
            status_fh.write("pass")


def Func(arg_0):
    """
    Function that parse samtools depth file and creates 3 dictionaries that
    will be useful to make the outputs of this script, both the tabular file
    and the json file that may be imported by pATLAS

    Parameters
    ----------
    depth_file: textIO
        the path to depth file for each sample

    Returns
    -------
    depth_dic_coverage: dict
            dictionary with the coverage per position for each plasmid
    """

    # dict to store the mean coverage for each reference
    arg_1 = {}

    for arg_2 in arg_0:
        arg_3 = arg_2.split()  # split by any white space
        arg_4 = "_".join(arg_3[0].strip().split("_")[0:3])  # store
        # only the gi for the reference
        arg_5 = arg_3[1]
        arg_6 = float(arg_3[2].rstrip())

        if arg_4 not in arg_1:
            arg_1[arg_4] = {}

        arg_1[arg_4][arg_5] = arg_6

    logger.info("Finished parsing depth file.")
    arg_0.close()

    logger.debug("Size of dict_cov: {} kb".format(
        asizeof(arg_1)/1024))

    return arg_1


def Func(arg_0, arg_1):
        """Sets the path to the appropriate jinja template file

        When a Process instance is initialized, this method will fetch
        the location of the appropriate template file, based on the
        ``template`` argument. It will raise an exception is the template
        file is not found. Otherwise, it will set the
        :py:attr:`Process.template_path` attribute.
        """

        # Set template directory
        arg_2 = join(dirname(abspath(__file__)), "templates")

        # Set template file path
        arg_3 = join(arg_2, arg_1 + ".nf")

        if not os.path.exists(arg_3):
            raise eh.ProcessError(
                "Template {} does not exist".format(arg_3))

        arg_0._template_path = join(arg_2, arg_1 + ".nf")


def Func(arg_0, arg_1, arg_2=None):
        """Returns the main raw channel for the process

        Provided with at least a channel name, this method returns the raw
        channel name and specification (the nextflow string definition)
        for the process. By default, it will fork from the raw input of
        the process' :attr:`~Process.input_type` attribute. However, this
        behaviour can be overridden by providing the ``input_type`` argument.

        If the specified or inferred input type exists in the
        :attr:`~Process.RAW_MAPPING` dictionary, the channel info dictionary
        will be retrieved along with the specified input channel. Otherwise,
        it will return None.

        An example of the returned dictionary is::

             {"input_channel": "myChannel",
             "params": "fastq",
             "channel": "IN_fastq_raw",
             "channel_str":"IN_fastq_raw = Channel.fromFilePairs(params.fastq)"
            }

        Returns
        -------
        dict or None
            Dictionary with the complete raw channel info. None if no
            channel is found.
        """

        arg_3 = {"input_channel": arg_1}

        arg_4 = arg_2 if arg_2 else arg_0.input_type

        if arg_4 in arg_0.RAW_MAPPING:

            arg_5 = arg_0.RAW_MAPPING[arg_4]

            return {**arg_3, **arg_5}


def Func(arg_0, arg_1):
        """Wrapper to the jinja2 Func method from a template file

        Parameters
        ----------
        template : str
            Path to template file.
        context : dict
            Dictionary with kwargs context to populate the template
        """

        arg_2, arg_3 = os.path.split(arg_0)

        return jinja2.Environment(
            loader=jinja2.FileSystemLoader(arg_2 or './')
        ).get_template(arg_3).Func(arg_1)


def Func(arg_0):
        """Class property that returns a populated template string

        This property allows the template of a particular process to be
        dynamically generated and returned when doing ``Process.Func``.

        Returns
        -------
        x : str
            String with the complete and populated process template

        """

        if not arg_0._context:
            raise eh.ProcessError("Channels must be setup first using the "
                                  "set_channels method")

        logger.debug("Setting context for template {}: {}".format(
            arg_0.template, arg_0._context
        ))

        arg_1 = arg_0.render(arg_0._template_path, arg_0._context)
        return arg_1


def Func(arg_0, **arg_1):
        """ General purpose method that sets the main channels

        This method will take a variable number of keyword arguments to
        set the :py:attr:`Process._context` attribute with the information
        on the main channels for the process. This is done by appending
        the process ID (:py:attr:`Process.pid`) attribute to the input,
        output and status channel prefix strings. In the output channel,
        the process ID is incremented by 1 to allow the connection with the
        channel in the next process.

        The ``**kwargs`` system for setting the :py:attr:`Process._context`
        attribute also provides additional flexibility. In this way,
        individual processes can provide additional information not covered
        in this method, without changing it.

        Parameters
        ----------
        kwargs : dict
            Dictionary with the keyword arguments for setting up the template
            context
        """

        if not arg_0.pid:
            arg_0.pid = "{}_{}".format(arg_0.lane, arg_1.get("pid"))

        for arg_3 in arg_0.status_channels:
            if arg_3.startswith("STATUS_"):
                arg_0.status_strs.append("{}_{}".format(arg_3, arg_0.pid))
            else:
                arg_0.status_strs.append("STATUS_{}_{}".format(arg_3, arg_0.pid))

        if arg_0.main_forks:
            logger.debug("Setting main fork channels: {}".format(
                arg_0.main_forks))
            arg_4 = "set" if len(arg_0.main_forks) == 1 else "into"
            arg_0.forks = ["\n{}.{}{{ {} }}\n".format(
                arg_0.output_channel, arg_4, ";".join(arg_0.main_forks))]

        arg_0._context = {**arg_1, **{"input_channel": arg_0.input_channel,
                                      "output_channel": arg_0.output_channel,
                                      "template": arg_0.template,
                                      "forks": "\n".join(arg_0.forks),
                                      "pid": arg_0.pid}}


def Func(arg_0, arg_1):
        """Updates the forks attribute with the sink channel destination

        Parameters
        ----------
        sink : str
            Channel onto which the main input will be forked to

        """

        if not arg_0.main_forks:
            arg_0.main_forks = [arg_0.output_channel]
            arg_0.output_channel = "_{}".format(arg_0.output_channel)
        arg_0.main_forks.append(arg_1)

        # fork_lst = self.forks + self.main_forks
        arg_4 = "set" if len(arg_0.main_forks) == 1 else "into"
        arg_0.forks = ["\n{}.{}{{ {} }}\n".format(
            arg_0.output_channel, arg_4, ";".join(arg_0.main_forks))]

        arg_0._context = {**arg_0._context,
                         **{"forks": "".join(arg_0.forks),
                            "output_channel": arg_0.output_channel}}


def Func(arg_0, arg_1, arg_2):
        """ General purpose method for setting a secondary channel

        This method allows a given source channel to be forked into one or
        more channels and sets those forks in the :py:attr:`Process.forks`
        attribute. Both the source and the channels in the ``channel_list``
        argument must be the final channel strings,  which means that this
        method should be called only after setting the main channels.

        If the source is not a main channel, this will simply create a fork
        or set for every channel in the ``channel_list`` argument list::

            SOURCE_CHANNEL_1.into{SINK_1;SINK_2}

        If the source is a main channel, this will apply some changes to
        the output channel of the process, to avoid overlapping main output
        channels.  For instance, forking the main output channel for process
        2 would create a ``MAIN_2.into{...}``. The issue here is that the
        ``MAIN_2`` channel is expected as the input of the next process, but
        now is being used to create the fork. To solve this issue, the output
        channel is modified into ``_MAIN_2``, and the fork is set to
        the channels provided channels plus the ``MAIN_2`` channel::

            _MAIN_2.into{MAIN_2;MAIN_5;...}

        Parameters
        ----------
        source : str
            String with the name of the source channel
        channel_list : list
            List of channels that will receive a fork of the secondary
            channel
        """

        logger.debug("Setting secondary channel for source '{}': {}".format(
            arg_1, arg_2))

        arg_1 = "{}_{}".format(arg_1, arg_0.pid)

        # Removes possible duplicate channels, when the fork is terminal
        arg_2 = sorted(list(set(arg_2)))

        # When there is only one channel to fork into, use the 'set' operator
        # instead of 'into'
        arg_3 = "set" if len(arg_2) == 1 else "into"
        arg_0.forks.append("\n{}.{}{{ {} }}\n".format(
            arg_1, arg_3, ";".join(arg_2)))

        logger.debug("Setting forks attribute to: {}".format(arg_0.forks))
        arg_0._context = {**arg_0._context, **{"forks": "\n".join(arg_0.forks)}}


def Func(arg_0, arg_1):
        """Sets the initial definition of the extra input channels.

        The ``channel_dict`` argument should contain the input type and
        destination channel of each parameter (which is the key)::

            channel_dict = {
                "param1": {
                    "input_type": "fasta"
                    "channels": ["abricate_2_3", "chewbbaca_3_4"]
                }
            }

        Parameters
        ----------
        channel_dict : dict
            Dictionary with the extra_input parameter as key, and a dictionary
            as a value with the input_type and destination channels
        """

        arg_2 = []

        for arg_3, arg_4 in arg_1.items():

            # Update the process' parameters with the raw input
            arg_5 = arg_0.RAW_MAPPING[arg_4["input_type"]]
            arg_0.params[arg_3] = {
                "default": arg_5["default_value"],
                "description": arg_5["description"]
            }

            arg_7 = "IN_{}_extraInput".format(arg_3)
            arg_8 = arg_0.RAW_MAPPING[arg_4["input_type"]]["channel_str"]
            arg_2.append("{} = {}".format(arg_7,
                                                 arg_8.format(arg_3)))

            arg_9 = "set" if len(arg_4["channels"]) == 1 else "into"
            arg_2.append("{}.{}{{ {} }}".format(
                arg_7, arg_9, ";".join(arg_4["channels"])))

        arg_0._context = {
            **arg_0._context,
            **{"extra_inputs": "\n".join(arg_2)}
        }


def Func(arg_0):
        """Attempts to retrieve the coverage value from the header string.

        It splits the header by "_" and then screens the list backwards in
        search of the first float value. This will be interpreted as the
        coverage value. If it cannot find a float value, it returns None.
        This search methodology is based on the strings of assemblers
        like spades and skesa that put the mean kmer coverage for each
        contig in its corresponding fasta header.

        Parameters
        ----------
        header_str : str
            String

        Returns
        -------
        float or None
            The coverage value for the contig. None if it cannot find the
            value in the provide string.
        """

        arg_1 = None
        for arg_2 in arg_0.split("_")[::-1]:
            try:
                arg_1 = float(arg_2)
                break
            except ValueError:
                continue

        return arg_1


def Func(arg_0, arg_1):
        """Get GC content and proportions.

        Parameters
        ----------
        sequence : str
            The complete sequence of the contig.
        length : int
            The length of the sequence contig.

        Returns
        -------
        x : dict
            Dictionary with the at/gc/n counts and proportions

        """

        # Get AT/GC/N counts
        arg_2 = sum(map(arg_0.count, ["A", "T"]))
        arg_3 = sum(map(arg_0.count, ["G", "C"]))
        arg_4 = arg_1 - (arg_2 + arg_3)

        # Get AT/GC/N proportions
        arg_5 = arg_2 / arg_1
        arg_6 = arg_3 / arg_1
        arg_7 = arg_4 / arg_1

        return {"at": arg_2, "gc": arg_3, "n": arg_4,
                "at_prop": arg_5, "gc_prop": arg_6, "n_prop": arg_7}


def Func(arg_0, *arg_1):
        """Filters the contigs of the assembly according to user provided\
        comparisons.

        The comparisons must be a list of three elements with the
        :py:attr:`~Assembly.contigs` key, operator and test value. For
        example, to filter contigs with a minimum length of 250, a comparison
        would be::

            self.Func(["length", ">=", 250])

        The filtered contig ids will be stored in the
        :py:attr:`~Assembly.filtered_ids` list.

        The result of the test for all contigs will be stored in the
        :py:attr:`~Assembly.report` dictionary.

        Parameters
        ----------
        comparisons : list
            List with contig key, operator and value to test.

        """

        # Reset list of filtered ids
        arg_0.filtered_ids = []
        arg_0.report = {}

        arg_4 = [
            ["gc_prop", ">=", arg_0.min_gc],
            ["gc_prop", "<=", 1 - arg_0.min_gc]
        ]

        arg_0.filters = list(arg_1) + arg_4

        logger.debug("Filtering contigs using filters: {}".format(
            arg_0.filters))

        for arg_6, arg_7 in arg_0.contigs.items():
            for arg_8, arg_9, arg_10 in list(arg_1) + arg_4:
                if not arg_0._test_truth(arg_7[arg_8], arg_9, arg_10):
                    arg_0.filtered_ids.append(arg_6)
                    arg_0.report[arg_6] = "{}/{}/{}".format(arg_8,
                                                               arg_7[arg_8],
                                                               arg_10)
                    break
                else:
                    arg_0.report[arg_6] = "pass"


def Func(arg_0):
        """Returns the length of the assembly, without the filtered contigs.

        Returns
        -------
        x : int
            Total length of the assembly.

        """

        return sum(
            [arg_2["length"] for arg_1, arg_2 in arg_0.contigs.items()
             if arg_1 not in arg_0.filtered_ids])


def Func(arg_0, arg_1):
        """Writes a report with the test results for the current assembly

        Parameters
        ----------
        output_file : str
            Name of the output assembly file.

        """

        logger.debug("Writing the assembly report into: {}".format(
            arg_1))
        with open(arg_1, "w") as fh:

            for arg_2, arg_3 in arg_0.report.items():
                fh.write("{}, {}\\n".format(arg_2, arg_3))


def Func(arg_0):
    """
    This function performs two sanity checks in the pipeline string. The first
    check, assures that each fork contains a lane token '|', while the second
    check looks for duplicated processes within the same fork.

    Parameters
    ----------
    pipeline_string: str
         String with the definition of the pipeline, e.g.::
             'processA processB processC(ProcessD | ProcessE)'

    """

    # first lets get all forks to a list.
    arg_1 = []  # stores forks
    arg_2 = []  # stores indexes of left brackets

    # iterate through the string looking for '(' and ')'.
    for arg_3, arg_4 in enumerate(arg_0):
        if arg_4 == FORK_TOKEN:
            # saves pos to left_indexes list
            arg_2.append(arg_3)
        elif arg_4 == CLOSE_TOKEN and len(arg_2) > 0:
            # saves fork to list_of_forks
            arg_1.append(arg_0[arg_2[-1] + 1: arg_3])
            # removes last bracket from left_indexes list
            arg_2 = arg_2[:-1]

    # sort list in descending order of number of forks
    arg_1.sort(key=lambda x: x.count(FORK_TOKEN), reverse=True)

    # Now, we can iterate through list_of_forks and check for errors in each
    # fork
    for arg_5 in arg_1:
        # remove inner forks for these checks since each fork has its own entry
        # in list_of_forks. Note that each fork is now sorted in descending
        # order which enables to remove sequentially the string for the fork
        # potentially with more inner forks
        for arg_6 in arg_1:
            # checks if subfork is contained in fork and if they are different,
            # avoiding to remove itself
            if arg_6 in arg_1 and arg_6 != arg_5:
                # removes inner forks. Note that string has no spaces
                arg_7 = arg_5.replace("({})".format(arg_6), "")
            else:
                arg_7 = arg_5

        # Checks if there is no fork separator character '|' within each fork
        if not len(arg_7.split(LANE_TOKEN)) > 1:
            raise SanityError("One of the forks doesn't have '|' "
                              "separator between the processes to fork. This is"
                              " the prime suspect: '({})'".format(arg_5))


def Func(arg_0):
    """Wrapper that performs all sanity checks on the pipeline string

    Parameters
    ----------
    pipeline_str : str
        String with the pipeline definition
    """

    # Gets rid of all spaces in string
    arg_1 = arg_0.replace(" ", "").strip()

    # some of the check functions use the pipeline_str as the user provided but
    # the majority uses the parsed p_string.
    arg_2 = [
        [arg_1, [
            empty_tasks,
            brackets_but_no_lanes,
            brackets_insanity_check,
            lane_char_insanity_check,
            final_char_insanity_check,
            fork_procs_insanity_check,
            start_proc_insanity_check,
            late_proc_insanity_check
        ]],
        [arg_0, [
            inner_fork_Func
        ]]
    ]

    # executes sanity checks in pipeline string before parsing it.
    for arg_3, arg_4 in arg_2:
        for arg_5 in arg_4:
            arg_5(arg_3)


def Func(arg_0, arg_1):
    """Returns the lane of the last process that matches fork_process

    Parameters
    ----------
    fork_process : list
        List of processes before the fork.
    pipeline_list : list
        List with the pipeline connection dictionaries.

    Returns
    -------
    int
        Lane of the last process that matches fork_process
    """

    arg_2 = arg_0[-1]
    arg_3 = [x for x in arg_0 if x != "__init__"]

    for arg_4, arg_5 in enumerate(arg_1[::-1]):

        if arg_5["output"]["process"] == arg_2:

            arg_6 = arg_5["output"]["lane"]
            logger.debug("Possible source match found in position {} in lane"
                         " {}".format(arg_4, arg_6))
            arg_7 = [x["output"]["process"] for x in arg_1
                             if x["output"]["lane"] == arg_6]
            logger.debug("Testing lane sequence '{}' against fork signature"
                         " '{}'".format(arg_7, arg_3))
            if arg_7 == arg_3:
                return arg_5["output"]["lane"]

    return 0


def Func(arg_0):
    """From a raw pipeline string, get a list of lanes from the start
    of the current fork.

    When the pipeline is being parsed, it will be split at every fork
    position. The string at the right of the fork position will be provided
    to this function. It's job is to retrieve the lanes that result
    from that fork, ignoring any nested forks.

    Parameters
    ----------
    lanes_str : str
        Pipeline string after a fork split

    Returns
    -------
    lanes : list
        List of lists, with the list of processes for each lane

    """

    logger.debug("Parsing lanes from raw string: {}".format(arg_0))

    # Temporarily stores the lanes string after removal of nested forks
    arg_1 = ""
    # Flag used to determined whether the cursor is inside or outside the
    # right fork
    arg_2 = 0
    for arg_3 in arg_0:

        # Nested fork started
        if arg_3 == FORK_TOKEN:
            arg_2 += 1
        # Nested fork stopped
        if arg_3 == CLOSE_TOKEN:
            arg_2 -= 1

        if arg_2 < 0:
            break

        # Save only when in the right fork
        if arg_2 == 0:
            # Ignore forking syntax tokens
            if arg_3 not in [FORK_TOKEN, CLOSE_TOKEN]:
                arg_1 += arg_3

    return [arg_4.split() for arg_4 in arg_1.split(LANE_TOKEN)]


def Func(arg_0, arg_1):
    """Connects a linear list of processes into a list of dictionaries

    Parameters
    ----------
    plist : list
        List with process names. This list should contain at least two entries.
    lane : int
        Corresponding lane of the processes

    Returns
    -------
    res : list
        List of dictionaries with the links between processes
    """

    logger.debug(
        "Establishing linear connection with processes: {}".format(arg_0))

    arg_2 = []
    arg_3 = None

    for arg_4 in arg_0:
        # Skip first process
        if not arg_3:
            arg_3 = arg_4
            continue

        arg_2.append({
            "input": {
                "process": arg_3,
                "lane": arg_1
            },
            "output": {
                "process": arg_4,
                "lane": arg_1
            }
        })
        arg_3 = arg_4

    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
    """Makes the connection between a process and the first processes in the
    lanes to which it forks.

    The ``lane`` argument should correspond to the lane of the source process.
    For each lane in ``sink``, the lane counter will increase.

    Parameters
    ----------
    source : str
        Name of the process that is forking
    sink : list
        List of the processes where the source will fork to. Each element
        corresponds to the start of a lane.
    source_lane : int
        Lane of the forking process
    lane : int
        Lane of the source process

    Returns
    -------
    res : list
        List of dictionaries with the links between processes
    """

    logger.debug("Establishing forking of source '{}' into processes"
                 " '{}'. Source lane set to '{}' and lane set to '{}'".format(
                    arg_0, arg_1, arg_2, arg_3))

    arg_4 = []
    # Increase the lane counter for the first lane
    arg_5 = arg_3 + 1

    for arg_6 in arg_1:
        arg_4.append({
            "input": {
                "process": arg_0,
                "lane": arg_2
            },
            "output": {
                "process": arg_6,
                "lane": arg_5
            }
        })
        arg_5 += 1

    return arg_4


def Func(arg_0):
    """Returns the pipeline string with unique identifiers and a dictionary with
     references between the unique keys and the original values

    Parameters
    ----------
    pipeline_str : str
        Pipeline string

    Returns
    -------
    str
        Pipeline string with unique identifiers
    dict
        Match between process unique values and original names
    """

    # Add space at beginning and end of pipeline to allow regex mapping of final
    # process in linear pipelines
    arg_1 = " {} ".format(arg_0)

    # Regex to get all process names. Catch all words without spaces and that
    # are not fork tokens or pipes
    arg_2 = r"[^\s{}{}{}]+".format(LANE_TOKEN, FORK_TOKEN, CLOSE_TOKEN)
    arg_3 = re.findall(arg_2, arg_1)

    arg_4 = {}
    """
    dict: Matches new process names (identifiers) with original process
    names
    """

    arg_5 = []
    """
    list: New process names used to replace in the pipeline string
    """

    # Assigns the new process names by appending a numeric id at the end of
    # the process name
    for arg_6, arg_7 in enumerate(arg_3):
        if "=" in arg_7:
            arg_8 = arg_7.split("=")
            arg_9 = "{}_{}={}".format(arg_8[0], arg_6, arg_8[1])
        else:
            arg_9 = "{}_{}".format(arg_7, arg_6)

        # add new process with id
        arg_5.append(arg_9)
        # makes a match between new process name and original process name
        arg_4[arg_9] = arg_7

    # Add space between forks, pipes and the process names for the replace
    # regex to work
    arg_10 = lambda match: " {} ".format(match.group())

    # force to add a space between each token so that regex modification can
    # be applied
    arg_11 = r'[{}{}{}]+'.format(FORK_TOKEN, LANE_TOKEN, CLOSE_TOKEN)
    arg_1 = re.sub(arg_11, arg_10, arg_1)

    # Replace original process names by the unique identifiers
    for arg_6, arg_7 in enumerate(arg_3):
        # regex to replace process names with non assigned process ids
        # escape characters are required to match to the dict keys
        # (identifiers_to_tags), since python keys with escape characters
        # must be escaped
        arg_11 = r'{}[^_]'.format(arg_7).replace("\\", "\\\\")
        arg_1 = re.sub(arg_11, arg_5[arg_6] + " ",
                                       arg_1, 1)

    return arg_1, arg_4


def Func(arg_0, arg_1):
    """Removes unique identifiers and add the original process names to the
    already parsed pipelines

    Parameters
    ----------
    identifiers_to_tags : dict
        Match between unique process identifiers and process names
    pipeline_links: list
        Parsed pipeline list with unique identifiers

    Returns
    -------
    list
        Pipeline list with original identifiers
    """

    # Replaces the unique identifiers by the original process names
    for arg_2, arg_3 in enumerate(arg_1):
        if arg_3["input"]["process"] != "__init__":
            arg_3["input"]["process"] = arg_0[
                arg_3["input"]["process"]]
        if arg_3["output"]["process"] != "__init__":
            arg_3["output"]["process"] = arg_0[
                arg_3["output"]["process"]]

    return arg_1


def Func(arg_0):
        """Parses the .nextflow.log file and retrieves the complete list
        of processes

        This method searches for specific signatures at the beginning of the
        .nextflow.log file::

             Apr-19 19:07:32.660 [main] DEBUG nextflow.processor
             TaskProcessor - Creating operator > report_corrupt_1_1 --
             maxForks: 4

        When a line with the .*Creating operator.* signature is found, the
        process name is retrieved and populates the :attr:`processes` attribute
        """

        with open(arg_0.log_file) as fh:

            for arg_1 in fh:
                if re.match(".*Creating operator.*", arg_1):
                    # Retrieves the process name from the string
                    arg_2 = re.match(".*Creating operator > (.*) --", arg_1)
                    arg_3 = arg_2.group(1)

                    if any([arg_3.startswith(arg_4) for arg_4 in arg_0._blacklist]):
                        continue

                    if arg_3 not in arg_0.skip_processes:
                        arg_0.processes[arg_2.group(1)] = {
                            "barrier": "W",
                            "submitted": set(),
                            "finished": set(),
                            "failed": set(),
                            "retry": set(),
                            "cpus": None,
                            "memory": None
                        }
                        arg_0.process_tags[arg_3] = {}

                # Retrieves the pipeline name from the string
                if re.match(".*Launching `.*` \[.*\] ", arg_1):
                    arg_8 = re.match(".*Launching `.*` \[(.*)\] ", arg_1)
                    arg_0.pipeline_tag = arg_8.group(1) if arg_8 else \
                        "?"
                    arg_10 = re.match(".*Launching `(.*)` \[.*\] ", arg_1)
                    arg_0.pipeline_name = arg_10.group(1) if arg_10 \
                        else "?"

        arg_0.content_lines = len(arg_0.processes)


def Func(arg_0):
        """Clears inspect attributes when re-executing a pipeline"""

        arg_0.trace_info = defaultdict(list)
        arg_0.process_tags = {}
        arg_0.process_stats = {}
        arg_0.samples = []
        arg_0.stored_ids = []
        arg_0.stored_log_ids = []
        arg_0.time_start = None
        arg_0.time_stop = None
        arg_0.execution_command = None
        arg_0.nextflow_version = None
        arg_0.abort_cause = None
        arg_0._c = 0
        # Clean up of tag running status
        for arg_13 in arg_0.processes.values():
            arg_13["barrier"] = "W"
            for arg_14 in ["submitted", "finished", "failed", "retry"]:
                arg_13[arg_14] = set()