def Guo_Sun(dp, voidage, vs, rho, mu, Dt, L=1):
    """Calculates pressure drop across a packed bed of spheres using a
    correlation developed in [1]_. This is valid for highly-packed particles
    at particle/tube diameter ratios between 2 and 3, where a ring packing
    structure occurs. If a packing ratio is so low, it is important to use this
    model because in some cases its predictions are as low as half those of
    other models!

    .. math::
        f_v = 180 + \\left(9.5374\\frac{d_p}{D_t} - 2.8054\\right)Re_{Erg}^{0.97}

    .. math::
        f_v = \\frac{\\Delta P d_p^2}{\\mu v_s L}\\frac{\\epsilon^3}{(1-\\epsilon)^2}

    .. math::
        Re_{Erg} = \\frac{\\rho v_s  d_p}{\\mu(1-\\epsilon)}

    Parameters
    ----------
    dp : float
        Particle diameter of spheres [m]
    voidage : float
        Void fraction of bed packing [-]
    vs : float
        Superficial velocity of the fluid (volumetric flow rate/cross-sectional
        area)[m/s]
    rho : float
        Density of the fluid [kg/m^3]
    mu : float
        Viscosity of the fluid, [Pa*s]
    Dt : float
        Diameter of the tube, [m]
    L : float, optional
        Length the fluid flows in the packed bed [m]

    Returns
    -------
    dP : float
        Pressure drop across the bed [Pa]

    Notes
    -----
    Developed with data in the range of:

    .. math::
        100 < Re_{m} <33000\\\\
        2 < d_t/d_p < 3 1\\\\
        0.476 < \\epsilon <0.492

    Examples
    --------
    >>> Guo_Sun(dp=14.2E-3, voidage=0.492, vs=0.6, rho=1E3, mu=1E-3, Dt=40.9E-3)
    42019.529911473706

    References
    ----------
    .. [1] Guo, Zehua, Zhongning Sun, Nan Zhang, Ming Ding, and Jiaqing Liu.
       "Pressure Drop in Slender Packed Beds with Novel Packing Arrangement."
       Powder Technology 321 (November 2017): 286-92.
       doi:10.1016/j.powtec.2017.08.024.
    """
    Rem = dp * rho * vs / mu / (1 - voidage)
    fv = 180 + (9.5374 * dp / Dt - 2.8054) * Rem ** 0.97
    return fv * (mu * vs * L / dp ** 2) * (1 - voidage) ** 2 / voidage ** 3


def abi_get_element_by_name(abi, name):
    """ Return element of abi (return None if fails to find) """
    if abi and 'abi' in abi:
        for a in abi['abi']:
            if 'name' in a and a['name'] == name:
                return a
    return None


@classmethod
def from_json(cls, val):
    """ Create chart type from JSON

        Args:
            val (:obj:`dict`)

        Returns:
            :obj:`Chart`
        """
    return cls(id=val.get('id', None))


def delay_each(wait):
    """
        invoke call with passed arguments, keywords in incoming things after
        delay `wait`

        @param wait: time in seconds
        """


@classmethod
def _from_dict(cls, _dict):
    """Initialize a MessageContextSkills object from a json dictionary."""
    args = {}
    xtra = _dict.copy()
    args.update(xtra)
    return cls(**args)


@classmethod
def __jsonDecode__(cls, state):
    """Returns an object of cls based on a given state"""
    return cls(state.pop('owner'), state.pop('type_'), state.pop('name'),
        state.pop('locations', None))


@classmethod
def create_social_auth(cls, user, uid, provider):
    """Create a UserSocialAuth instance for given user"""
    raise NotImplementedError('Implement in subclass')


@staticmethod
def to_config(pref):
    """Pre-processing user's 'pref' to 'self.config' for ease to use."""
    return pref


@classmethod
def get_input_oriented_model(cls, use_super_efficiency, non_discr_categories):
    """ Returns input-oriented model used in ModelBase.

            Args:
                use_super_efficiency (bool): true if super efficiency model
                    should be created, false otherwise.
                non_discr_categories (list of str): list of non-discretionary
                    categories. If empty, all categories are considered
                    discretionary.

            Returns:
                InputOrientedModel: allocated input-oriented model.
        """
    raise NotImplementedError()


def __nonzero__():
    """Return a true value of the interface specification is non-empty
        """


def predict_proba_model(model, scoring_inputs):
    """Uses a trained scikit-learn model to predict class probabilities for the
    scoring data"""
    return model.predict_proba(scoring_inputs)


def __setstate__(state):
    """Set the object data.
        """


def ratio(value, count):
    """compute ratio but ignore count=0"""
    if count == 0:
        return 0.0
    else:
        return value / count


@staticmethod
def get_braces_content(data):
    """extract data from within comma separated, round-braces string
        return list of strings

        >>> ASDL.get_braces_content('(a,b,c)')
        ['a', 'b', 'c']
        """
    left_brace = data.split('(')
    if len(left_brace) > 1:
        return left_brace[1].split(')')[0].split(',')
    return []


@staticmethod
def _retry_after(current_retries):
    """
        retries will happen in this sequence;
        1min, 2min, 4min, 8min, 16min, 32min, 16min, 16min, 16min ...
        """
    if current_retries < 0:
        current_retries = 0
    if current_retries >= 6:
        return 60 * 16
    else:
        return 60 * (1 * 2 ** current_retries)


def getSquareDistance(p1, p2):
    """
    Square distance between two points
    """
    dx = p1['x'] - p2['x']
    dy = p1['y'] - p2['y']
    return dx * dx + dy * dy


def changelog():
    """ Iterator over the history of property changes
        """


@classmethod
def from_module_dict(cls, environment, module_dict, globals):
    """Creates a template object from a module.  This is used by the
        module loader to create a template object.

        .. versionadded:: 2.4
        """
    return cls._from_namespace(environment, module_dict, globals)


def _plot_unit_traces(ax, x, data, ci, color, err_kws, **kwargs):
    """Plot a trace for each observation in the original data."""
    if isinstance(color, list):
        if 'alpha' not in err_kws:
            err_kws['alpha'] = 0.5
        for i, obs in enumerate(data):
            ax.plot(x, obs, color=color[i], label='_nolegend_', **err_kws)
    else:
        if 'alpha' not in err_kws:
            err_kws['alpha'] = 0.2
        ax.plot(x, data.T, color=color, label='_nolegend_', **err_kws)


def isTau(pid):
    """Determine if the PID is that of an tau or antitau"""
    return abs(pid) == 15


