def construct_identifier(*args):
    """ Create a post identifier from comment/post object or arguments.

    Examples:

        ::
            construct_identifier('username', 'permlink')
            construct_identifier({'author': 'username',
                'permlink': 'permlink'})
    """
    if len(args) == 1:
        op = args[0]
        author, permlink = op['author'], op['permlink']
    elif len(args) == 2:
        author, permlink = args
    else:
        raise ValueError('construct_identifier() received unparsable arguments'
            )
    author = author.replace('@', '')
    fields = dict(author=author, permlink=permlink)
    return '{author}/{permlink}'.format(**fields)


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 recv_all(sock, n):
    """ Helper function to recv n bytes or return None if EOF is hit """
    data = b''
    while len(data) < n:
        packet = sock.recv(n - len(data))
        if not packet:
            return None
        data += packet
    return data


def post_install(context):
    """Post install script"""


@classmethod
def DeregisterOutput(cls, output_class):
    """Deregisters an output class.

    The output classes are identified based on their NAME attribute.

    Args:
      output_class (type): output module class.

    Raises:
      KeyError: if output class is not set for the corresponding data type.
    """
    output_class_name = output_class.NAME.lower()
    if output_class_name in cls._disabled_output_classes:
        class_dict = cls._disabled_output_classes
    else:
        class_dict = cls._output_classes
    if output_class_name not in class_dict:
        raise KeyError('Output class not set for name: {0:s}.'.format(
            output_class.NAME))
    del class_dict[output_class_name]


def add_argument(*args, **kw):
    """
        Add arguments for parsing.  This should be -o/--option or positional.
        Note that the interface defines the following parameters so that at
        the very least, external extensions can guarantee that they can
        properly add command line arguments when necessary.  The
        implementation itself should, and will provide and support many more
        options than those listed here.  That said, the implementation must
        support the following:

        :arg args: List of option arguments.  Generally something like
            ['-h', '--help'].
        :keyword dest: The destination name (var).  Default: arg[0]'s string.
        :keyword help: The help text for --help output (for that argument).
        :keyword action: Must support: ['store', 'store_true', 'store_false',
            'store_const']
        :keyword choices:  A list of valid values that can be passed to an
         option whose action is ``store``.
        :keyword const: The value stored if action == 'store_const'.
        :keyword default: The default value.
        :returns: ``None``

        """


def getdims(x=(10000, 200)):
    """
    return the dims for network
    """
    assert len(x) == 2
    n_sample = x[0]
    if n_sample > 20000:
        dims = [x[-1], 128, 32]
    elif n_sample > 10000:
        dims = [x[-1], 64, 32]
    elif n_sample > 5000:
        dims = [x[-1], 32, 16]
    elif n_sample > 2000:
        dims = [x[-1], 128]
    elif n_sample > 500:
        dims = [x[-1], 64]
    else:
        dims = [x[-1], 16]
    return dims


def list_straten_adapter(obj, request):
    """
    Adapter for rendering a list of
    :class:`crabpy.gateway.crab.Straat` to json.
    """
    return {'id': obj.id, 'label': obj.label, 'status': {'id': obj.status.
        id, 'naam': obj.status.naam, 'definitie': obj.status.definitie}}


def composite(image1, image2, mask):
    """Create composite image by blending images using a transparency mask"""
    image = image2.copy()
    image.paste(image1, None, mask)
    return image


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

        :param PaperFolderTeamInviteType val:
        :rtype: EventType
        """
    return cls('paper_folder_team_invite', val)


def fromValue(value):
    """Return the scaled value for the metric value"""


def get_params():
    """Parse and analyse command line parameters."""
    import argparse
    parser_usage = """
Provide an input file generated using mmseqs2 and converted into BLASTP compatible tab-separated format.
Outputs a file of ortholog and paralogs that can be processed by InParanoid.
"""
    parser = argparse.ArgumentParser(description='mmseqs2 parser 0.1',
        usage=parser_usage)
    parser.add_argument('-i', '--input', type=str, required=True, help=
        """Tab-separated alignment file generated using mmseqs2 and converted in BLASTP tab-separated format.
NOTE: for details on the fields contained in the output refer to function inparanoid_like_parser"""
        , default=None)
    parser.add_argument('-q', '--query', type=str, required=True, help=
        'FASTA file with the query proteins.', default=None)
    parser.add_argument('-t', '--db', type=str, required=True, help=
        'FASTA file with the target proteins.', default=None)
    parser.add_argument('-o', '--output', type=str, required=True, help=
        'File in which the output will be stored.', default=None)
    parser.add_argument('-r', '--run-dir', type=str, required=False, help=
        'Directory in which the files with sequence lengths are stored.',
        default=None)
    parser.add_argument('-c', '--cutoff', type=int, required=False, help=
        'Cutoff score (sum of hsp bitscores for each hit) for alignments.',
        default=40)
    parser.add_argument('-d', '--debug', required=False, help=
        """Output debug information.