def broadcast_logical_xor(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns the result of element-wise **logical xor** with broadcasting.

    Example::

       x = [[ 1.,  1.,  0.],
            [ 1.,  1.,  0.]]

       y = [[ 1.],
            [ 0.]]

       broadcast_logical_xor(x, y) = [[ 0.,  0.,  1.],
                                      [ 1.,  1.,  0.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L190

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


@staticmethod
def before(**kw):
    """Do setup just before actions in a group are performed.

        Can be implemented as a static method by the :class:`Action`
        subclass.

        :param ``**kw``: a dictionary of configuration objects as specified
          by the ``config`` class attribute.
        """
    pass


def reference_prefix(metric, reference):
    """
    Return the prefix for a metric displayed for a reference (or no Reference)

    :return:
        A string that is used as the prefix for a reference metric.
    """
    if reference is not None and reference.delta_percent:
        return None
    return metric.prefix


@staticmethod
def sanitize_for_archive(url, headers, payload):
    """Sanitize the URL, headers and payload of a HTTP request before storing/retrieving items.
        By default, this method does not modify url, headers and payload. The modifications take
        place within the specific backends that redefine the sanitize_for_archive.

        :param: url: HTTP url request
        :param: headers: HTTP headers request
        :param: payload: HTTP payload request

        :returns url, headers and payload sanitized
        """
    return url, headers, payload


def _float_metric_value(metric):
    """Gets the value of a float-value keras metric."""
    return metric.result().numpy().astype(float)


def setAbortState(*args):
    """Access and changes protected abort_state class data. The returned value representation is an integer ranging from 0 to 1. This approach is a secure method to access and change saved system abort state values.

    Parameters
    ----------
    abort_state : int
        Values for abort state range from 0 for 'System Performance Nominal' to 1 for 'Abort'.
    value : int
        Set values from 0 for 'System Performance Nominal' to 1 for 'Abort'.

    Returns
    -------
    abort_state : int
         Values for abort state range from 0 for 'System Performance Nominal' to 1 for 'Abort'.
    """
    args[0].abort_state = args[1]
    return args[0]


def factor(n):
    """
        find the prime factors of n along with their frequencies. Example:

        >>> factor(786456)
        [(2,3), (3,3), (11,1), (331,1)]

        Source: Project Euler forums for problem #3
    """
    f, factors, prime_gaps = 1, [], [2, 4, 2, 4, 6, 2, 6, 4]
    if n < 1:
        return []
    while True:
        for gap in ([1, 1, 2, 2, 4] if f < 11 else prime_gaps):
            f += gap
            if f * f > n:
                if n == 1:
                    return factors
                else:
                    return factors + [(n, 1)]
            if not n % f:
                e = 1
                n //= f
                while not n % f:
                    n //= f
                    e += 1
                factors.append((f, e))


def get_tokens(line_dt):
    """
    Goes through each charachter in scrumpy file attempting to find tokens

    BUG: if there is a numeric after a direction token this fails
    e.g. '->2 "PROTON"' fails but '-> 2 "PROTON"' works
    """
    tokens = []
    quoted = False
    tk_str = ''
    line_dt = line_dt.replace('->', '-> ')
    line_dt = line_dt.replace('<-', '<- ')
    line_dt = line_dt.replace('<>', '<> ')
    for ch in line_dt:
        if ch in ['"', "'"]:
            if not quoted:
                quoted = True
                if len(tk_str) and ch != ' ':
                    tokens.append(tk_str)
                tk_str = ch
            elif tk_str[0] == ch:
                tk_str += ch
                tokens.append(tk_str)
                tk_str = ''
                quoted = False
            else:
                tk_str += ch
        elif ch in ['(', ')', ':', ',', ' '] and not quoted:
            if len(tk_str):
                tokens.append(tk_str)
            tk_str = ''
            if ch != ' ':
                tokens.append(ch)
        else:
            tk_str += ch
    if len(tk_str):
        tokens.append(tk_str)
    return tokens


@staticmethod
def sector_hex_to_subsector_hex(hex_id):
    """Transform sector hex_id to subsector hex_id"""
    hex_id_col = int(hex_id[:2])
    hex_id_row = int(hex_id[2:])
    col = hex_id_col % 8
    row = hex_id_row % 10
    if col == 0:
        col = 8
    if row == 0:
        row = 10
    return '{0:02d}{1:02d}'.format(col, row)


def padNextPower2(size: int) ->int:
    """Calculate the amount of padding to next power of 2

    Parameters
    ----------
    size : float
        Size of array to be padded

    Returns
    -------
    padSize : int
        Amout of extra padding required to increase to next power of 2
    """
    import math
    next2Power = math.ceil(math.log(size, 2))
    next2Size = math.pow(2, int(next2Power))
    return int(next2Size) - size


def p_enum_constant_list_1(t):
    """enum_constant_list : enum_constant"""
    t[0] = t[1]


@classmethod
def _check_addable(cls, obj, tagname):
    """Check if the given tagname is addable to the given obj
        """
    if tagname == cls.tagname:
        return True
    for elt in cls._choice_classes:
        if elt.tagname in obj:
            err = '%s is already defined' % elt.tagname
            if elt.tagname != tagname:
                err = "%s is defined so you can't add %s" % (elt.tagname,
                    tagname)
            raise Exception(err)


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


@classmethod
def account_capture_relinquish_account_details(cls, val):
    """
        Create an instance of this class set to the
        ``account_capture_relinquish_account_details`` tag with value ``val``.

        :param AccountCaptureRelinquishAccountDetails val:
        :rtype: EventDetails
        """
    return cls('account_capture_relinquish_account_details', val)


@classmethod
def create_oauth(cls, name, token, refresh_token, description=None):
    """
        Creates the OAUTH credentials.

        Parameters
        ----------
        name : str
            the name to use for this set of credentials.
        token: str
            the OAUTH token
        refresh_token: str
            The OAUTH token

        description : str
            the description to use for this set of credentials.

        Returns
        -------
        credential : Credential
            the created credential.

        Examples
        --------
        .. code-block:: python

            >>> import datarobot as dr
            >>> cred = dr.Credential.create_oauth(
            ...     name='my_oauth_cred',
            ...     token='XXX',
            ...     refresh_token='YYY',
            ... )
            >>> cred
            Credential('5e429d6ecf8a5f36c5693e03', 'my_oauth_cred', 'oauth'),
        """
    payload = {'name': name, 'credentialType': 'oauth', 'token': token,
        'refreshToken': refresh_token, 'description': description}
    return cls.from_server_data(cls._client.post(cls._path, data=payload).
        json())


def document_contains_text(docbody):
    """Test whether document contains text, or is just full of worthless
       whitespace.
       @param docbody: (list) of strings - each string being a line of the
        document's body
       @return: (integer) 1 if non-whitespace found in document; 0 if only
        whitespace found in document.
    """
    found_non_space = 0
    for line in docbody:
        if not line.isspace():
            found_non_space = 1
            break
    return found_non_space


def buildStarted(builderName, build):
    """Builder 'builderName' has just started a build. The build is an
        object which implements IBuildStatus, and can be queried for more
        information.

        This method may return an IStatusReceiver (it could even return
        'self'). If it does so, stepStarted and stepFinished methods will be
        invoked on the object for the steps of this one build. This is a
        convenient way to subscribe to all build steps without missing any.
        This receiver will automatically be unsubscribed when the build
        finishes.

        It can also return a tuple of (IStatusReceiver, interval), in which
        case buildETAUpdate messages are sent ever 'interval' seconds, in
        addition to the stepStarted and stepFinished messages."""


def truncate(s, n):
    """Return s truncated to n characters."""
    return s if len(s) <= n else s[:n - 3] + '...'


def to66(theVal):
    """Converts theVal to representation code 66 integer from theWord."""
    return theVal


def trim(text, tabwidth=4):
    """
    Trim text of common, leading whitespace.

    Based on the trim algorithm of PEP 257:
        http://www.python.org/dev/peps/pep-0257/
    """
    if not text:
        return ''
    lines = text.expandtabs(tabwidth).splitlines()
    maxindent = len(text)
    indent = maxindent
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    trimmed = [lines[0].strip()] + [line[indent:].rstrip() for line in
        lines[1:]]
    i = 0
    while i < len(trimmed) and not trimmed[i]:
        i += 1
    return '\n'.join(trimmed[i:])


@staticmethod
def _custom_datasource_name(collection_id):
    """
        Prepares a name for custom (BYOC) datasource, which is then added to DataSource enum.

        :param: collection_id: Collection id of the BYOC, user's input.
        :type: string
        :return: Name for custom (BYOC) datasource.
        :rtype: string
        """
    return 'BYOC_{}'.format(collection_id)


def get_intersection(u, v, node_presence):
    """
    Get the intersection between the presence of u and v.

    :param u: First Node
    :param v: Second Node
    :param node_presence: Node presence
    :return: Interection
    """
    intersec = []
    for ut0, ut1 in zip(node_presence[u][::2], node_presence[u][1::2]):
        for vt0, vt1 in zip(node_presence[v][::2], node_presence[v][1::2]):
            if ut0 <= vt1 and vt0 <= ut1:
                intersec += [max(ut0, vt0), min(vt1, ut1)]
    return intersec


def render_git_describe_long(pieces):
    """TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def arr_as_arr5(arr):
    """Convert an n-tensor to a 5-tensor"""
    depth = len(arr.shape)
    if depth == 1:
        return arr.reshape(1, 1, 1, 1, arr.shape[0])
    if depth == 2:
        return arr.reshape(1, 1, 1, arr.shape[0], arr.shape[1])
    if depth == 3:
        return arr.reshape(1, 1, arr.shape[0], arr.shape[1], arr.shape[2])
    if depth == 4:
        return arr.reshape(1, arr.shape[0], arr.shape[1], arr.shape[2], arr
            .shape[3])
    if depth == 5:
        return arr
    if depth == 6 and arr.shape[0] in [None, 1]:
        return arr.reshape(arr.shape[1:])
    raise ValueError('invalid number of dimensions')


@classmethod
def get_real_child_model(cls, data):
    """Returns the real base class specified by the discriminator"""
    discriminator_value = data[cls.json_discriminator_key]
    return cls.discriminator_value_class_map.get(discriminator_value)


def encode_request(command, pathname, params):
    """Encode a command, pathname and parameters into a turnip-proto-request.
    """
    if b' ' in command or b'\x00' in pathname:
        raise ValueError('Metacharacter in arguments')
    bits = [pathname]
    for name in sorted(params):
        value = params[name]
        if b'=' in name or b'\x00' in name + value:
            raise ValueError('Metacharacter in arguments')
        bits.append(name + b'=' + value)
    return command + b' ' + b'\x00'.join(bits) + b'\x00'


def lambd_NH3_SO3_CB89(T, P):
    """n-a: ammonia sulfite [CB89]."""
    lambd = 0.158
    valid = T == 298.15
    return lambd, valid


def count_query_results(query, endpoint):
    """
    Returns the total number of results that query 'query' will generate
    WARNING: This is too expensive just for providing a number of result pages
             Providing a dummy count for now
    """
    return 1000


def cunningham(lbm):
    """
    The Cunningham equation for resting metabolic rate (RMR). This formula is similar to Katch-McArdle, but provides a slightly higher estimate.

    """
    return 500 + 22 * lbm


def elem_C(w, C):
    """
    Simulation Function: -C-

    Inputs
    ----------
    w = Angular frequency [1/s]
    C = Capacitance [F]
    """
    return 1 / (C * (w * 1.0j))


def getSegments(nmlcell, component, sg_to_segments):
    """Get the list of segments the `component` is applied to"""
    sg = component.segmentGroup
    seg = component.segment
    if sg is None:
        if seg:
            segments = [seg]
        else:
            segments = nmlcell.morphology.segment
    elif sg == 'all':
        segments = [seg for seglist in sg_to_segments.values() for seg in
            seglist]
    else:
        segments = sg_to_segments[sg]
    return segments


def conv_8upto16(val, nb):
    """ converts val (8bits) to 8+n bits (n must be comprised between 0 & 8 bits)
    :warning: conversion output shall not exceed 16bits (input shall strictly be unsigned 8bits)
    :warning: nb shall be in range 0-8 (note that using 0 doesn't change val)
    :param val: 8b var to convert
    :param nb: nb of bit pseudo shifts to add
    :return: 8+n bits conversion result """
    return (val << nb) + (val & 255 >> 8 - nb) & 65535


def retrieve_options(args, env):
    """
    Retrieve PlopRotTemp options from input arguments
    """
    options = []
    if args.core != -1:
        options.extend(['--core {}'.format(args.core)])
    if args.mtor != 4:
        options.extend(['--mtor {}'.format(args.mtor)])
    if args.n != 1000:
        options.extend(['--n {}'.format(args.n)])
    if args.forcefield != 'OPLS2005':
        options.extend(['--force {}'.format(args.forcefield)])
    if args.mae_lig:
        options.extend(['--mae_charges'])
    if args.gridres != 10:
        options.extend(['--gridres {}'.format(args.gridres)])
    return ' '.join(options)


def binstate_to_density(binstate):
    """Converts from binary state to density

	Args:
		binstate (string) : The binary state
	Returns:
		int
	Example:
		>>> binstate_to_density('1110')
		>>> 3
	"""
    return sum(map(int, binstate))


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


def getNextByDate(message_id):
    """Returns a proxy for the next message by date"""


def compress(lhs_label, rhs_label):
    """Combine two labels where the rhs replaces the lhs. If the rhs is
    empty, assume the lhs takes precedent."""
    if not rhs_label:
        return lhs_label
    label = list(lhs_label)
    label.extend([None] * len(rhs_label))
    label = label[:len(rhs_label)]
    for idx, rhs_part in enumerate(rhs_label):
        label[idx] = rhs_part or label[idx]
    return label


def users_statistics(lines):
    """
        Parse detailed statistics about each user.

        Input:
        `lines`    # A sequence of strings which represents rows of multiple
                   # tables with information about users' statistics. The table
                   # can be obtained by executing 'user STAT' command in DS
                   # console. Example:
                   # [
                   #     "-------------------------------------------------------",
                   #     "Name: 		=user1",
                   #     "Score: 		0",
                   #     "State: 		In Flight",
                   #     "Enemy Aircraft Kill: 		0",
                   #     "Enemy Static Aircraft Kill: 		0",
                   #     "Enemy Tank Kill: 		0",
                   #     "Enemy Car Kill: 		0",
                   #     "Enemy Artillery Kill: 		0",
                   #     "Enemy AAA Kill: 		0",
                   #     "Enemy Wagon Kill: 		0",
                   #     "Enemy Ship Kill: 		0",
                   #     "Enemy Radio Kill: 		0",
                   #     "Friend Aircraft Kill: 		0",
                   #     "Friend Static Aircraft Kill: 		0",
                   #     "Friend Tank Kill: 		0",
                   #     "Friend Car Kill: 		0",
                   #     "Friend Artillery Kill: 		0",
                   #     "Friend AAA Kill: 		0",
                   #     "Friend Wagon Kill: 		0",
                   #     "Friend Ship Kill: 		0",
                   #     "Friend Radio Kill: 		0",
                   #     "Fire Bullets: 		0",
                   #     "Hit Bullets: 		0",
                   #     "Hit Air Bullets: 		0",
                   #     "Fire Roskets: 		0",
                   #     "Hit Roskets: 		0",
                   #     "Fire Bombs: 		0",
                   #     "Hit Bombs: 		0",
                   #     "-------------------------------------------------------",
                   # ]

        Output:
        An object which provides information about users' statistics.
        """


def p_function_call_parameter_list(p):
    """function_call_parameter_list : function_call_parameter_list COMMA function_call_parameter
                                    | function_call_parameter"""
    if len(p) == 4:
        p[0] = p[1] + [p[3]]
    else:
        p[0] = [p[1]]


def have_pyrex():
    """
    Return True if Cython or Pyrex can be imported.
    """
    pyrex_impls = 'Cython.Distutils.build_ext', 'Pyrex.Distutils.build_ext'
    for pyrex_impl in pyrex_impls:
        try:
            __import__(pyrex_impl, fromlist=['build_ext']).build_ext
            return True
        except Exception:
            pass
    return False


def create_snapshot(DirectoryId=None, Name=None):
    """
    Creates a snapshot of a Simple AD or Microsoft AD directory in the AWS cloud.
    See also: AWS API Documentation

    :example: response = client.create_snapshot(
        DirectoryId='string',
        Name='string'
    )

    :type DirectoryId: string
    :param DirectoryId: [REQUIRED]
            The identifier of the directory of which to take a snapshot.

    :type Name: string
    :param Name: The descriptive name to apply to the snapshot.

    :rtype: dict
    :return: {
        'SnapshotId': 'string'
    }

    """
    pass


def getDimension(unique_name):
    """Returns a IDimension in the Catalog with the given unique name."""


def fullname(cls):
    """Gets the fully qualified type name of this class."""
    if type(cls) != type:
        cls = type(cls)
    module = cls.__module__
    if module is None or module == str.__class__.__module__:
        return cls.__name__
    else:
        return '.'.join([module, cls.__name__])


def difference(c1, c2):
    """Return the keys or items in c1 for which there is no key in c2.

        If c1 is None, then None is returned.  If c2 is None, then c1
        is returned.

        If neither c1 nor c2 is None, the output is a Set if c1 is a Set or
        TreeSet, and is a Bucket if c1 is a Bucket or BTree.
        """


def swap_axes(ranges):
    """Swaps the ":math:`i`" and ":math:`j`" axes of a reduction's optional **ranges** parameter.

    This function returns **None** if **ranges** is **None**,
    and swaps the :math:`i` and :math:`j` arrays of indices otherwise."""
    if ranges is None:
        return None
    else:
        return *ranges[3:6], *ranges[0:3]


def structure_torrent_data(target_dict, hash_str, data):
    """Updated target dict with torrent data structured suitably
    for config storage.

    :param target_dict: dict - dictionary to update
    :param hash_str: str - torrent identifying hash
    :param data: dict - torrent data received from RPC (see parse_torrent())
    :return:
    """
    data = dict(data)
    if 'hash' not in data:
        data['hash'] = hash_str
    if 'name' not in data:
        data['name'] = None
    if 'url' not in data:
        data['url'] = None
    target_dict[hash_str] = {'hash': data['hash'], 'name': data['name'],
        'url': data['url']}


def close_tables(egg_string, target_level=0):
    """ The egg string is hierarchically ordered. This function appends curly brackets to close open tables.
    It takes the indentation of the last closed bracket as reference for the current level/depth of the hierarchy.
    :param egg_string:
    :type egg_string: str
    :param target_level: The level determinates the target indentation/depth,
    in other words how many tables should be closed.
    :type target_level: int
    :return: egg_string with closed tables.
    :rtype: str
    """
    last_level = egg_string[egg_string[:-1].rfind('\n'):].count('  ')
    diff = last_level - target_level
    for level in range(diff):
        egg_string += '{0}}}\n'.format('  ' * (last_level - level - 1))
    return egg_string


def game_property_clear():
    """Remove all game properties from all selected objects

    """
    pass


def get_first_df(corpus):
    """
    Get the first document in a corpus, so that we can
    check what columns it has
    """
    from corpkit.corpus import Corpus
    if not isinstance(corpus, Corpus):
        corpus = Corpus(corpus, print_info=False)
    if corpus.subcorpora:
        return corpus.subcorpora[0].files[0].document
    elif corpus.files:
        return corpus.files[0].document
    else:
        return corpus.document


def is_power2(num):
    """
    states if a number is a power of two
    """
    return num != 0 and num & num - 1 == 0


def init():
    """Initialize a site."""
    print('Please read the documentation and set up Coil CMS manually:')
    print('https://coil.readthedocs.io/admin/setup/')
    return 255


def output_resid(results):
    """
    This convenience function outputs the residuals
    from a regression
    """
    return results.resid


def mean(array, *args, **kwargs):
    """
    Computes the arithmetic mean.

    See Also
    --------
    Array.mean
    """
    return array.mean(*args, **kwargs)


@classmethod
def _write_vars_plus_flanks_to_fasta(cls, outfile, vcf_records, ref_seqs,
    flank_length, number_ns=0):
    """Given a dict of vcf records made by vcf_file_read.vcf_file_to_dict(),
        and its correcsponding file of reference sequences, writes a new fasta file
        of each ref seq and inferred variant sequence plus flank_length nucleotides added to
        its start and end. Calls each sequence:
            ref_name.start_position.vcf_list_index.allele_number
        where allele_numbers in same order as VCF, with ref seq = allele 0."""
    prev_ref_name = None
    prev_ref_pos = None
    j = 0
    with open(outfile, 'w') as f:
        for ref_name in sorted(vcf_records):
            for i, vcf_record in enumerate(vcf_records[ref_name]):
                start_position, alleles = (vcf_record.
                    inferred_var_seqs_plus_flanks(ref_seqs[ref_name],
                    flank_length))
                for allele_index, allele_seq in enumerate(alleles):
                    seq_name = '.'.join([ref_name, str(start_position + 1),
                        str(j), str(i), str(allele_index)])
                    allele_seq = allele_seq.replace('.', '')
                    for n in range(number_ns):
                        allele_seq = 'N' + allele_seq + 'N'
                    print('>' + seq_name, allele_seq, sep='\n', file=f)
                if (prev_ref_name == ref_name and prev_ref_pos ==
                    start_position):
                    j += 1
                else:
                    j = 0
                prev_ref_name = ref_name
                prev_ref_pos = start_position


def render_git_describe_long(pieces):
    """TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def get_host_path(volume):
    """
    Get the first part of a docker volume entry.

    >>> docker_volume_string = "./path/on/host:/path/in/container:rw"
    >>> get_host_path(docker_volume_string)
    './path/on/host'
    """
    return volume.split(':')[0]


def calculate_max_velocity(engine_speed_at_max_power, max_speed_velocity_ratio
    ):
    """
    Calculates max vehicle velocity [km/h].

    :param engine_speed_at_max_power:
        Rated engine speed [RPM].
    :type engine_speed_at_max_power: float

    :param max_speed_velocity_ratio:
        Maximum speed velocity ratio of the gear box [h*RPM/km].
    :type max_speed_velocity_ratio: float

    :return:
        Max vehicle velocity [km/h].
    :rtype: float
    """
    return engine_speed_at_max_power / max_speed_velocity_ratio


def symbolic(func):
    """Dummy decorator used in TensorFlow 2.0 to enter the Keras graph."""
    return func


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def file_lines_generator(path: 'str', with_eol=False):
    """
    read lines from file
    :param path: path
    :param with_eol: where line with '
' suffix
    :return: file line generator
    """
    with open(path) as fp:
        while True:
            line = fp.readline()
            if len(line) == 0:
                break
            if with_eol:
                yield line
            else:
                yield line[:-1]


def _encrypt(data):
    """Low level encrypt interface"""


def _combine_dicts(list_of_dicts, combine_function):
    """
    >>> d = _combine_dicts(
    ...      [ {'key1': 1, 'key2': 2},
    ...        {'key1': 1} ],
    ...      combine_function = operator.add)
    >>> d['key1']
    2
    >>> d['key2']
    2
    """
    result = {}
    for a_dict in list_of_dicts:
        for k, v in list(a_dict.items()):
            if k in result:
                result[k] = combine_function(result[k], v)
            else:
                result[k] = v
    return result


@staticmethod
def _is_redirection_result(response):
    """
        Return True if response is that of a redirection else False
        Redirection results have no information of use.
        """
    imdb_id = response['data'].get('tconst')
    if imdb_id and imdb_id != response['data'].get('news', {}).get('channel'):
        return True
    return False


def fi(df, close='close', volume='volume', col='fi', n=2):
    """Force Index (FI)
    It illustrates how strong the actual buying or selling pressure is. High
    positive values mean there is a strong rising trend, and low values signify
    a strong downward trend.
    http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index
    Args:
        close(pandas.Series): dataset 'Close' column.
        volume(pandas.Series): dataset 'Volume' column.
        n(int): n period.
        fillna(bool): if True, fill nan values.
    Returns:
        pandas.Series: New feature generated.
    """
    df = df.copy()
    fi = df[close].diff(n) * df[volume].diff(n)
    df[col] = fi
    return df


def normalize_page_number(page_number, page_range):
    """Handle a negative *page_number*.

    Return a positive page number contained in *page_range*.
    If the negative index is out of range, return the page number 1.
    """
    try:
        return page_range[page_number]
    except IndexError:
        return page_range[0]


def __new__(cls, cpe_str, *args, **kwargs):
    """
        Create a new CPE Name of version 2.3 with URI style.

        :param string cpe_str: CPE Name string
        :returns: CPE object of version 2.3 of CPE specification with
            URI style.
        :rtype: CPE2_3_URI
        """
    return dict.__new__(cls)


def k2r(temp_k):
    """Convert temperature value from Kelvin to Rankine"""
    return temp_k * 9 / 5


def get_prim_obj_from_sol(sol, parameters=None):
    """
    Gets the primal objective from the solution of the LP problem

    Parameters
    -------------
    sol
        Solution of the ILP problem by the given algorithm
    parameters
        Possible parameters of the algorithm

    Returns
    -------------
    prim_obj
        Primal objective
    """
    return sol['primal objective']


def compute_pairwise_centroid(vec1, vec2):
    """Takes 2 vectors vec1, vec2 and returns the centroids of
    vec1 and vec2 as a vector named "centroids". Here, the "centroid"
    vector is a list type variable. For better understanding please the run
    code and check the variables in the "test of function/example section below
    the function"

    Dependencies:
        *Does not require any custom function (constructed by me)

    Required by:
        *pairwise_cluster_init
        *pairwise_cluster_elong

	"""
    centroids = []
    for i in range(0, len(vec1)):
        centroid = (vec1[i] + vec2[i]) / 2
        centroids.append(centroid)
    return centroids


def remove_head_id(ref, hyp):
    """Assumes that the ID is the begin token of the string which is common
    in Kaldi but not in Sphinx."""
    ref_id = ref[0]
    hyp_id = hyp[0]
    if ref_id != hyp_id:
        print(
            """Reference and hypothesis IDs do not match! ref="{}" hyp="{}"
File lines in hyp file should match those in the ref file."""
            .format(ref_id, hyp_id))
        exit(-1)
    ref = ref[1:]
    hyp = hyp[1:]
    return ref, hyp


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


@classmethod
def CreateTranslation(cls, x=0, y=0, z=0):
    """
        Creates a translation matrix for the given offset.

        :param x: x-coordinate of translation (default 0)
        :type x:  ``int`` or ``float``

        :param y: y-coordinate of translation (default 0)
        :type y:  ``int`` or ``float``

        :param z: z-coordinate of translation (default 0)
        :type z:  ``int`` or ``float``
        """
    result = cls()
    result.translate(x, y, z)
    return result


def join_b2_path(b2_dir, b2_name):
    """
    Like os.path.join, but for B2 file names where the root directory is called ''.

    :param b2_dir: a directory path
    :type b2_dir: str
    :param b2_name: a file name
    :type b2_name: str
    """
    if b2_dir == '':
        return b2_name
    else:
        return b2_dir + '/' + b2_name


def parse_accession(data_dict):
    """Retrieve Accession from PhagesDB.

    :param data_dict: Dictionary of data retrieved from PhagesDB.
    :type data_dict: dict
    :returns: Accession of the phage.
    :rtype: str
    """
    try:
        accession = data_dict['genbank_accession']
    except:
        accession = ''
    return accession


def get_message_by_hash(message_id_hash):
    """Return the message with the matching Message-ID-Hash.

        :param message_id_hash: The Message-ID-Hash header contents to
            search for.
        :returns: The message, or None if no matching message was found.
        """


def verify_equal_package_versions(packages):
    """
    Verify that all packages have the same version number.

    :param packages: The list of ``Package`` objects, ``list``
    :returns: The version number
    :raises: :exc:RuntimeError` If the version is not equal in all packages
    """
    version = None
    for package in packages:
        if version is None:
            version = package.version
        elif package.version != version:
            raise RuntimeError(
                """Two packages have different version numbers (%s != %s):
- %s
- %s"""
                 % (package.version, version, package.filename, list(
                packages)[0].filename))
    return version


@classmethod
def seri_kws(cls):
    """Get a list of valid keyword arguments."""
    return list(set(list(cls._schema_properties.keys()) + cls._oldstyle_kws))


def __call__(context):
    """Returns a default value for the field."""


def _xyplot_base(plot_function, coordinate_pairs, *args, **kwds):
    """A wrapper around <function> based on coordinate pairs
       instead of x and y lists.
       Optionally takes keyword "swapxy" to swap x and y."""
    swapxy = kwds.pop('swapxy', False)
    x, y = zip(*coordinate_pairs)
    if swapxy:
        x, y = y, x
    return plot_function(x, y, *args, **kwds)


def calc_relativistic_correction(stoichiometry):
    """Calculate the relativistic correction to the Kramers-Kronig transform.

	Parameters:
	-----------
	stoichiometry : array of integer/float pairs
		Each pair in the list consists of an atomic number and the relative proportion of that element.

	Returns
	-------
	This function returns a ``float`` holding the relativistic
	corection to the Kramers-Kronig transform.

	"""
    correction = 0
    for z, n in stoichiometry:
        correction += (z - (z / 82.5) ** 2.37) * n
    return correction


@staticmethod
def _allocate_space(current_directory) ->int:
    """Attempt to allocate directory `data{n}`, increment until success.

        Returns
        -------
        _postfix : int
            The number corresponding to the allocated directory.
        """
    _postfix = 0
    while True:
        _attempt = current_directory.joinpath('data' + str(_postfix))
        if not _attempt.exists():
            _attempt.mkdir(parents=True)
            break
        else:
            _postfix += 1
    return _postfix


def fetch_insertion(chrom, st, cigar):
    """ fetch insertion regions defined by cigar. st must be zero based
	return list of tuple of (chrom,st, end)

	NOTE: insertion region does NOT present in reference genome and there
	fore cannot represented using reference coordinates[start, end]. So we
	use [start, SIZE).
	[(100,2)] means 2nt insert between 100 and 101
	"""
    chrom_st = st
    ins_bound = []
    for c, s in cigar:
        if c == 0:
            chrom_st += s
        elif c == 1:
            ins_bound.append((chrom, chrom_st, s))
            continue
        elif c == 2:
            chrom_st += s
        elif c == 3:
            chrom_st += s
        elif c == 4:
            chrom_st += s
        else:
            continue
    return ins_bound


@classmethod
def from_dir(cls, project_home):
    """Construct a ProjectMetadata that reads from the specified directory."""
    return cls(project_home)


def latex_table(result, *, decimal_places=3, label=None):
    """
    Creates a latex table from the results dataframe of the statistical analysis.

    # Parameters

    result (RankResult):
        Should be the return value the autorank function.

    decimal_places (int, default=3):
        Number of decimal places that are used for the report.

    label (str, default=None):
        Label of the table. Defaults to 'tbl:stat_results' if None.
    """
    if label is None:
        label = 'tbl:stat_results'
    table_df = result.rankdf
    columns = table_df.columns.to_list()
    if result.pvalue >= result.alpha:
        columns.remove('effect_size')
        columns.remove('magnitude')
    if result.posthoc == 'tukeyhsd':
        columns.remove('meanrank')
    columns.insert(columns.index('ci_lower'), 'CI')
    columns.remove('ci_lower')
    columns.remove('ci_upper')
    rename_map = {}
    if result.all_normal:
        rename_map['effect_size'] = '$d$'
    else:
        rename_map['effect_size'] = 'D-E-L-T-A'
    rename_map['magnitude'] = 'Magnitude'
    rename_map['mad'] = 'MAD'
    rename_map['median'] = 'MED'
    rename_map['meanrank'] = 'MR'
    rename_map['mean'] = 'M'
    rename_map['std'] = 'SD'
    format_string = '[{0[ci_lower]:.' + str(decimal_places
        ) + 'f}, {0[ci_upper]:.' + str(decimal_places) + 'f}]'
    table_df['CI'] = table_df.agg(format_string.format, axis=1)
    table_df = table_df[columns]
    table_df = table_df.rename(rename_map, axis='columns')
    float_format = '{:0.' + str(decimal_places) + 'f}'
    table_string = table_df.to_latex(float_format=float_format.format).strip()
    table_string = table_string.replace('D-E-L-T-A', '$\\delta$')
    print('\\begin{table}[h]')
    print('\\centering')
    print(table_string)
    print('\\caption{Summary of populations}')
    print('\\label{%s}' % label)
    print('\\end{table}')


def install(context):
    """
     Ordinarily, GenericSetup handlers check for the existence of XML files.
     Here, we are not parsing an XML file, but we use this text file as a
     flag to check that we actually meant for this import step to be run.
     The file is found in profiles/default.
    """
    if context.readDataFile('sc.galleria.support_default.txt') is None:
        return


def copy_driver_button():
    """Copy the driver for the highlighted button

    """
    pass


def _cdp_split_times_read_aligns(split_alignment_dict):
    """
    Dict. of times a read aligns to all references
    {read: times aligned}
    """
    srna_align_counts = {}
    for aligned_sRNAs in split_alignment_dict.values():
        for aligned_sRNA, count in aligned_sRNAs.items():
            if aligned_sRNA in srna_align_counts:
                srna_align_counts[aligned_sRNA] += count
            else:
                srna_align_counts[aligned_sRNA] = count
    return srna_align_counts


@classmethod
def estimated_input_weight(cls, txin, is_segwit_tx):
    """Return an estimate of serialized input weight in weight units."""
    script = cls.input_script(txin, True)
    input_size = len(cls.serialize_input(txin, script)) // 2
    if cls.is_segwit_input(txin, guess_for_address=True):
        witness_size = len(cls.serialize_witness(txin, True)) // 2
    else:
        witness_size = 1 if is_segwit_tx else 0
    return 4 * input_size + witness_size


def _import(name):
    """Return module from a package.

    These two are equivalent:

        > from package import module as bar
        > bar = _import('package.module')

    """
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        try:
            mod = getattr(mod, comp)
        except AttributeError:
            raise ImportError('No module named %s' % mod)
    return mod


def RESET(db, cache):
    """
    Truncates the entire database and clears the cache.

    This will commit to the database, all database information
    WILL be lost!
    """
    cache.ram.clear()
    cache.disk.clear()
    for table in db.tables:
        db[table].truncate('CASCADE')
    db.commit()


def _hermite_param(ctx, n, z, parabolic_cylinder):
    """
    Combined calculation of the Hermite polynomial H_n(z) (and its
    generalization to complex n) and the parabolic cylinder
    function D.
    """
    n, ntyp = ctx._convert_param(n)
    z = ctx.convert(z)
    q = -ctx.mpq_1_2
    if not z:
        T1 = [2, ctx.pi], [n, 0.5], [], [q * (n - 1)], [], [], 0
        if parabolic_cylinder:
            T1[1][0] += q * n
        return T1,
    can_use_2f0 = ctx.isnpint(-n) or ctx.re(z) > 0 or ctx.re(z
        ) == 0 and ctx.im(z) > 0
    expprec = ctx.prec * 4 + 20
    if parabolic_cylinder:
        u = ctx.fmul(ctx.fmul(z, z, prec=expprec), -0.25, exact=True)
        w = ctx.fmul(z, ctx.sqrt(0.5, prec=expprec), prec=expprec)
    else:
        w = z
    w2 = ctx.fmul(w, w, prec=expprec)
    rw2 = ctx.fdiv(1, w2, prec=expprec)
    nrw2 = ctx.fneg(rw2, exact=True)
    nw = ctx.fneg(w, exact=True)
    if can_use_2f0:
        T1 = [2, w], [n, n], [], [], [q * n, q * (n - 1)], [], nrw2
        terms = [T1]
    else:
        T1 = [2, nw], [n, n], [], [], [q * n, q * (n - 1)], [], nrw2
        T2 = [2, ctx.pi, nw], [n + 2, 0.5, 1], [], [q * n], [q * (n - 1)], [
            1 - q], w2
        terms = [T1, T2]
    if parabolic_cylinder:
        expu = ctx.exp(u)
        for i in range(len(terms)):
            terms[i][1][0] += q * n
            terms[i][0].append(expu)
            terms[i][1].append(1)
    return tuple(terms)


def set_aes_src(lucid, srcval):
    """Call lucid8824.set_aes_src"""
    lucid.set_aes_src(srcval)


def _get_exclude_files(old_baseline):
    """
    Older versions of detect-secrets always had an `exclude_regex` key,
    this was replaced by the `files` key under an `exclude` key in v0.12.0

    :rtype: str|None
    """
    if old_baseline.get('exclude'):
        return old_baseline['exclude']['files']
    if old_baseline.get('exclude_regex'):
        return old_baseline['exclude_regex']


def get_empty_znode(node_id):
    """
    Get an empty ZNode with headers filled.

    Args:
        node_id: String that identifies the ZNode

    Returns:
        A dictionary representing a ZNRecord
    """
    return {'id': node_id, 'simpleFields': {}, 'listFields': {},
        'mapFields': {}}


@staticmethod
def _escape_unicode_char_xubrace(c, ord=ord):
    """
        Escape a Unicode code point using `\\xHH` (8-bit) or
        `\\u{H....H}` notation.
        """
    n = ord(c)
    if n < 256:
        return '\\x{0:02x}'.format(n)
    return '\\u{{{0:0x}}}'.format(n)


def ct_parse_header(line):
    """Return simple string of header"""
    return line.strip()


def randompass(string_length=10):
    """Generate random password"""
    from random import choice
    from string import ascii_letters
    letters = ascii_letters
    return ''.join(choice(letters) for i in range(string_length))


def detect(path):
    """
        A static method that returns whether *path* can be parsed by us.
        """


@staticmethod
def _get_row_attribute(row_number, row_attribute):
    """
        Return the attribute for a row. But the preference of the attributes is for the column attributes.

        :param row_number: Number of the actual column that will be used to get it's respective attribute. [str]
        :param row_attribute: List or dictionary with all the attributes to each row. [list, dict]
        :return The attribute value of that row's attribute
        """
    attribute = None
    if row_attribute is not None and str(row_number) in row_attribute:
        attribute = row_attribute[str(row_number)]
    return attribute


def check_integer_na_columns(numerical_column):
    """ Integer columns containing NA values are converted to Float in pandas
        This function checks for a column if it only contains integers (.0)
        In this case we attempt to convert all columns, not just the columns
        that contain an NA value, because we sliced the dataframes from a bigger
        dataframe that could contain NA values.
    """
    for i in numerical_column:
        if str(i) != 'nan':
            decimal_value = str(i).split('.')[1]
            if float(decimal_value) != 0:
                return False
    return True


def save_userpref():
    """Save user preferences separately, overrides startup file preferences

    """
    pass


def make_json(structure, variable_name=None, indent=1, **k):
    """Converts something into a json string, optionally attributing the result
    to a variable.

    It also escapes the forward slash, making the result suitable
    to be included in an HTML <script> tag.
    """
    import json
    s = json.dumps(structure, indent=indent, **k).replace('/', '\\/')
    return '{0} = {1};\n'.format(variable_name, s) if variable_name else s


@classmethod
def from_dict(cls, data: dict) ->'Individual':
    """Load an Individual from a dictionary.

        :param data: Dictionary containing the keys 'age', 'chromosome', 'fitness' and 'id'.
        :return: Individual
        """
    result = cls(chromosome=data['chromosome'], fitness=data['fitness'])
    result.age = data['age']
    result.id = data['id']
    return result


def check_libraries():
    """ Are all required modules available? """
    try:
        import PyQt4
    except ImportError:
        print(
            """

        ----
        PyQt4 is not available ('import PyQt4' failed with ImportError)

        It's not automatically installed through pip because I (the packager)
        can't get beyond 'No distributions at all found for PyQt4' after 'pip
        install PyQt4'

        Please install either from your package manager or by following the
        instructions on the wiki, https://github.com/jsoffer/eilat/wiki/set-up
        ----

        """
            )
        raise
    try:
        import colorama
    except:
        print(
            """

        ----
        Did pip fail at installing 'colorama'? It's a bug
        ----

        """
            )
        raise
    try:
        import tldextract
    except:
        print(
            """

        ----
        Did pip fail at installing 'tldextract'? It's a bug
        ----

        """
            )
        raise


@classmethod
def member_space_limits_remove_custom_quota_details(cls, val):
    """
        Create an instance of this class set to the
        ``member_space_limits_remove_custom_quota_details`` tag with value
        ``val``.

        :param MemberSpaceLimitsRemoveCustomQuotaDetails val:
        :rtype: EventDetails
        """
    return cls('member_space_limits_remove_custom_quota_details', val)


def _format_media_type(endpoint, version, suffix):
    """
    Formats a value for a cosmos Content-Type or Accept header key.

    :param endpoint: a cosmos endpoint, of the form 'x/y',
    for example 'package/repo/add', or 'package/error'
    :type endpoint: str
    :param version: The version of the request
    :type version: str
    :param suffix: The string that will be appended to
    endpoint type, most commonly 'request' or 'response'
    :type suffix: str
    :return: a formatted value for a Content-Type or Accept header key
    :rtype: str
    """
    prefix = endpoint.replace('/', '.')
    separator = '-' if suffix else ''
    return 'application/vnd.dcos.{}{}{}+json;charset=utf-8;version={}'.format(
        prefix, separator, suffix, version)


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def get_float_from_config(config, section, key, default=None):
    """
    Get a value from the config if it exists, otherwise return the default value
    :param config: The configuration to get the value from
    :param section: The section to get the value from
    :param key: The key that may or may not exist
    :param default: The default value to return, which is None by default
    :return: The value if it exists, else default
    """
    if config.has_option(section, key):
        return config.getfloat(section, key)
    else:
        return default


def getReferencesHeader():
    """
    Returns the 'references' part in output file
    """
    str = ''
    str += """-------------------------------------------------------------------------------------------------------
"""
    str += ' References:\n'
    str += '\n'
    str += (
        '   Very Fast Empirical Prediction and Rationalization of Protein pKa Values\n'
        )
    str += '   Hui Li, Andrew D. Robertson and Jan H. Jensen\n'
    str += (
        '   PROTEINS: Structure, Function, and Bioinformatics 61:704-721 (2005)\n'
        )
    str += '   \n'
    str += """   Very Fast Prediction and Rationalization of pKa Values for Protein-Ligand Complexes
"""
    str += '   Delphine C. Bas, David M. Rogers and Jan H. Jensen\n'
    str += (
        '   PROTEINS: Structure, Function, and Bioinformatics 73:765-783 (2008)\n'
        )
    str += '   \n'
    str += """   PROPKA3: Consistent Treatment of Internal and Surface Residues in Empirical pKa predictions
"""
    str += (
        '   Mats H.M. Olsson, Chresten R. Sondergard, Michal Rostkowski, and Jan H. Jensen\n'
        )
    str += (
        '   Journal of Chemical Theory and Computation, 7(2):525-537 (2011)\n')
    str += '   \n'
    str += (
        '   Improved Treatment of Ligands and Coupling Effects in Empirical Calculation\n'
        )
    str += '    and Rationalization of pKa Values\n'
    str += (
        '   Chresten R. Sondergaard, Mats H.M. Olsson, Michal Rostkowski, and Jan H. Jensen\n'
        )
    str += '   Journal of Chemical Theory and Computation, (2011)\n'
    str += '   \n'
    str += """-------------------------------------------------------------------------------------------------------
"""
    return str


def merge_dicts(*dict_args, **kwargs):
    """
    Thanks Aaron Hall http://stackoverflow.com/a/26853961/
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    _type = kwargs.get('type', dict)
    result = _type()
    for dictionary in dict_args:
        result.update(dictionary)
    return result


@classmethod
def run(cls, options=None):
    """Build foreman-maintain upgrade run"""
    cls.command_sub = 'run'
    if options is None:
        options = {}
    result = cls._construct_command(options)
    return result


def name(obj):
    """ return name of an object (type). """
    t = str(type(obj))
    s = str(obj)
    if 'function' in t:
        pre, post = s.split(' at ', 1)
        pre, post = pre.split()
        name = "<function '" + post + "'>"
    elif 'module' in t:
        pre, post = s.split(' from ', 1)
        name = '<' + pre[1:] + '>'
    elif 'class' in t:
        if 'method' in t:
            pre, post = s.split(' of ', 1)
            name = "<method '" + pre.split()[-1] + "'>"
        else:
            pre, post = t.split('class ', 1)
            name = "<ding '" + post[:-1][1:-1] + "'>"
    elif 'built-in' in t:
        name = '<' + t + '>'
    return name


def merge(data, skip=50, fraction=1.0):
    """Merge one every 'skip' clouds into a single emcee population,
    using the later 'fraction' of the run."""
    w, s, d = data.chains.shape
    start = int((1.0 - fraction) * s)
    total = int((s - start) / skip)
    return data.chains[:, start::skip, :].reshape((w * total, d))


def nii_ones_like(in_file, value, dtype, newpath=None):
    """Create a NIfTI file filled with ``value``, matching properties of ``in_file``"""
    import os
    import numpy as np
    import nibabel as nb
    nii = nb.load(in_file)
    data = np.ones(nii.shape, dtype=float) * value
    out_file = os.path.join(newpath or os.getcwd(), 'filled.nii.gz')
    nii = nb.Nifti1Image(data, nii.affine, nii.header)
    nii.set_data_dtype(dtype)
    nii.to_filename(out_file)
    return out_file


def get_channel_youtube_url(channel_code):
    """ Get the Youtube Channel URL given its code

    Example:
        UC6gsueJf0YTIF3inlGKWLPg
        must return:
        https://www.youtube.com/channel/UC6gsueJf0YTIF3inlGKWLPg
    """
    return 'https://www.youtube.com/channel/{:s}'.format(channel_code)


def mean(array, *args, **kwargs):
    """
    Computes the arithmetic mean.

    See Also
    --------
    Array.mean
    """
    return array.mean(*args, **kwargs)


def class_to_str(obj):
    """ get class string from object

    Examples
    --------

    >>> class_to_str(list).split('.')[1]
    'list'

    """
    mod_str = obj.__module__
    name_str = obj.__name__
    if mod_str == '__main__':
        return name_str
    else:
        return '.'.join([mod_str, name_str])


def ccs_light(optlevel, chunksize, slicesize):
    """Correct the slicesize and the chunksize based on optlevel."""
    if optlevel in (0, 1, 2):
        slicesize //= 2
    elif optlevel in (3, 4, 5):
        pass
    elif optlevel in (6, 7, 8):
        chunksize /= 2
    elif optlevel == 9:
        chunksize /= 2
        slicesize *= 2
    return chunksize, slicesize


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def _retry_matcher(details):
    """Matches retry details emitted."""
    if not details:
        return False
    if 'retry_name' in details and 'retry_uuid' in details:
        return True
    return False


def ElementWiseSum(*args, **kwargs):
    """Adds all input arguments element-wise.

    .. math::
       add\\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n

    ``add_n`` is potentially more efficient than calling ``add`` by `n` times.

    The storage type of ``add_n`` output depends on storage types of inputs

    - add_n(row_sparse, row_sparse, ..) = row_sparse
    - add_n(default, csr, default) = default
    - add_n(any input combinations longer than 4 (>4) with at least one default type) = default
    - otherwise, ``add_n`` falls all inputs back to default storage and generates default storage

    Defined in src/operator/tensor/elemwise_sum.cc:L155

    Parameters
    ----------
    args : NDArray[]
        Positional input arguments

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


@staticmethod
def addable_cells(obj):
    """
        List object addable cells

        TESTS ::

            sage: from sage.combinat.skew_partition import SkewPartition
            sage: from sage_widget_adapters.combinat.skew_partition_grid_view_adapter import SkewPartitionGridViewAdapter
            sage: sp = SkewPartition([[4, 2, 1],[2, 1]])
            sage: SkewPartitionGridViewAdapter.addable_cells(sp)
            [(0, 1), (1, 0), (0, 4), (1, 2), (2, 1), (3, 0)]
        """
    return obj.inner().corners() + obj.outer().outside_corners()


def _format_frequency_axis(ax):
    """Format the frequency axis of an omega scan plot

    Parameters
    ----------
    ax : `~matplotlib.axis.Axis`
        the `Axis` object to format
    """
    ax.grid(True, axis='y', which='both')
    ax.set_yscale('log')
    ax.set_ylabel('Frequency [Hz]')


def AICc(k, L, n):
    """Computes the corrected Akaike Information Criterion.

    Keyword arguments:
    L  --  log likelihood value of given distribution.
    k  --  number of fitted parameters.
    n  --  number of observations.

    """
    AICc = 2 * k - 2 * L + 2 * k * (k + 1) / (n - k - 1)
    return AICc


def initiateAuthentication(identity_url, return_to=None):
    """Initiate the OpenID authentication.
        """


def melt(df):
    """Melt a census dataframe into two value columns, for the estimate and margin"""
    import pandas as pd
    melted = pd.melt(df, id_vars=list(df.columns[:9]), value_vars=list(df.
        columns[9:]))
    melted = melted[['gvid', 'variable', 'value']]
    estimates = melted[~melted.variable.str.contains('_m90')].set_index([
        'gvid', 'variable'])
    margins = melted[melted.variable.str.contains('_m90')].copy()
    margins.columns = ['gvid', 'ovariable', 'm90']
    margins['variable'] = margins.ovariable.str.replace('_m90', '')
    final = estimates.join(margins.set_index(['gvid', 'variable']).drop(
        'ovariable', 1))
    return final


def assert_equivalent(o1, o2):
    """Asserts that o1 and o2 are distinct, yet equivalent objects
    """
    if not (isinstance(o1, type) and isinstance(o2, type)):
        assert o1 is not o2
    assert o1 == o2
    assert o2 == o1


def merge_aliases(log, deployed_accounts, aliases):
    """
    Merge account aliases into deployed_accounts lookup table.
    """
    for account in deployed_accounts:
        account['Alias'] = aliases.get(account['Id'], '')
        log.debug(account)
    return deployed_accounts


def methodReturnType(m, macro):
    """macro should be NS_IMETHOD or NS_IMETHODIMP"""
    if m.nostdcall and m.notxpcom:
        return '%s%s' % (macro == 'NS_IMETHOD' and 'virtual ' or '', m.
            realtype.nativeType('in').strip())
    elif m.nostdcall:
        return '%snsresult' % (macro == 'NS_IMETHOD' and 'virtual ' or '')
    elif m.notxpcom:
        return '%s_(%s)' % (macro, m.realtype.nativeType('in').strip())
    else:
        return macro


def challenge(status='403 Forbidden', app_headers=()):
    """ -> wsgi application

        o Return a WSGI application which represents a "challenge"
        (request for credentials) in response to the current request.
        """


def _init_globals() ->None:
    """
    Initialize all global variables declared by this submodule.
    """
    global WRITER_BASENAME_TO_CONTAINER_FILETYPE_TO_CODEC_NAMES
    WRITER_BASENAME_TO_CONTAINER_FILETYPE_TO_CODEC_NAMES = {'ffmpeg': {
        'avi': ('libx264', 'libxvid', 'mpeg4', 'h263', 'mpeg2video'), 'gif':
        ('gif',), 'mkv': None, 'mov': None, 'mp4': None, 'ogv': (
        'libtheora',), 'webm': ('libvpx',)}, 'avconv': None, 'mencoder':
        None, 'convert': {'gif': (None,)}}
    codec_names = WRITER_BASENAME_TO_CONTAINER_FILETYPE_TO_CODEC_NAMES
    codec_names['ffmpeg']['mp4'] = ('libx264', 'hevc') + codec_names['ffmpeg'][
        'avi'][1:]
    codec_names['ffmpeg']['mov'] = codec_names['ffmpeg']['mp4']
    codec_names['ffmpeg']['mkv'] = codec_names['ffmpeg']['webm'] + codec_names[
        'ffmpeg']['ogv'] + codec_names['ffmpeg']['mp4']
    codec_names['avconv'] = codec_names['ffmpeg']
    codec_names['mencoder'] = codec_names['ffmpeg']


def formActions(primaryButton='', button2=False, button3=False, button4=
    False, button5=False, inlineHelpText=False, blockHelpText=False):
    """
    *Generate a formActions - TBS style*

    **Key Arguments:**
        - ``primaryButton`` -- the primary button
        - ``button2`` -- another button
        - ``button3`` -- another button
        - ``button4`` -- another button
        - ``button5`` -- another button
        - ``inlineHelpText`` -- inline and block level support for help text that appears around form controls
        - ``blockHelpText`` -- a longer block of help text that breaks onto a new line and may extend beyond one line

    **Return:**
        - ``formActions`` -- the formActions
    """
    falseList = [primaryButton, button2, button3, button4, button5,
        inlineHelpText]
    for i in range(len(falseList)):
        if not falseList[i]:
            falseList[i] = ''
    [primaryButton, button2, button3, button4, button5, inlineHelpText
        ] = falseList
    if inlineHelpText:
        inlineHelpText = (
            '%(inlineHelpText)s' % locals())
    else:
        inlineHelpText = ''
    if blockHelpText:
        blockHelpText = (
            '%(blockHelpText)s' % locals())
    else:
        blockHelpText = ''
    formActions = (
        """

          %(primaryButton)s
          %(button2)s
          %(button3)s
          %(button4)s
          %(button5)s

%(inlineHelpText)s%(blockHelpText)s"""
         % locals())
    return formActions


def cache_directives_in_headers(headers):
    """
    Checks if cache controls are set in response headers
    """
    cache_control = 'cache-control' in headers
    pragma = 'pragma' in headers and 'no-cache' in headers['pragma']
    expires = 'expires' in headers
    return expires or pragma or cache_control


@classmethod
def from_xlogdb_line(cls, line):
    """
        Parse a line from xlog catalogue

        :param str line: a line in the wal database to parse
        :rtype: WalFileInfo
        """
    try:
        name, size, time, compression = line.split()
    except ValueError:
        compression = None
        try:
            name, size, time = line.split()
        except ValueError:
            raise ValueError('cannot parse line: %r' % (line,))
    if compression == 'None':
        compression = None
    size = int(size)
    time = float(time)
    return cls(name=name, size=size, time=time, compression=compression)


def appendb(path, data):
    """Write data to a binary file.

    Args:
        path (str): Full path to file
        data (str): File bytes

    Returns:
        int: Number of bytes appended
    """
    with open(path, 'ab') as handle:
        return handle.write(data)


def _get_list(dict_, key):
    """get dict_[key] or create this entry as a new list."""
    res = dict_.get(key)
    if res is not None:
        return res
    new = []
    dict_[key] = new
    return new


def parse_line(line_string):
    """standardize line describtion.

    Bruker saves line description in all caps
    and omits the type if only one exists instead of
    using alfa"""
    if len(line_string) == 1:
        line_string = line_string + 'a'
    elif len(line_string) > 2:
        line_string = line_string[:2]
    return line_string.capitalize()


def t_TAG(t):
    """:[a-zA-Z_][a-zA-Z0-9_]*"""
    t.value = t.value[1:].upper()
    return t


def remove_edge(graph, s, t):
    """Remove edge from a graph.

    Parameters
    ----------
    graph : regraph.Graph
    s : hashable, source node id.
    t : hashable, target node id.

    Raises
    ------
    GraphError
        If edge between `s` and `t` does not exist.

    """
    graph.remove_edge(s, t)


def get_relion_header(names):
    """
    Create a relion star file header.

    names - Header names as list

    Returns:
    header string
    """
    header = []
    header.append('')
    header.append('data_')
    header.append('')
    header.append('loop_')
    for index, name in enumerate(names):
        header.append('{0} #{1}'.format(name, index + 1))
    return '\n'.join(header)


def detypographize(s):
    u"""
    >>> print(detypographize(u'“Foo bar—baz ‘qux’—xyzzy”: A–Z'))
    "Foo bar--baz 'qux'--xyzzy": A-Z
    """
    return s.replace(u'“', u'"').replace(u'”', u'"').replace(u'‘', u"'"
        ).replace(u'’', u"'").replace(u'—', u'--').replace(u'–', u'-').replace(
        u'−', u'-').replace(u'\xa0', u' ')


@classmethod
def raise_exception(cls, error, task_id, upload_layer, verbose_message):
    """
        A method to create a new saved exception.
        """
    if verbose_message is None:
        verbose_message = error
    exception = cls(error=error, verbose_traceback=verbose_message, task_id
        =task_id, upload_layer=upload_layer)
    exception.save()
    return exception


def pattern_match(s, p):
    """pattern match used in 'include' and 'exclude' option
    """
    i, j, star_match_pos, last_star_pos = 0, 0, 0, -1
    while i < len(s):
        if j < len(p) and p[j] in (s[i], '?'):
            i, j = i + 1, j + 1
        elif j < len(p) and p[j] == '*':
            star_match_pos, last_star_pos = i, j
            j += 1
        elif last_star_pos > -1:
            i, star_match_pos = star_match_pos + 1, star_match_pos + 1
            j = last_star_pos + 1
        else:
            return False
    while j < len(p) and p[j] == '*':
        j += 1
    return j == len(p)


def check_auth(username, password):
    """
    This function is called to check if a username / password
    combination is valid.
    """
    return username == 'admin' and password == 'secret'


def removeNonUTF8(s):
    """remove non-utf8 values from string s and replace with <NON-UTF8>"""
    if s:
        new_words = []
        for w in s.split():
            if len(w.encode('utf-8', 'ignore').decode('utf-8', 'ignore')
                ) < len(w):
                new_words.append('<NON-UTF8>')
            else:
                new_words.append(w)
        return ' '.join(new_words)
    return ''


@staticmethod
def is_victim():
    """ Determines if the object is a Victim. """
    return False


def delete_virtual_mfa_device(SerialNumber=None):
    """
    Deletes a virtual MFA device.
    See also: AWS API Documentation

    Examples
    The following delete-virtual-mfa-device command removes the specified MFA device from the current AWS account.
    Expected Output:

    :example: response = client.delete_virtual_mfa_device(
        SerialNumber='string'
    )

    :type SerialNumber: string
    :param SerialNumber: [REQUIRED]
            The serial number that uniquely identifies the MFA device. For virtual MFA devices, the serial number is the same as the ARN.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@:/-

    :return: response = client.delete_virtual_mfa_device(
        SerialNumber='arn:aws:iam::123456789012:mfa/ExampleName',
    )

    print(response)

    """
    pass


def _donothing_func(*args, **kwargs):
    """Perform no good and no bad"""
    pass


def create_adjancency_matrix(db, save_folder='../../data/interim/',
    num_orders=10):
    """
    Make weighted adjacency matrix from the instacart database.
    """
    if not isinstance(num_orders, int):
        raise TypeError('Number of orders must be of type int.')
    query_string = (
        """
        SELECT
            CAST (o.user_id AS INTEGER),
            p.product_id,
            COUNT(p.product_id) AS weight
        FROM
            order_products__prior as p
        INNER JOIN
            (
                SELECT
                    order_id,
                    user_id
                FROM
                    orders
                WHERE
                    eval_set='prior'
                LIMIT
                    {}
            ) AS o
        ON
            o.order_id=p.order_id
        GROUP BY
            o.user_id, p.product_id
        ;
        """
        .format(num_orders))
    df = db.get_dataframe(query_string)
    df.to_csv(save_folder + 'weighted_adjacency_matrix_{}_orders.csv'.
        format(num_orders), index=False)
    prior_orders_query = (
        """
        SELECT
            o.user_id, p.product_id,
            products.department_id, products.aisle_id,
            p.order_id, p.add_to_cart_order,
            p.reordered, o.order_number,
            o.order_dow, o.order_hour_of_day,
            CAST (o.days_since_prior AS INTEGER)
        FROM
            order_products__prior AS p
        INNER JOIN
        (
            SELECT
                user_id, order_id, order_number,
                order_dow, order_hour_of_day,
                days_since_prior
            FROM
                orders
            WHERE
                order_id IN
                (
                    SELECT
                        DISTINCT order_id
                    FROM
                        orders
                    WHERE
                        eval_set='prior'
                    LIMIT
                        {}
                )
        ) AS o
        ON
            o.order_id=p.order_id
        INNER JOIN
            products
        ON
            products.product_id=p.product_id
        ;
    """
        .format(num_orders))
    df = db.get_dataframe(prior_orders_query)
    df.to_csv(save_folder + 'full_info_{}_prior_orders.csv'.format(
        num_orders), index=False)
    db.close()


def _inFilesystemNamespace(path):
    """
    Determine whether the given unix socket path is in a filesystem namespace.

    While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
    above support PF_UNIX sockets in an "abstract namespace" that does not
    correspond to any path. This function returns C{True} if the given socket
    path is stored in the filesystem and C{False} if the path is in this
    abstract namespace.
    """
    return path[:1] not in (b'\x00', u'\x00')


def is_ens_domain(authority: str) ->bool:
    """
    Return false if authority is not a valid ENS domain.
    """
    if authority[-4:] != '.eth' or len(authority.split('.')) not in [2, 3]:
        return False
    return True


def _secret_for_graph(secrets, graph):
    """
    returns the first available secret for graph `graph`, or None
    """
    for k, v in secrets.items():
        if v['graph'] == graph:
            return k


def interleave_none(a, b):
    """

    >>> interleave_none([0, None, 2, None], [1, 3])
    (0, 1, 2, 3)
    """
    result = []
    i = j = 0
    n = len(a) + len(b)
    while i + j < n:
        if a[i] is not None:
            result.append(a[i])
            i += 1
        else:
            result.append(b[j])
            i += 1
            j += 1
    return tuple(result)


def maketabdesc(descs=[]):
    """Create a table description.

    Creates a table description from a set of column descriptions. The
    resulting table description can be used in the :class:`table` constructor.

    For example::

      scd1 = makescacoldesc("col2", "aa")
      scd2 = makescacoldesc("col1", 1, "IncrementalStMan")
      scd3 = makescacoldesc("colrec1", {})
      acd1 = makearrcoldesc("arr1", 1, 0, [2,3,4])
      acd2 = makearrcoldesc("arr2", 0.+0j)
      td = maketabdesc([scd1, scd2, scd3, acd1, acd2])
      t = table("mytable", td, nrow=100)

    | This creates a table description `td` from five column descriptions
      and then creates a 100-row table called `mytable` from the table
      description.
    | The columns contain respectivily strings, integer scalars, records,
      3D integer arrays with fixed shape [2,3,4], and complex arrays with
      variable shape.

    """
    rec = {}
    if isinstance(descs, dict):
        descs = [descs]
    for desc in descs:
        colname = desc['name']
        if colname in rec:
            raise ValueError('Column name ' + colname +
                ' multiply used in table description')
        rec[colname] = desc['desc']
    return rec


def json_serializer(obj):
    """Default JSON serializer."""
    import calendar
    import datetime
    if isinstance(obj, datetime.datetime):
        if obj.utcoffset() is not None:
            obj = obj - obj.utcoffset()
        millis = int(calendar.timegm(obj.timetuple()) * 1000 + obj.
            microsecond / 1000)
        return millis
    if isinstance(obj, set):
        return list(obj)
    raise TypeError('Not sure how to serialize %s' % (obj,))


def _parse_boolean(xml_boolean):
    """Converts strings "true" and "false" from XML files to Python bool"""
    if xml_boolean is not None:
        assert xml_boolean in ['true', 'false'
            ], 'The boolean string must be "true" or "false"'
        return {'true': True, 'false': False}[xml_boolean]


def delete_bgp_peer(virtualInterfaceId=None, asn=None, customerAddress=None):
    """
    Deletes a BGP peer on the specified virtual interface that matches the specified customer address and ASN. You cannot delete the last BGP peer from a virtual interface.
    See also: AWS API Documentation

    :example: response = client.delete_bgp_peer(
        virtualInterfaceId='string',
        asn=123,
        customerAddress='string'
    )

    :type virtualInterfaceId: string
    :param virtualInterfaceId: The ID of the virtual interface from which the BGP peer will be deleted.
            Example: dxvif-456abc78
            Default: None

    :type asn: integer
    :param asn: The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.
            Example: 65000

    :type customerAddress: string
    :param customerAddress: IP address assigned to the customer interface.
            Example: 192.168.1.2/30 or 2001:db8::2/125

    :rtype: dict
    :return: {
        'virtualInterface': {
            'ownerAccount': 'string',
            'virtualInterfaceId': 'string',
            'location': 'string',
            'connectionId': 'string',
            'virtualInterfaceType': 'string',
            'virtualInterfaceName': 'string',
            'vlan': 123,
            'asn': 123,
            'authKey': 'string',
            'amazonAddress': 'string',
            'customerAddress': 'string',
            'addressFamily': 'ipv4'|'ipv6',
            'virtualInterfaceState': 'confirming'|'verifying'|'pending'|'available'|'down'|'deleting'|'deleted'|'rejected',
            'customerRouterConfig': 'string',
            'virtualGatewayId': 'string',
            'routeFilterPrefixes': [
                {
                    'cidr': 'string'
                },
            ],
            'bgpPeers': [
                {
                    'asn': 123,
                    'authKey': 'string',
                    'addressFamily': 'ipv4'|'ipv6',
                    'amazonAddress': 'string',
                    'customerAddress': 'string',
                    'bgpPeerState': 'verifying'|'pending'|'available'|'deleting'|'deleted',
                    'bgpStatus': 'up'|'down'
                },
            ]
        }
    }

    :returns:
    ipv4 : IPv4 address family
    ipv6 : IPv6 address family

    """
    pass


def set_table3_field(str_fields, ifield, value):
    """
    ifield is 1 based
    """
    return str_fields[:ifield - 1] + value + str_fields[ifield:]


def strip_version(version):
    """Strip the version of all whitespace."""
    return version.strip().replace(' ', '')


@classmethod
def register(cls, algorithm_name: str, mutation_class):
    """Register a class with a string key."""
    cls.REGISTRY[algorithm_name] = mutation_class
    return mutation_class


def prop_get_distancetofocus(wf):
    """Function to determine distance to focus (in meters) from current location.

    Parameters
    ----------
    wf : obj
        Wavefront class object

    Returns
    -------
    distance to focus : float
        Distance to focus in meters
    """
    return wf.z_w0 - wf.z


def is_client_auth_required(domain):
    """
    Domain requires client authentication if *any* HTTPS endpoint requires it for full TLS connection.
    """
    https, httpswww = domain.https, domain.httpswww
    return (https.https_client_auth_required or httpswww.
        https_client_auth_required)


def save_settings(file_path, record_details, overwrite=False, secret_key=''):
    """ a method to save dictionary typed data to a local file

    :param file_path: string with path to settings file
    :param record_details: dictionary with record details
    :param overwrite: [optional] boolean to overwrite existing file data
    :param secret_key: [optional] string with key to decrypt drep file
    :return: string with file path
    """
    title = 'save_settings'
    try:
        _path_arg = '%s(file_path=%s)' % (title, str(file_path))
    except:
        raise ValueError('%s(file_path=...) must be a string.' % title)
    _details_arg = '%s(record_details={...})' % title
    if not isinstance(record_details, dict):
        raise ValueError('%s must be a dictionary.' % _details_arg)
    if secret_key:
        try:
            _secret_arg = '%s(secret_key=%s)' % (title, str(secret_key))
        except:
            raise ValueError('%s(secret_key=...) must be a string.' % title)
    ext_map = {}
    file_extensions = {'json': '.+\\.json$', 'json.gz': '.+\\.json\\.gz$',
        'yaml': '.+\\.ya?ml$', 'yaml.gz': '.+\\.ya?ml\\.gz$', 'drep':
        '.+\\.drep$'}
    import re
    for key, value in file_extensions.items():
        file_pattern = re.compile(value)
        if file_pattern.findall(file_path):
            ext_map[key] = True
        else:
            ext_map[key] = False
    file_time = 0
    file_data = ''.encode('utf-8')
    if ext_map['json']:
        import json
        file_data = json.dumps(record_details, indent=2).encode('utf-8')
    elif ext_map['yaml']:
        import yaml
        file_data = yaml.dump(record_details).encode('utf-8')
    elif ext_map['json.gz']:
        import json
        import gzip
        file_bytes = json.dumps(record_details).encode('utf-8')
        file_data = gzip.compress(file_bytes)
    elif ext_map['yaml.gz']:
        import yaml
        import gzip
        file_bytes = yaml.dump(record_details).encode('utf-8')
        file_data = gzip.compress(file_bytes)
    elif ext_map['drep']:
        from labpack.compilers import drep
        file_data = drep.dump(record_details, secret_key)
        file_time = 1
    else:
        raise ValueError('%s must be one of %s file types.' % (_path_arg,
            list(ext_map.keys())))
    import os
    if not overwrite:
        if os.path.exists(file_path):
            raise Exception(
                '%s already exists. To overwrite %s, set overwrite=True' %
                (_path_arg, _path_arg))
    dir_path = os.path.split(file_path)
    if dir_path[0]:
        if not os.path.exists(dir_path[0]):
            os.makedirs(dir_path[0])
    with open(file_path, 'wb') as f:
        f.write(file_data)
        f.close()
    if file_time:
        os.utime(file_path, times=(file_time, file_time))
    return file_path


def sync_frame_initializer(new_frame, reference_frame):
    """Set the initializers of the new_frame to be the same as the reference_frame,
    for both the default initializer and per-column initializers.

    Parameters
    ----------
    new_frame : Frame
        The frame to set initializers
    reference_frame : Frame
        The frame to copy initializers
    """
    new_frame._default_initializer = reference_frame._default_initializer
    new_frame._initializers = reference_frame._initializers


def print_attachments(stream, test, all_channels=False):
    """Print out subunit attachments.

    Print out subunit attachments that contain content. This
    runs in 2 modes, one for successes where we print out just stdout
    and stderr, and an override that dumps all the attachments.
    """
    channels = 'stdout', 'stderr'
    for name, detail in test['details'].items():
        name = name.split(':')[0]
        if detail.content_type.type == 'test':
            detail.content_type.type = 'text'
        if (all_channels or name in channels) and detail.as_text():
            title = 'Captured %s:' % name
            stream.write('\n%s\n%s\n' % (title, '~' * len(title)))
            for line in detail.as_text().split('\n'):
                stream.write('    %s\n' % line)


@classmethod
def from_accessions(cls, name, accessions):
    """
        Create a Cohort from an iterable of Accessions.

        Parameters
        ----------
        name : str
            The name of the Cohort
        accessions : iterable of Accessions
            The accessions that will be frozen in the cohort
            under the given name

        Returns
        -------
        A Cohort object

        """
    self = cls(name)
    self.add_accessions(accessions)
    return self


def string_to_bool(_value):
    """Converts "True" to True None to False. Case-insensitive."""
    if _value is not None and _value.lower() == 'true':
        return True
    else:
        return False


@staticmethod
def convert_list_to_test_format(origin: str, data: list) ->str:
    """
        Convert a list in a format ready for tests.

        :param origin: The parent key of the list
        :param data: The list to convert
        :return: The resulting string
        """
    result = []
    for item in data:
        if isinstance(item, str):
            result.append("'%s'" % item)
        elif isinstance(item, bool):
            result.append('`%s`' % 'true' if item else 'false')
        elif isinstance(item, (int, float)):
            result.append('`%s`' % item)
    return '%s[]==[%s]' % (origin, ', '.join(result))


@classmethod
def index(cls, value):
    """Return an index into the Enum given a value."""
    return cls.ALL.index(value)


def waveforms(path, *args, short_circuit=False, validity=None, extrapolated
    =None):
    """Validate waveform files for NSNS simulation

    """
    import re
    import os.path
    import numpy as np
    import h5py
    from . import _Validity
    waveforms = list(set(args))
    v = validity or _Validity(short_circuit)
    raise NotImplementedError()
    return v.valid


@classmethod
def store_db_obj(cls, in_obj, out_obj):
    """Store the IP DB object. """
    cls.ip_db_obj['in'] = in_obj
    cls.ip_db_obj['out'] = out_obj


@classmethod
def showcase_view(cls, val):
    """
        Create an instance of this class set to the ``showcase_view`` tag with
        value ``val``.

        :param ShowcaseViewType val:
        :rtype: EventType
        """
    return cls('showcase_view', val)


def generic_specific_names(species_name):
    """Get generic and specific names from species name."""
    species_name = species_name.replace('s__', '')
    species_name = species_name.replace('Candidatus ', '')
    generic, specific = species_name.split(' ')
    return generic, specific


def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    """
    To check equality of floats
    :param a:
    :param b:
    :param rel_tol:
    :param abs_tol:
    :return:
    """
    if a is None or b is None:
        return False
    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)


def getInfo(lang=None):
    """List of additional information about the event.

        The contents of the list are defined in master data of calendar.

        """


@classmethod
def get_preferred_strategy(cls, strategy1, strategy2):
    """Get preferred strategy in case of multiple migrations being done at once.

        Chose strategy with higher priority - if two migrations are done at the same time one marked as IGNORE another
        as RETRY, we have to retry flow.

        :param strategy1: the first strategy to compare with
        :type strategy1: TaintedFlowStrategy
        :param strategy2: the second strategy to compare with
        :type strategy2: TaintedFlowStrategy
        :return: strategy with higher priority
        :rtype: TaintedFlowStrategy
        """
    return max(strategy1, strategy2)


@staticmethod
def _attributes(element):
    """Get OSM element atttributes and do some common type conversion"""
    result = {}
    for k, v in element.attrib.items():
        if k == 'uid':
            v = int(v)
        elif k == 'changeset':
            v = int(v)
        elif k == 'version':
            v = float(v)
        elif k == 'id':
            v = int(v)
        elif k == 'lat':
            v = float(v)
        elif k == 'lon':
            v = float(v)
        elif k == 'open':
            v = v == 'true'
        elif k == 'visible':
            v = v == 'true'
        elif k == 'ref':
            v = int(v)
        elif k == 'comments_count':
            v = int(v)
        result[k] = v
    return result


def clear_session_vars(context, *args):
    """
    Helper function to clear session variables
    """
    session = context['cs_session_data']
    for i in args:
        try:
            del session[i]
        except:
            pass


def dump_opcodes(opmap):
    """Utility for dumping opcodes"""
    op2name = {}
    for k in opmap.keys():
        op2name[opmap[k]] = k
    for i in sorted(op2name.keys()):
        print('%-3s %s' % (str(i), op2name[i]))


@classmethod
def first_or_create(cls, **attributes):
    """
        Get the first record matching the attributes or create it.

        :param attributes: The instance attributes
        :type attributes: dict

        :return: The new instance
        :rtype: Model
        """
    instance = cls().new_query_without_scopes().where(attributes).first()
    if instance is not None:
        return instance
    return cls.create(**attributes)


def _write(fobj, data):
    """ Write data to file """
    fobj.write(data)


@staticmethod
def resolve_name(value):
    """Resolves name for a given object

        If the object needs to be recursively resolved, this method will
        perform that recursive call.

        Args:
            value (object): A parameter to check if it needs to be recursively
                resolved.

        Returns:
            object: A resolved parameter which may either be a dict or a
                primative object.

        """
    if value is not None and hasattr(value, 'resolve_names') and callable(
        getattr(value, 'resolve_names')):
        return value.resolve_names()
    else:
        return value


def writeScp(filename, uttids, pointers):
    """
    Takes a list of utterance IDs and a list of strings in the format "filename:offset",
      and writes them to a Kaldi script file.
    """
    with open(filename, 'w') as f:
        for uttid, pointer in zip(uttids, pointers):
            f.write('%s %s\n' % (uttid, pointer))


def get_network_monitor_setup(setup, job):
    """
    Return the proper setup for the network monitor.
    The network monitor is currently setup together with the payload and is start before it. The payload setup should
    therefore be provided. The network monitor setup is prepended to it.

    :param setup: payload setup string.
    :param job: job object.
    :return: network monitor setup string.
    """
    return ''


def add_jsclassifier(rule):
    """
        add_jsclassifier

        Add an additional JS classifier rule file

        @param rule: JS classifier rule file
        @type rule: C{str}
        @return: None
        """


@classmethod
def export_to_hdf5(cls, h5_file, model, pids):
    """exports the properties in a vectorized way"""
    encoding = model._encoding
    mid = []
    cordm = []
    integ = []
    stress = []
    isop = []
    fctn = []
    assert len(pids) > 0, pids
    for pid in pids:
        prop = model.properties[pid]
        mid.append(prop.mid)
        cordm.append(prop.cordm)
        if prop.integ is None:
            integ.append(b'')
        elif prop.integ == 0:
            integ.append(b'BUBBLE')
        elif prop.integ == 1:
            integ.append(b'GAUSS')
        elif prop.integ == 2:
            integ.append(b'TWO')
        elif prop.integ == 3:
            integ.append(b'THREE')
        else:
            integ.append(prop.integ.encode(encoding))
        if prop.stress is None:
            stress.append(b'')
        elif prop.stress == 1:
            stress.append(b'GAUSS')
        else:
            stress.append(prop.stress.encode(encoding))
        if prop.isop is None:
            isop.append(b'')
        elif prop.isop == 0:
            isop.append(b'REDUCED')
        elif prop.isop == 1:
            isop.append(b'FULL')
        elif prop.isop == 2:
            isop.append('2')
        else:
            isop.append(prop.isop.encode(encoding))
        fctn.append(prop.fctn.encode(encoding))
    h5_file.create_dataset('pid', data=pids)
    h5_file.create_dataset('mid', data=mid)
    h5_file.create_dataset('cordm', data=cordm)
    h5_file.create_dataset('integ', data=integ)
    h5_file.create_dataset('stress', data=stress)
    h5_file.create_dataset('isop', data=isop)
    h5_file.create_dataset('fctn', data=fctn)


def get_solutions(file_descriptor):
    """Generator of solution lines and corresponding stripped lines for
    \\*mac\\* file.

    .. note:: This function does not return events! It is just original lines and
        cleaned lines containing solutions (i.e sets of frontier
        places/boundaries).

        We remove the last ``'\\n'`` and ``'\\t'``.
        Tabs in the middle are replaced by one space ``' '``.

    :param: Opened file.
    :type: <file>
    :return: A generator of tuples; each tuple contains the original line,
        and the cleaned line.

        :Example:

            For an original line: ``'Z\\tY\\tX\\n'``

            .. code-block:: python

                ('Z\\tY\\tX', 'X Y Z')

    :rtype: <tuple <str>, <str>>
    """
    for line in file_descriptor:
        line = line.rstrip('\n')
        stripped_line = line.rstrip('\t').replace('\t', ' ')
        if stripped_line == '':
            continue
        if stripped_line[0] not in ('%', '=', ' '):
            yield line, stripped_line


@classmethod
def join(cls, *elements, **attributes):
    """
        This method works like Python's str.join(), for example:

            Br.join(*elements)

        """
    from .misc import ElementContainer
    container = ElementContainer()
    if elements:
        ielements = iter(elements)
        for element in ielements:
            if element is not None:
                container.append_children(element)
                break
        for element in ielements:
            if element is not None:
                container.append_children(cls(**attributes), element)
        return container


def zero_bond_price(par_value, market_rate, n):
    """
	Prices a Zero-Coupon Bond
	par_value= bond's par value (base)
	market_rate= market return rate (0.n format)
	n= years into future
	"""
    return par_value / (1 + market_rate) ** n


def set_dtype(dtype):
    """Set numpy dtype.

    Parameters
    ----------
    dtype : str or numpy.dtype
    """
    global _dtype
    _dtype = dtype


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
        If not specified, the value defaults to None.

        """
    self = cls()
    for key in iterable:
        self[key] = value
    return self


def subt(intf, ints):
    """
    overpython.subt(intf, ints)

    Subtract intf with ints. Raises ValueError if intf/ints is a string.
    """
    try:
        return float(intf) - float(ints)
    except ValueError:
        raise ValueError('%s/%s is not a number' % (intf, ints))


def total_seconds(td):
    """Equivalent to `datetime.timedelta.total_seconds`."""
    return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6
        ) / 10 ** 6


def _common_queue_ops(operation, transport, request, name, callback=None):
    """Function for common operation

    This is a lower level call to get a single
    instance of queue.

    :param transport: Transport instance to use
    :type transport: `transport.base.Transport`
    :param request: Request instance ready to be sent.
    :type request: `transport.request.Request`
    :param name: Queue reference name.
    :type name: `six.text_type`
    :param callback: Optional callable to use as callback.
        If specified, this request will be sent asynchronously.
        (IGNORED UNTIL ASYNC SUPPORT IS COMPLETE)
    :type callback: Callable object.
    """
    request.operation = operation
    request.params['queue_name'] = name
    resp = transport.send(request)
    return resp.deserialized_content