NOTE: this is not used when the input is STDIN."""
        , default=False, action='store_true')
    args = parser.parse_args()
    return args, parser


def commit():
    """Commit the current transaction.

        In explicit mode, if a transaction hasn't begun, a
        `NoTransaction` exception will be raised.
        """


def ut_haider(dp, mu, phi, rhog, rhos):
    """
    Calculate terminal velocity of a particle as discussed in the Haider and
    Levenspiel [5]_. Valid for particle sphericities of 0.5 to 1. Particle
    diameter should be an equivalent spherical diameter, such as the diameter
    of a sphere having same volume as the particle.

    To determine the terminal velocity for a range of particle sphericities, Haider
    and Levenspiel first define two dimensionless quantities

    .. math::

       d_{*} = d_p \\left[ \\frac{g\\, \\rho_g (\\rho_s - \\rho_g)}{\\mu^2} \\right]^{1/3} \\
       u_* = \\left[ \\frac{18}{d{_*}^2} + \\frac{2.3348 - 1.7439\\, \\phi}{d{_*}^{0.5}} \\right]^{-1}

    where :math:`0.5 \\leq \\phi \\leq 1` and particle diameter :math:`d_p` is an
    equivalent spherical diameter, the diameter of a sphere having the same volume
    as the particle. The relationship between :math:`u_*` and :math:`u_t` is given
    by

    .. math:: u_* = u_t \\left[ \\frac{\\rho{_g}^2}{g\\, \\mu\\, (\\rho_s - \\rho_g)} \\right]^{1/3}

    The terminal velocity of the particle can finally be determined by rearranging
    the above equation such that

    .. math:: u_t = u_* \\left[ \\frac{g\\, \\mu\\, (\\rho_s - \\rho_g)}{\\rho{_g}^2} \\right]^{1/3}

    Parameters
    ----------
    dp : float
        Diameter of particle [m]
    mu : float
        Viscosity of gas [kg/(m s)]
    phi : float
        Sphericity of particle [-]
    rhog : float
        Density of gas [kg/m^3]
    rhos : float
        Density of particle [kg/m^3]

    Returns
    -------
    ut : float
        Terminal velocity of a particle [m/s]

    Example
    -------
    >>> ut_haider(0.00016, 1.8e-5, 0.67, 1.2, 2600)
    0.8857

    References
    ----------
    .. [5] A. Haider and O. Levenspiel. Drag coefficient and terminal velocity
           of spherical and nonspherical particles. Powder Technology,
           58:63–70, 1989.
    """
    if phi > 1.0 or phi < 0.5:
        raise ValueError('Sphericity must be 0.5 <= phi <= 1.0')
    d_star = dp * (9.81 * rhog * (rhos - rhog) / mu ** 2) ** (1 / 3)
    u_star = (18 / d_star ** 2 + (2.3348 - 1.7439 * phi) / d_star ** 0.5) ** -1
    ut = u_star * (9.81 * (rhos - rhog) * mu / rhog ** 2) ** (1 / 3)
    return ut


def wireframe(use_boundary: bool=True, use_even_offset: bool=True,
    use_relative_offset: bool=False, use_replace: bool=True, thickness:
    float=0.01, offset: float=0.01, use_crease: bool=False, crease_weight:
    float=0.01):
    """Create a solid wire-frame from faces

    :param use_boundary: Boundary, Inset face boundaries
    :type use_boundary: bool
    :param use_even_offset: Offset Even, Scale the offset to give more even thickness
    :type use_even_offset: bool
    :param use_relative_offset: Offset Relative, Scale the offset by surrounding geometry
    :type use_relative_offset: bool
    :param use_replace: Replace, Remove original faces
    :type use_replace: bool
    :param thickness: Thickness
    :type thickness: float
    :param offset: Offset
    :type offset: float
    :param use_crease: Crease, Crease hub edges for improved subsurf
    :type use_crease: bool
    :param crease_weight: Crease weight
    :type crease_weight: float
    """
    pass


def rupture_force_from_dpdf(dpdf, forces, force_step=None):
    """Calculate the average rupture force for a given probability
    density and the associated force values by numerical integration.

    *f_ext* (the theoretical external force for a rigid molecule) is defined
    by f_ext = 'spring constant' * 'velocity'  * 'time' + 'initial force'
    or the real external force for zero sping constant.

    Parameters
    ----------
    dpdf: list of floats
        dp/df-values for each *f_ext*-value.
    forces: list of floats
        External forces for each *f_ext*.
    force_step: float (optional)
        Step size of *f_ext*.

    Returns
    -------
    result: float
        Rupture force.

    """
    if force_step is None:
        force_step = forces[1] - forces[0]
        for i in range(2, len(forces)):
            if abs(force_step - (forces[i] - forces[i - 1])) > 1e-06:
                raise ValueError('The force steps in list forces should ' +
                    'be constant.')
    integration1 = 0.0
    integration2 = 0.0
    for i in range(len(dpdf)):
        integration1 += dpdf[i] * force_step * forces[i]
        integration2 += dpdf[i] * force_step
    return integration1 / integration2


def format_file_name(path: str) ->str:
    """
    strip illegal characters
    """
    return path.replace('/', '').replace(' ', '').replace('+', '-').replace('"'
        , '').replace('\\', '').replace(':', '-').replace('|', '-')


@classmethod
def factory(cls, global_config, **local_config):
    """Used for paste app factories in paste.deploy config files.

        Any local configuration (that is, values under the [app:APPNAME]
        section of the paste config) will be passed into the `__init__` method
        as kwargs.

        A hypothetical configuration would look like:

            [app:wadl]
            latest_version = 1.3
            paste.app_factory = masakari.api.fancy_api:Wadl.factory

        which would result in a call to the `Wadl` class as

            import masakari.api.fancy_api
            fancy_api.Wadl(latest_version='1.3')

        You could of course re-implement the `factory` method in subclasses,
        but using the kwarg passing it shouldn't be necessary.

        """
    return cls(**local_config)


def initialize_stats_dict(individual):
    """
    Initializes the stats dict for individual
    The statistics initialized are:
        'generation': generation in which the individual was evaluated. Initialized as: 0
        'mutation_count': number of mutation operations applied to the individual and its predecessor cumulatively. Initialized as: 0
        'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively. Initialized as: 0
        'predecessor': string representation of the individual. Initialized as: ('ROOT',)

    Parameters
    ----------
    individual: deap individual

    Returns
    -------
    object
    """
    individual.statistics['generation'] = 0
    individual.statistics['mutation_count'] = 0
    individual.statistics['crossover_count'] = 0
    individual.statistics['predecessor'] = 'ROOT',


def _set_index(x, index):
    """ set the index attribute of something it is possible

    if index is None, or x doesn't have an index attribute it won't do anything

    """
    if index is None:
        return x
    if hasattr(x, 'index'):
        x.index = index
    return x


def get_desktop():
    """
    Get Desktop path
    """
    import winreg
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
        'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
        )
    return winreg.QueryValueEx(key, 'Desktop')[0]


def get_rel_path(path, base):
    """get relative path, e.g., get_rel_path('abc/de/fg', 'abc') => 'de/fg'
    """
    lb = len(base)
    assert path[:lb] == base
    if len(path) == lb:
        rel_path = ''
    elif path[lb] == '/':
        rel_path = path[lb + 1:]
    else:
        rel_path = path[lb:]
    return rel_path


def med(x, D, mixed=False):
    """Generate fraction representation using Mediant method"""
    n1, d1 = int(x), 1
    n2, d2 = n1 + 1, 1
    m = 0.0
    if x != n1:
        while d1 <= D and d2 <= D:
            m = float(n1 + n2) / (d1 + d2)
            if x == m:
                if d1 + d2 <= D:
                    n1, d1 = n1 + n2, d1 + d2
                    d2 = D + 1
                elif d1 > d2:
                    d2 = D + 1
                else:
                    d1 = D + 1
                break
            elif x < m:
                n2, d2 = n1 + n2, d1 + d2
            else:
                n1, d1 = n1 + n2, d1 + d2
    if d1 > D:
        n1, d1 = n2, d2
    if not mixed:
        return [0, n1, d1]
    q = divmod(n1, d1)
    return [q[0], q[1], d1]


def d_perspective_camera_d_shape_parameters(shape_pc_uv, warped_uv, camera):
    """
    Calculates the derivative of the perspective projection with respect to the
    shape parameters.

    Parameters
    ----------
    shape_pc_uv : ``(n_points, 3, n_parameters)`` `ndarray`
        The (sampled) basis of the shape model.
    warped_uv : ``(n_points, 3)`` `ndarray`
        The shape instance with the view transform (rotation and translation)
        applied on it.
    camera : `menpo3d.camera.PerspectiveCamera`
        The camera object that is responsible of projecting the model to the
        image plane.

    Returns
    -------
    dw_da : ``(2, n_shape_parameters, n_points)`` `ndarray`
        The derivative of the perspective camera transform with respect to
        the shape parameters.
    """
    n_points, n_dims, n_parameters = shape_pc_uv.shape
    assert n_dims == 3
    z = warped_uv[:, (2)]
    dw_da = camera.rotation_transform.apply(shape_pc_uv.transpose(0, 2, 1)).T
    dw_da[:2] -= warped_uv[:, :2].T[:, (None)] * dw_da[2] / z
    return camera.projection_transform.focal_length * dw_da[:2] / z


def transform(request, data, finishing=False):
    """Transform in-coming message entity. request will be updated in
        place. Returns the transformed request data.

        ``request``,
            :class:`IHTTPRequest` plugin whose `request.response` attribute
            is being transformed.

        ``data``,
            Either request body or chunk data (in case of chunked encoding)
            in byte-string.

        ``finishing``,
            In case of chunked encoding, this denotes whether this is the last
            chunk to be received.
        """


@classmethod
def load(cls, key, backend=None, only_hdr=False):
    """Load an instance of self with the given key from specified backend.

        :param key:    A dictionary with string keys and string values as
                       produced by the get_key method or a Frontend instance.

        :param backend=None:   The backend we want to load from. If this is
                               None, we call get_backend() to try to get one.

        :param only_hdr=False: Whether to only load the header (in which case
                               we do not need a backend).

        ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-

        :return:   A new instance of self corresponding to the one we
                   `save`-ed previously if only_hdr is False or a dictionary
                   representing the header if only_hdr is True.

        ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-

        PURPOSE:  Inverse of save method; load it back.

        """
    backend = cls.get_backend(backend)
    new_item = backend.load(key, only_hdr=only_hdr, front_cls=cls)
    return new_item


@classmethod
def geometric(cls, n, p):
    """
        Visualization for a Geometric distribution
        Args:
            n, p (float): parameters to a Geometric distribution
        Returns:
            image (IPython.display.Image): The image that can be displayed inline in a Jupyter notebook
        """
    if not isinstance(n, int):
        raise ValueError(
            'For a Geometric distribution, n should always be an integer.')
    if n < 0:
        raise ValueError(
            'For a Geometric distribution, n should be greater than or equal to zero.'
            )
    if not 0 <= p <= 1:
        raise ValueError(
            'For a Geometric distribution, p should always be between 0 and 1.'
            )
    return cls._call_post(dist='geometric', n=n, p=p)


def reshape_1d(df):
    """If parameter is 1D row vector then convert it into 2D matrix."""
    shape = df.shape
    if len(shape) == 1:
        return df.reshape(shape[0], 1)
    else:
        return df


@staticmethod
def call_mod_ptr_or_value(annotation, value):
    """
        Last step in a call_mod_ for classes which wrap swig types and expose them
        via ``value`` and ``ptr`` properties.
        """
    if annotation[::-1].startswith('*'):
        return value.ptr
    return value.value


def et_to_str(node):
    """Get the text value of an Element, returning None if not found."""
    try:
        return node.text
    except AttributeError:
        return None


def copy_prev_settings():
    """Copy settings from previous version

    """
    pass


def __call__(environ):
    """ Return an instance of ``pyramid.request.Request``"""


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


@staticmethod
def _optimize_printing(pipe, config: dict):
    """
        make the sklearn config syntax prettily readable for humans
        """
    if pipe is None:
        return str(config)
    prettified_config = ['' + '\n']
    for el_key, el_value in config.items():
        items = el_key.split('__')
        name = items[0]
        rest = '__'.join(items[1:])
        if name in pipe.named_steps:
            new_pretty_key = '    ' + name + '->'
            prettified_config.append(new_pretty_key + pipe.named_steps[name
                ].prettify_config_output(rest, el_value) + '\n')
        else:
            raise ValueError('Item is not contained in pipeline:' + name)
    return ''.join(prettified_config)


@staticmethod
def _dimensions_to_values(dimensions):
    """
        Replace dimensions specs with their `dimension`
        values, and ignore those without
        """
    values = []
    for dimension in dimensions:
        if isinstance(dimension, dict):
            if 'extractionFn' in dimension:
                values.append(dimension)
            elif 'dimension' in dimension:
                values.append(dimension['dimension'])
        else:
            values.append(dimension)
    return values


def psi_Ca_H_HSO4_HMW84(T, P):
    """c-c'-a: calcium hydrogen bisulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def order_points(p1, p2, nd=3):
    """Given two points swap each axes where p1 > p2

    Args:
      p1 (point): starting point
      p2 (point): ending point
      nd (int optional): number of axes to compare defaults to 3 ie x, y, z
    Returns:
      list: returns same points with axes ordered [[x,y,z], [x,y,z]]

    Links:
    Images:"""
    for i in range(0, nd):
        if p1[i] > p2[i]:
            t1 = p1[i]
            p1[i] = p2[i]
            p2[i] = t1
    return p1, p2


def unauthed_report_predicate(context, request):
    """
    This allows the user to access the view if context object public
    flag is True
    """
    if context.public:
        return True


def moment2(x, y, f, nx, ny, nrm_fac=None):
    """sum[x^nx*y^ny*f]/nrm_fac"""
    if nrm_fac is None:
        nrm_fac = f.sum()
    return (x ** nx * y ** ny * f).sum() / nrm_fac


@classmethod
def from_dict(cls, data_in, model):
    """Constructs a Project from a dictionary of values and a model

        Args:
            data_in (dict): The data to construct the Project from
            model: The model used to predict the durations of tasks

        Returns:
            Project: The constructed project
        """
    return cls(data_in['name'], model, uid=data_in.get('uid', None), tasks=
        data_in.get('tasks', []), dependencies=data_in.get('dependencies', []))


def predecessors_query(var_name, node_id, node_label, edge_label,
    predecessor_label=None):
    """Generate query for getting the ids of all the predecessors of a node.

    Parameters
    ----------
    var_name
        Name of the variable corresponding to the node to match
    node_id
        Id of the node to match
    node_label
        Label of the node to match
    edge_label
        Label of the edge to match
    predecessor_label
        Label of the predecessors we want to find. node_label if None.
    """
    if predecessor_label is None:
        predecessor_label = node_label
    query = "OPTIONAL MATCH (pred:{})-[:{}]-> (n:{} {{id : '{}'}})\n".format(
        predecessor_label, edge_label, node_label, node_id
        ) + 'RETURN pred.id as pred'
    return query


def isoformat(dt):
    """Return iso-formatted timestamp

    Like .isoformat(), but uses Z for UTC instead of +00:00
    """
    return dt.isoformat().replace('+00:00', 'Z')


def inc_key(text):
    """ increment the last letter of text by one.  Used to replace key in SQL LIKE case with less than """
    return text[0:-1] + chr(ord(text[-1]) + 1)


def find_stab(state, stab_xs, stab_zs):
    """
    Find the sign of the logical operator.

    Args:
        state:
        stab_xs:
        stab_zs:

    Returns:

    """
    if len(stab_xs) == 0 and len(stab_zs) == 0:
        return True
    stab_xs = set(stab_xs)
    stab_zs = set(stab_zs)
    stabs = state.stabs
    built_up_xs = set()
    built_up_zs = set()
    for q in stab_xs:
        for stab_id in state.destabs.col_z[q]:
            built_up_xs ^= stabs.row_x[stab_id]
            built_up_zs ^= stabs.row_z[stab_id]
    for q in stab_zs:
        for stab_id in state.destabs.col_x[q]:
            built_up_xs ^= stabs.row_x[stab_id]
            built_up_zs ^= stabs.row_z[stab_id]
    built_up_xs ^= stab_xs
    built_up_zs ^= stab_zs
    if len(built_up_xs) != 0 or len(built_up_zs) != 0:
        return False
    else:
        return True


def google_has_height(style):
    """
    Check if the style of the element has the 'height' attribute
    explicitly defined

    :type style: dict

    :rtype: bool
    """
    return 'height' in style


@classmethod
def _new(cls, local_class, cache_class):
    """ when constructing a new remote using _new you MUST
            call init afterward to bind the remote api """
    newcls = type(cls.__name__, (cls,), dict(_local_class=local_class,
        _cache_class=cache_class))
    local_class._remote_class = newcls
    local_class._cache_class = cache_class
    cache_class._remote_class = newcls
    cache_class._local_class = local_class
    newcls.weighAnchor()
    cache_class.weighAnchor()
    return newcls


@classmethod
def normalize_name(cls, name):
    """
        Replace some characters in command names.
        """
    return name.lower().replace('_', '-').replace(' ', '-')


def feed_url(itunes_lookup_response):
    """
    Returns feed URL from the itunes lookup response
    :param itunes_lookup_response:
    :return: str
    """
    if len(itunes_lookup_response.get('results')) == 0:
        raise LookupError('iTunes response has no results')
    url = itunes_lookup_response.get('results')[0].get('feedUrl')
    if url is None:
        raise LookupError('feedUrl field is not present in response')
    return url


@classmethod
def from_interval(cls, interval):
    """Create the ranges object from `pybedtools.Interval`

        # Arguments
            interval: `pybedtools.Interval` instance
        """
    return cls(chr=interval.chrom, start=interval.start, end=interval.end,
        id=interval.name, strand=interval.strand)


@classmethod
def from_json(cls, project, data):
    """return instance made from given json
        """
    action = cls(project)
    action._apply_json(data)
    return action


@staticmethod
def _close_data_layers(data_layers):
    """Close all data layers with exclusion h5 handlers.

        Parameters
        ----------
        data_layers : None | dict
            Aggregation data layers. Must have fobj exclusion handlers to close
        """
    if data_layers is not None:
        for layer in data_layers.values():
            if 'fobj' in layer:
                layer['fobj'].close()


def parse_image_id(image_ref):
    """Return the image id from a given image ref

    This function just returns the last word of the given image ref string
    splitting with '/'.
    :param str image_ref: a string that includes the image id
    :return: the image id string
    :rtype: string
    """
    return image_ref.rsplit('/')[-1]


def get_attribute_in_object(o, attribute_type=False, attribute_value=False,
    drop=False):
    """Gets the first attribute of a specific type within an object"""
    found_attribute = {'value': ''}
    for i, a in enumerate(o['Attribute']):
        if a['type'] == attribute_type:
            found_attribute = a.copy()
            if drop:
                o['Attribute'].pop(i)
            break
        if a['value'] == attribute_value:
            found_attribute = a.copy()
            if drop:
                o['Attribute'].pop(i)
        if '|' in a['type'] or a['type'] == 'malware-sample':
            if attribute_value in a['value'].split('|'):
                found_attribute = a.copy()
                if drop:
                    o['Attribute'].pop(i)
    return found_attribute


@staticmethod
def initialise_fluids(nw):
    """
        Fluid initialisation for fluid mixture at outlet of the node.

        Parameters
        ----------
        nw : tespy.networks.network
            Network using this component object.
        """
    return


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


@classmethod
def from_item(cls, item):
    """
        Create SlackResource-like class object
        :param item: dict
        :return:
        """
    return cls(**item)


def reverseString(st):
    """ Reverses a string """
    return str(st[::-1])


def put_uri_extension(data):
    """This block of data contains integrity-checking information (hashes
        of plaintext, crypttext, and shares), as well as encoding parameters
        that are necessary to recover the data. This is a serialized dict
        mapping strings to other strings. The hash of this data is kept in
        the URI and verified before any of the data is used. All buckets for
        a given file contain identical copies of this data.

        The serialization format is specified with the following pseudocode:
        for k in sorted(dict.keys()):
            assert re.match(r'^[a-zA-Z_\\-]+$', k)
            write(k + ':' + netstring(dict[k]))

        @param data=URIExtensionData
        @return: a Deferred that fires (with None) when the operation completes
        """


def get_batch_event_count(batch_id):
    """
        Return the count of events.

        :param batch_id:
            The batch identifier for the batch to operate on.

        :returns:
            The number of events in the batch.
            If async, a Deferred is returned instead.
        """


@classmethod
def generate(cls, *args, **kwargs):
    """Shortcut: Hook-up a new initial installation and write configuration file to the disk"""
    node_config = cls(*args, dev_mode=False, **kwargs)
    node_config.initialize()
    node_config.to_configuration_file()
    return node_config


def hawkesll(lda=None, alpha=None, beta=None, state=None, lags=None, marks=
    None, valid_length=None, max_time=None, out=None, name=None, **kwargs):
    """Computes the log likelihood of a univariate Hawkes process.

    The log likelihood is calculated on point process observations represented
    as *ragged* matrices for *lags* (interarrival times w.r.t. the previous point),
    and *marks* (identifiers for the process ID). Note that each mark is considered independent,
    i.e., computes the joint likelihood of a set of Hawkes processes determined by the conditional intensity:

    .. math::

      \\lambda_k^*(t) = \\lambda_k + \\alpha_k \\sum_{\\{t_i < t, y_i = k\\}} \\beta_k \\exp(-\\beta_k (t - t_i))

    where :math:`\\lambda_k` specifies the background intensity ``lda``, :math:`\\alpha_k` specifies the *branching ratio* or ``alpha``, and :math:`\\beta_k` the delay density parameter ``beta``.

    ``lags`` and ``marks`` are two NDArrays of shape (N, T) and correspond to the representation of the point process observation, the first dimension corresponds to the batch index, and the second to the sequence. These are "left-aligned" *ragged* matrices (the first index of the second dimension is the beginning of every sequence. The length of each sequence is given by ``valid_length``, of shape (N,) where ``valid_length[i]`` corresponds to the number of valid points in ``lags[i, :]`` and ``marks[i, :]``.

    ``max_time`` is the length of the observation period of the point process. That is, specifying ``max_time[i] = 5`` computes the likelihood of the i-th sample as observed on the time interval :math:`(0, 5]`. Naturally, the sum of all valid ``lags[i, :valid_length[i]]`` must be less than or equal to 5.

    The input ``state`` specifies the *memory* of the Hawkes process. Invoking the memoryless property of exponential decays, we compute the *memory* as

    .. math::

        s_k(t) = \\sum_{t_i < t} \\exp(-\\beta_k (t - t_i)).

    The ``state`` to be provided is :math:`s_k(0)` and carries the added intensity due to past events before the current batch. :math:`s_k(T)` is returned from the function where :math:`T` is ``max_time[T]``.

    Example::

      # define the Hawkes process parameters
      lda = nd.array([1.5, 2.0, 3.0]).tile((N, 1))
      alpha = nd.array([0.2, 0.3, 0.4])  # branching ratios should be < 1
      beta = nd.array([1.0, 2.0, 3.0])

      # the "data", or observations
      ia_times = nd.array([[6, 7, 8, 9], [1, 2, 3, 4], [3, 4, 5, 6], [8, 9, 10, 11]])
      marks = nd.zeros((N, T)).astype(np.int32)

      # starting "state" of the process
      states = nd.zeros((N, K))

      valid_length = nd.array([1, 2, 3, 4])  # number of valid points in each sequence
      max_time = nd.ones((N,)) * 100.0  # length of the observation period

      A = nd.contrib.hawkesll(
          lda, alpha, beta, states, ia_times, marks, valid_length, max_time
      )

    References:

    -  Bacry, E., Mastromatteo, I., & Muzy, J. F. (2015).
       Hawkes processes in finance. Market Microstructure and Liquidity
       , 1(01), 1550005.

    Defined in src/operator/contrib/hawkes_ll.cc:L84

    Parameters
    ----------
    lda : NDArray
        Shape (N, K) The intensity for each of the K processes, for each sample
    alpha : NDArray
        Shape (K,) The infectivity factor (branching ratio) for each process
    beta : NDArray
        Shape (K,) The decay parameter for each process
    state : NDArray
        Shape (N, K) the Hawkes state for each process
    lags : NDArray
        Shape (N, T) the interarrival times
    marks : NDArray
        Shape (N, T) the marks (process ids)
    valid_length : NDArray
        The number of valid points in the process
    max_time : NDArray
        the length of the interval where the processes were sampled

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

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


def __getitem__(name):
    """Return the named instance"""


def option_name_to_variable_name(option: str):
    """
    Convert an option name like `--ec2-user` to the Python name it gets mapped to,
    like `ec2_user`.
    """
    return option.replace('--', '', 1).replace('-', '_')


def comment_lines(text, prefix='# '):
    """
    Build a Python comment line from input text.

    Parameters
    ----------
    text : str
        Text to comment out.
    prefix : str
        Character to append to the start of each line.
    """
    return prefix + ('\n' + prefix).join(text.split('\n'))


def print_progress(_, i, n) ->None:
    """Prints the progress of a tournament"""
    global n_completed, n_total
    n_completed = i + 1
    n_total = n
    print(
        f'{n_completed:04} of {n:04} worlds completed ({n_completed / n:0.2%})'
        , flush=True)


def format_trace_id(trace_id: int) ->str:
    """Format the trace id according to b3 specification."""
    return format(trace_id, '032x')


def joinExt(*extensions):
    """ Join several path parts with a ."""
    return '.'.join(extensions)


@classmethod
def init_project(cls, project):
    """
        Execute the benchbuild experiment.

        We perform this experiment in 2 steps:
            1. with likwid disabled.
            2. with likwid enabled.

        Args:
            project: The project we initialize.

        Returns:
            The initialized project.
        """
    project.ldflags += ['-lpjit', '-lgomp']
    project.cflags = ['-fno-omit-frame-pointer', '-rdynamic', '-Xclang',
        '-load', '-Xclang', 'LLVMPolly.so', '-Xclang', '-load', '-Xclang',
        'LLVMPolyJIT.so', '-O3', '-mllvm', '-polli-enable-log', '-mllvm',
        '-polli']
    return project


def _reset_regularization_hyperparameter(hparams):
    """Reset regularization hyperparameter lambda."""
    modified_hparams = hparams.copy()
    if 'lambda' in modified_hparams:
        del modified_hparams['lambda']
    return modified_hparams


@classmethod
def from_dict(cls, uri_dict):
    """
        Creates URI from dict

        :return: URI
        """
    return cls(**uri_dict)


def describe_product_as_admin(AcceptLanguage=None, Id=None):
    """
    Retrieves information about a specified product, run with administrator access.
    See also: AWS API Documentation

    :example: response = client.describe_product_as_admin(
        AcceptLanguage='string',
        Id='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

    :type Id: string
    :param Id: [REQUIRED]
            The identifier of the product for which to retrieve information.

    :rtype: dict
    :return: {
        'ProductViewDetail': {
            'ProductViewSummary': {
                'Id': 'string',
                'ProductId': 'string',
                'Name': 'string',
                'Owner': 'string',
                'ShortDescription': 'string',
                'Type': 'CLOUD_FORMATION_TEMPLATE',
                'Distributor': 'string',
                'HasDefaultPath': True|False,
                'SupportEmail': 'string',
                'SupportDescription': 'string',
                'SupportUrl': 'string'
            },
            'Status': 'AVAILABLE'|'CREATING'|'FAILED',
            'ProductARN': 'string',
            'CreatedTime': datetime(2015, 1, 1)
        },
        'Tags': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    }

    """
    pass


def _tdec(code: str, unit: str='C') ->str:
    """
    Translates a 4-digit decimal temperature representation

    Ex: 1045 -> -4.5°C    0237 -> 23.7°C
    """
    if not code:
        return
    ret = f"{'-' if code[0] == '1' else ''}{int(code[1:3])}.{code[3]}"
    if unit:
        ret += f'°{unit}'
    return ret


def check_read(requested, result):
    """Checks that the result of a read from a file was of the expected size
    Raises EOFError if nothing was read, or IOError if the read was incomplete
    """
    if len(result) != requested and requested != 0:
        if result == '':
            raise EOFError()
        else:
            raise IOError('Incomplete read, requested %d recieved %d' % (
                requested, len(result)))


def mval(f, c):
    """Get the negative value, otherwise zero.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the column ``c``.
    c : str
        Name of the column in the dataframe ``f``.

    Returns
    -------
    new_val : float
        Negative value or zero.

    """
    new_val = -f[c] if f[c] < 0 else 0
    return new_val


def cache_exists(key, cache=None):
    """Checks whether there is a value in the cache associated with the given key.

    :param str|unicode key: The cache key to check.

    :param str|unicode cache: Cache name with optional address (if @-syntax is used).

    :rtype: bool
    """
    return False


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a ReMo item."""
    return str(item['remo_url'])


def _get_df_between_date_by_index(data_df, date_frm, date_to):
    """
    该函数仅用于 return_risk_analysis 中计算使用
    :param data_df:
    :param date_frm:
    :param date_to:
    :return:
    """
    if date_frm is not None and date_to is not None:
        new_data_df = data_df[(data_df.index >= date_frm) & (data_df.index <=
            date_to)]
    elif date_frm is not None:
        new_data_df = data_df[data_df.index >= date_frm]
    elif date_to is not None:
        new_data_df = data_df[data_df.index <= date_to]
    else:
        new_data_df = data_df
    return new_data_df


def circle_diam_rad(radius):
    """Usage: Find circle's diameter from radius"""
    return radius * 2


def CRRAutilityP(c, gam):
    """
    Evaluates constant relative risk aversion (CRRA) marginal utility of consumption
    c given risk aversion parameter gam.

    Parameters
    ----------
    c : float
        Consumption value
    gam : float
        Risk aversion

    Returns
    -------
    (unnamed) : float
        Marginal utility
    """
    return c ** -gam


def create_route_short_name(relation):
    """Create a meaningful route short name."""
    return relation.tags.get('ref') or ''


def crossings(y, value, x=None):
    """Finds the crossing points where a (poly-)line defined by a 1D y array has the given
    values and return the (linearly) interpolated index or x value if an x array is given
    """
    raise NotImplementedError


def tangent(u, lmbda):
    """Computes the normalized arc tangent (du/ds, lmbda/ds). Computation is based on
    the equations

       ||du/ds||^2 + (dlmbda/ds)^2 = 1,
       d/ds f(u(s), lmbda(s)) = 0.

    They can be reduced to the nonlinear equation

        0 = df/du v + df/dlmbda sqrt(1 - ||v||^2)

    for `v := du/ds`. Its Jacobian is

        J(v) = df/du - 2 df/dlmbda v^T / sqrt(1 - ||v||^2),

    a rank-1 update to df/du which can be solved via Sherman-Morrison.

    Note that this does not work at turning points where `dlmbda/ds = 0`. Here, `v` is
    the nontrivial solution to

       0 = df/du v.
    """
    pass


@classmethod
def description(cls):
    """Get password manager description."""
    return cls.__doc__.split('\n')[0][:-1]


def delete():
    """Remove all selected keyframes

    """
    pass


def is_quantity(val):
    """Is ``val`` a quantity (int, float, datetime, etc) (not str, bool)?

    Relies on presence of __sub__.
    """
    return hasattr(val, '__sub__')


def can_edit_file(path):
    """Checks if a file can be opend in write mode.

    :param path: The path to the file.
    :return True if it is possible to write on the file, False otherwise.
    """
    can_edit = True
    try:
        fp = open(path, 'a')
        fp.close()
    except IOError:
        can_edit = False
    return can_edit


@classmethod
def get_config_opts(cls):
    """Override base class config options as do not use datasource """
    return []


def _pack_key(tag, wire_type):
    """
    Packs a tag and a wire_type into single int according to the protobuf spec.
    """
    return tag << 3 | wire_type


def _set_uv(params, name: str, index: int, value: float):
    """Adjust the Parameters.UV parameter"""
    if index is not None:
        raise IndexError('You cannot index the UV parameter')
    params.UV = value


def write_2col(filename, data1, data2):
    """Writes data in 2 columns separated by tabs in a "filename" file."""
    f = open(filename, 'w')
    for i, __ in enumerate(data1):
        f.write('\t' + str(data1[i]) + '\t\t' + str(data2[i]) + '\n')
    f.close()


def getname(f):
    """Get the name of an object.

    For use in case of callables that are not functions, and
    thus may not have __name__ defined.

    Order: f.__name__ >  f.name > str(f)
    """
    try:
        return f.__name__
    except:
        pass
    try:
        return f.name
    except:
        pass
    return str(f)


def _power2(n):
    """Find the next power of 2.
    """
    p2 = 16
    while n > p2:
        p2 += p2
    return p2


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 deleteLink(nodeA, nodeB):
    """Delete a link between two node objects.

    This function can be empty. Used for optional complex database quieries.

    Parameters:
        nodeA (MgvNode): source node.
        nodeB (MgvNode): destination node.
    """
    return


def canonical_gid(gid):
    """Get canonical form of NCBI genome accession.

    Example:
        G005435135 -> G005435135
        GCF_005435135.1 -> G005435135
        GCF_005435135.1_ASM543513v1_genomic -> G005435135
        RS_GCF_005435135.1 -> G005435135
        GB_GCA_005435135.1 -> G005435135
    """
    if gid.startswith('U'):
        return gid
    gid = gid.replace('RS_', '').replace('GB_', '')
    gid = gid.replace('GCA_', 'G').replace('GCF_', 'G')
    if '.' in gid:
        gid = gid[0:gid.find('.')]
    return gid


def downgrade():
    """Downgrade database."""
    pass


def search_ancestor(node, *node_types):
    """
    Recursively looks at the parents of a node and returns the first found node
    that matches node_types. Returns ``None`` if no matching node is found.

    :param node: The ancestors of this node will be checked.
    :param node_types: type names that are searched for.
    :type node_types: tuple of str
    """
    while True:
        node = node.parent
        if node is None or node.type in node_types:
            return node


@classmethod
def set_user(cls, value):
    """
        sets the cloud in the category general
        :param value: the cloud as defined in cloudmesh.yaml
        :return:
        """
    cls.set('user', value)


def get_content_length(environ):
    """Return a positive CONTENT_LENGTH in a safe way (return 0 otherwise)."""
    try:
        return max(0, int(environ.get('CONTENT_LENGTH', 0)))
    except ValueError:
        return 0


def run_code(code):
    """Execute the code string `code`.

    Intended to be used in conjunction with :func:`call`.
    """
    exec(code)


def getRoles():
    """Get a sequence of the global roles assigned to the user.
        """


def set_verbosity(verbosity=0):
    """
    Increase verbosity of functions.
    :param verbosity: 0=low, 1=details, 2=very verbose, 3=debug
    """
    global VERBOSE
    VERBOSE = int(verbosity)


def _get_object_id(ordered_dict):
    """
    Gets the first value of the ordered dict (that represents a YAML object).
    ruamel.YAML uses a CommentedMapValuesView as OrderedDict which doesn't support indexing, so we iterate.
    """
    return next(iter(ordered_dict.values()))


def get_progress():
    """Returns a float (from 0.0 to 1.0) describing the amount of the
        download that has completed. This value will remain at 0.0 until the
        first byte of plaintext is pushed to the download target."""


def get_file_metadata(root):
    """Read and parse ReSpecTh XML file metadata (file author, version, etc.)

    Parameters
    ----------
    root : ``etree.Element``
        root of ReSpecTh XML file

    Returns
    -------
    properties : dict
        Dictionary with file metadata

    """
    properties = {}
    properties['file-authors'] = [{'name': '', 'ORCID': ''}]
    try:
        properties['file-authors'][0]['name'] = root.find('fileAuthor').text
    except AttributeError:
        print('Warning: no fileAuthor given')
    properties['file-version'] = '(1, 0)'
    elem = root.find('fileVersion')
    if elem is None:
        print('Warning: no fileVersion element')
    try:
        version = int(elem.find('major').text), int(elem.find('minor').text)
    except AttributeError:
        print('Warning: missing fileVersion major/minor')
    properties['file-version'] = str(version)
    properties['reference'] = {}
    elem = root.find('bibliographyLink')
    try:
        properties['reference']['citation'] = elem.attrib['preferredKey']
    except KeyError:
        print('Warning: missing preferredKey attribute in bibliographyLink')
    try:
        properties['reference']['doi'] = elem.attrib['doi']
    except KeyError:
        print('Warning: missing doi attribute in bibliographyLink')
    return properties


def duplicate():
    """Duplicate selected control points

    """
    pass


def _coerce_client_id(client_id):
    """
    Ensure the provided client ID is a byte string. If a text string is
    provided, it is encoded as UTF-8 bytes.

    :param client_id: :class:`bytes` or :class:`str` instance
    """
    if isinstance(client_id, type(u'')):
        client_id = client_id.encode('utf-8')
    if not isinstance(client_id, bytes):
        raise TypeError(
            '{!r} is not a valid consumer group (must be str or bytes)'.
            format(client_id))
    return client_id


@staticmethod
def _generate_create_dict(record, record_type, data, ttl, **kwargs):
    """Returns a dict appropriate to pass into Dns_Domain_ResourceRecord::createObject"""
    resource_record = {'host': record, 'data': data, 'ttl': ttl, 'type':
        record_type}
    for key, value in kwargs.items():
        resource_record.setdefault(key, value)
    return resource_record


def ge_dsm_precomp(point):
    """
    void ge_dsm_precomp(ge_dsmp r, const ge_p3 *s)
    :param point:
    :return:
    """
    return point


def getServerInfo(pbclient=None, dc_id=None):
    """ gets info of servers of a data center"""
    if pbclient is None:
        raise ValueError("argument 'pbclient' must not be None")
    if dc_id is None:
        raise ValueError("argument 'dc_id' must not be None")
    server_info = []
    servers = pbclient.list_servers(dc_id, 1)
    for server in servers['items']:
        props = server['properties']
        info = dict(id=server['id'], name=props['name'], state=server[
            'metadata']['state'], vmstate=props['vmState'])
        server_info.append(info)
    return server_info


def p_dictorsetmaker_star2_2(p):
    """dictorsetmaker_star2 : dictorsetmaker_star2 COMMA test"""
    keys, values = p[1]
    p[0] = keys, values + [p[3]]


@staticmethod
def _parse_physical_dn(dn):
    """
        Handles DNs that look like the following:
        topology/pod-1/node-103/sys/phys-[eth1/12]
        """
    name = dn.split('/')
    pod = name[1].split('-')[1]
    node = name[2].split('-')[1]
    module = name[4].split('[')[1]
    interface_type = module[:3]
    module = module[3:]
    port = name[5].split(']')[0]
    return interface_type, pod, node, module, port


def descope_subscription_ids_set(subset_key):
    """Descope subscriptions set with '.'

    :returns: (queue, project)
    """
    tokens = subset_key.split('.')
    return tokens[1] or None, tokens[0] or None


@classmethod
def from_emlines(cls, emlines, vlim=None, **kwargs):
    """Instantiate from a list of EmLines

        Parameters
        ----------
        emlines : list
          List of EmLine objects
        vlim : list, optional
          Velocity limits for the system
          If not set, the first components sets vlim
        """
    init_eml = emlines[0]
    slf = cls(init_eml.attrib['coord'], init_eml.z, vlim=vlim)
    if slf.chk_emline(init_eml):
        slf._emlines.append(init_eml)
    else:
        raise IOError('Bad component input')
    for emline in emlines[1:]:
        slf.add_emline(emline)
    return slf


@classmethod
def is_supported(cls, currency):
    """Check if currency is supported"""
    if currency in cls._SUPPORTED_CURRENCIES:
        return True
    else:
        return False