@staticmethod
def _compute_bi(c_final, asset_bounds_i):
    """
        Calculates which bound value to assign to a bounded asset - lower bound or upper bound.

        :param c_final: (float) a value calculated using the covariance matrices of free weights.
                          Refer to https://pdfs.semanticscholar.org/4fb1/2c1129ba5389bafe47b03e595d098d0252b9.pdf for
                          more information.
        :param asset_bounds_i: (list) a list containing the lower and upper bound values for the ith weight
        :return: bounded weight value
        """
    if c_final > 0:
        return asset_bounds_i[1][0]
    return asset_bounds_i[0][0]


def __new__(cls, state, hint=None, metric=None):
    """Creates a Result object.

        :param state: state object
        :param hint: reason why this result arose
        :param metric: reference to the
            :class:`~nagiosplugin.metric.Metric` from which this result
            was derived
        """
    return tuple.__new__(cls, (state, hint, metric))


@staticmethod
def _sanitize_response(response):
    """
        Clean up the response string
        """
    text = response.text.strip()
    if text[-1] == ',':
        return text[0:-1]
    return text


def elevation_gain(elevations, isMiles=True, upthreshold=8, downthreshold=8,
    debug=False):
    """
    calculate elevation gain over a series of elevation points

    NOTE: thresholds of 8 meters approximately matches strava

    :param elevations: list of elevation points in meters
    :param isMiles:  if True return feet, if False return m
    :param upthreshold: threshold of increase when to decide climbing, meters
    :param downthreshold: threshold of decrease when to decide descending, meters
    :param debug: if True, return tuple with gain, debuginfo
    :rtype: gain[, debuginfo] - gain in meters or feet depending on isMiles
    """
    if debug:
        debuginfo = ['ele,state,highup,lowdown,totclimb\n']
    state = 'unknown'
    thisel = elevations[0]
    highup = thisel
    lowdown = thisel
    totclimb = 0.0
    if debug:
        debuginfo.append('{},{},{},{},{}\n'.format(thisel, state, highup,
            lowdown, totclimb))
    for thisel in elevations[1:]:
        if state == 'unknown':
            if thisel >= highup + upthreshold:
                state = 'climbing'
                highup = thisel
            elif thisel <= lowdown - downthreshold:
                state = 'descending'
                lowdown = thisel
        elif state == 'climbing':
            if thisel > highup:
                highup = thisel
            elif thisel <= highup - downthreshold:
                state = 'descending'
                totclimb += highup - lowdown
                lowdown = thisel
        elif state == 'descending':
            if thisel < lowdown:
                lowdown = thisel
            elif thisel >= lowdown + upthreshold:
                state = 'climbing'
                highup = thisel
        if debug:
            debuginfo.append('{},{},{},{},{}\n'.format(thisel, state,
                highup, lowdown, totclimb))
    if state == 'climbing':
        totclimb += highup - lowdown
        if debug:
            debuginfo.pop()
            debuginfo.append('{},{},{},{},{}\n'.format(thisel, state,
                highup, lowdown, totclimb))
    if isMiles:
        totclimb = totclimb / 1609.344 * 5280
    if debug:
        return totclimb, debuginfo
    return totclimb


def allowGroupRemove(principal_id, group_id):
    """True iff this plugin will allow removing a certain principal from a
        certain group."""


def format_long_string(string, max_length):
    """ Format a string so it fits in column of a specific width.

    Parameters
    ----------
    string : str
        String to format
    max_length : int
        Maximum length of returned string

    Returns
    -------
    str
        Formatted string
    """
    if len(string) > max_length:
        string = string[:max_length - 3]
        string += '...'
    return string


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

        :param str val:
        :rtype: PathOrLink
        """
    return cls('path', val)


def nbconvert(code):
    """Create Jupyter Notebook code

    Return dict in ipynb format
    Arguments:
    code -- code string separated by \\n
    """
    cells = []
    for cell in code.split('\n# <codecell>\n'):
        cells.append({'cell_type': 'code', 'execution_count': None,
            'metadata': {'collapsed': True}, 'outputs': [], 'source': [cell]})
    result = {'cells': cells, 'nbformat': 4, 'nbformat_minor': 0,
        'metadata': {'kernelspec': {'display_name': 'Python 2', 'language':
        'python', 'name': 'python2'}, 'language_info': {'codemirror_mode':
        {'name': 'ipython', 'version': 2}, 'file_extension': '.py',
        'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter':
        'python', 'pygments_lexer': 'ipython2', 'version': '2.7.6'}}}
    return result


def ref(name: str, value=None, _store={}):
    """
    A simple YAML like reference utility.
    It to easily store a value under a given key and return it.

    :param name: name of the reference
    :param value: new value of the reference (if value isn't None)
    :param _store: dict to store everything in
    :return: the value of the reference
    """
    if value is not None:
        _store[name] = value
    return _store[name]


def pad(s, n, p=' ', sep='|', align='left'):
    """
    Returns a padded string.
    s = string to pad
    n = width of string to return
    sep = separator (on end of string)
    align = text alignment, "left", "center", or "right"
    """
    if align == 'left':
        return (s + p * n)[:n] + sep
    elif align == 'center':
        pos = n + len(s) / 2 - n / 2
        return (p * n + s + p * n)[pos:pos + n] + sep
    elif align == 'right':
        return (p * n + s)[-n:] + sep


def use(app=None, gl=None):
    """ Set the usage options for vispy

    Specify what app backend and GL backend to use.

    Parameters
    ----------
    app : str
        The app backend to use (case insensitive). Standard backends:
            * 'PyQt4': use Qt widget toolkit via PyQt4.
            * 'PyQt5': use Qt widget toolkit via PyQt5.
            * 'PySide': use Qt widget toolkit via PySide.
            * 'PySide2': use Qt widget toolkit via PySide2.
            * 'PyGlet': use Pyglet backend.
            * 'Glfw': use Glfw backend (successor of Glut). Widely available
              on Linux.
            * 'SDL2': use SDL v2 backend.
            * 'osmesa': Use OSMesa backend
        Additional backends:
            * 'ipynb_webgl': run vispy from a Jupyter notebook (not fully
               functional)
            * 'ipynb_vnc': render in a Jupyter notebook via a VNC approach
              (experimental)
    gl : str
        The gl backend to use (case insensitive). Options are:
            * 'gl2': use Vispy's desktop OpenGL API.
            * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for
              testing.
            * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle.
              Availability of ES 2.0 is larger for Windows, since it relies
              on DirectX.
            * 'gl+': use the full OpenGL functionality available on
              your system (via PyOpenGL).

    Notes
    -----
    If the app option is given, ``vispy.app.use_app()`` is called. If
    the gl option is given, ``vispy.gloo.use_gl()`` is called.

    If an app backend name is provided, and that backend could not be
    loaded, an error is raised.

    If no backend name is provided, Vispy will first check if the GUI
    toolkit corresponding to each backend is already imported, and try
    that backend first. If this is unsuccessful, it will try the
    'default_backend' provided in the vispy config. If still not
    succesful, it will try each backend in a predetermined order.

    See Also
    --------
    vispy.app.use_app
    vispy.gloo.gl.use_gl
    """
    if app is None and gl is None:
        raise TypeError('Must specify at least one of "app" or "gl".')
    if app == 'ipynb_webgl':
        app = 'headless'
        gl = 'webgl'
    if app == 'osmesa':
        from ..util.osmesa_gl import fix_osmesa_gl_lib
        fix_osmesa_gl_lib()
        if gl is not None:
            raise ValueError('Do not specify gl when using osmesa')
    if gl:
        from .. import gloo, config
        config['gl_backend'] = gl
        gloo.gl.use_gl(gl)
    if app:
        from ..app import use_app
        use_app(app)


def bake_animation():
    """Update the audio animation cache

    """
    pass


def _get_win_folder_from_registry(csidl_name):
    """This is a fallback technique at best. I'm not sure if using the
    registry for this guarantees us the correct answer for all CSIDL_*
    names.
    """
    import winreg as _winreg
    shell_folder_name = {'CSIDL_APPDATA': 'AppData', 'CSIDL_COMMON_APPDATA':
        'Common AppData', 'CSIDL_LOCAL_APPDATA': 'Local AppData'}[csidl_name]
    key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
        'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders'
        )
    dir, type = _winreg.QueryValueEx(key, shell_folder_name)
    return dir


def bake():
    """Bake fluid simulation

    """
    pass


@classmethod
def get_logout_location_to(cls, request):
    """Return the default path after the logout"""
    return '/'


def is_file_genpath(genpath):
    """
    Determine whether the genpath is a file (e.g., '/stdout') or not (e.g., 'command')
    :param genpath: a generalized path
    :return: a boolean value indicating if the genpath is a file.
    """
    return genpath.startswith('/')


def outputMarkdown(markdown_cont, output_file):
    """
    Writes to an output file if `outfile` is a valid path.

    """
    if output_file:
        with open(output_file, 'w') as out:
            out.write(markdown_cont)


def seconds_to_timestamp(seconds):
    """
    timestamp hh:mm:ss derived from seconds since midnight
    """
    h = int(seconds / 60 ** 2)
    seconds = seconds - 60 ** 2 * h
    m = int(seconds / 60)
    seconds = seconds - 60 * m
    s = int(seconds)
    timestamp = '{0:2d}:{1:2d}:{2:2d}'.format(h, m, s)
    timestamp = timestamp.replace(' ', '0')
    return timestamp


def div(p1, p2):
    """Divergence of P=(p1, p2) using backward differece scheme:

    div(P) = p1_x + p2_y

    Parameters
    ----------
    p1 : ~numpy.ndarray
        The first component to be processed.
    p2 : ~numpy.ndarray
        The second component to be processed.

    Returns
    -------
    div_p : ~numpy.ndarray
        The divergence of P=(p1, p2).

    """
    p1_x = p1.copy()
    p1_x[:, :-1] -= p1[:, 1:]
    p2_y = p2.copy()
    p2_y[:-1, :] -= p2[1:, :]
    div_p = p1_x + p2_y
    return div_p


@staticmethod
def get_argparser_positional_args():
    """
        Yield tuples (name, opts) for each positional argument.

        It's almost impossible to remove positional args from argparser, so
        we use method here to be able to override it in subclasses.

        """
    return ()


def tag_strings_match(tag_string, mandatory_tag):
    """true if tag string matches the mandatory tag,
    the comparison is not symmetric if tag_string ends with a
    wildcard (asterisk)
    """
    if mandatory_tag.endswith('*'):
        return tag_string.startswith(mandatory_tag[:-1])
    else:
        return tag_string == mandatory_tag


def single_or_plural(single, plural, n, include_count=False):
    """Little helper to spit out single or plural version of a word.
    """
    ni = int(n)
    msg = '%d ' % ni if include_count else ''
    if ni > 1 or ni == 0:
        return msg + plural
    else:
        return msg + single


def getid(obj):
    """Return id if argument is a Resource.

    Abstracts the common pattern of allowing both an object or an object's ID
    (UUID) as a parameter when dealing with relationships.
    """
    try:
        if obj.uuid:
            return obj.uuid
    except AttributeError:
        pass
    try:
        return obj.id
    except AttributeError:
        return obj


def default_path():
    """Return default repository path."""
    from git import InvalidGitRepositoryError
    from renku.core.commands.git import get_git_home
    try:
        return get_git_home()
    except InvalidGitRepositoryError:
        return '.'


def project_geometric_phantom_image_filter(*args, **kwargs):
    """Procedural interface for ProjectGeometricPhantomImageFilter"""
    import itk
    instance = itk.ProjectGeometricPhantomImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


@staticmethod
def get_device(device_id):
    """! @brief Return the DAPAccess device with the give ID"""
    raise NotImplementedError()


def fromBasicServiceEndpoint(cls, endpoint):
    """Create a new instance of this class from the endpoint
        object passed in.

        @return: None or OpenIDServiceEndpoint for this endpoint object"""
    type_uris = endpoint.matchTypes(cls.openid_type_uris)
    if type_uris and endpoint.uri is not None:
        openid_endpoint = cls()
        openid_endpoint.parseService(endpoint.yadis_url, endpoint.uri,
            endpoint.type_uris, endpoint.service_element)
    else:
        openid_endpoint = None
    return openid_endpoint


def csv_source_settings(column_configs):
    """
    Details about the file to load.
    Used for parsing the CSV during load.
    """
    return {'filePath': 'from dataframe', 'delimiter': ',', 'lineSeparator':
        '\n', 'quote': '"', 'quoteEscape': '"', 'columnConfigs': column_configs
        }


def get_rst_title(title, character):
    """Permit to get a title formatted as ReStructuredText test (underlined with a chosen character)."""
    return '%s\n%s\n' % (title, character * len(title))


def int_to_bytes(n: int, byteorder: str='big') ->bytes:
    """
    Converts an int `n` to bytes.

    Parameters:
        n         (int): Integer.
        byteorder (str): Desired byte order ('big' or 'little').

    Returns:
        bytes: Bytes representation of `n`.
    """
    return n.to_bytes(max((n.bit_length() + 7) // 8, 1), byteorder)


def prettify_xml(xmlstr):
    """add indentation to create pretty xml"""
    indent = 1
    for i in range(len(xmlstr)):
        item = xmlstr[i]
        if item.startswith('</'):
            indent -= 1
            tag = xmlstr[i - 1].startswith('<')
            yield tag * ' ' * indent * 4 + item + '\n'
        elif item.startswith('<'):
            tag = xmlstr[i + 1].startswith('<')
            yield ' ' * indent * 4 + item + tag * '\n'
            indent += 1
        else:
            yield item
    raise StopIteration()


def get_class(m):
    """Import class from string

    :param m: string or class to be imported
    :type m: str or class
    :rtype: class

    >>> get_class('microtc.textmodel.TextModel')
    <class 'microtc.textmodel.TextModel'>
    """
    import importlib
    if isinstance(m, str):
        a = m.split('.')
        p = importlib.import_module('.'.join(a[:-1]))
        return getattr(p, a[-1])
    return m


@classmethod
def list_by_portgroup_id(cls, context, portgroup_id, limit=None, marker=
    None, sort_key=None, sort_dir=None, owner=None):
    """Return a list of Port objects associated with a given portgroup ID.

        :param context: Security context.
        :param portgroup_id: the ID of the portgroup.
        :param limit: maximum number of resources to return in a single result.
        :param marker: pagination marker for large data sets.
        :param sort_key: column to sort results by.
        :param sort_dir: direction to sort. "asc" or "desc".
        :param owner: a node owner to match against
        :returns: a list of :class:`Port` object.

        """
    db_ports = cls.dbapi.get_ports_by_portgroup_id(portgroup_id, limit=
        limit, marker=marker, sort_key=sort_key, sort_dir=sort_dir, owner=owner
        )
    return cls._from_db_object_list(context, db_ports)


def set_encrypted_uploadable(u):
    """Provide a source of encrypted upload data. 'u' must implement
        IEncryptedUploadable.

        When this is called, the IEncryptedUploadable will be queried for its
        length and the storage_index that should be used.

        This returns a Deferred that fires with this Encoder instance.

        This must be performed before start() can be called.
        """


def isfloat(value):
    """Check if value is float."""
    try:
        float(value)
        return True
    except ValueError:
        return False


def DownloadData(Dir, Var, Startdate, Enddate, latlim, lonlim, Waitbar,
    cores, TimeCase, CaseParameters):
    """This is main interface.

    Args:
        status (dict): Status.
        conf (dict): Configuration.
    """
    status_cod = -1
    return status_cod


@classmethod
def globalStatusBar(cls):
    """
        Class method to get a reference to a global status bar.

        The global status bar is the status bar of the main window. If
        no such window exists and the web browser was called from the eric IDE,
        the status bar of the IDE is returned.

        @return reference to the global status bar
        @rtype QStatusBar
        """
    if cls.BrowserWindows:
        return cls.BrowserWindows[0].statusBar()
    else:
        return None


def iterup(h5group, includeself=True):
    """
    Iterator which yields all parent h5py.Group's up till root

    :param h5py.Group h5group:
    :param bool includeself:
    :returns generator:
    """
    if includeself:
        yield h5group
    while h5group.parent != h5group:
        h5group = h5group.parent
        yield h5group


def Capitalize(v):
    """Capitalise a string.

    >>> s = Schema(Capitalize)
    >>> s('hello world')
    'Hello world'
    """
    return str(v).capitalize()


def save_fits(cont, path):
    """
    Create a new FITS file from a container.

    Parameters
    ----------
    cont : :class:`~acalib.Container`

    path : str
    	Path to new FITS file to be created from the container.
    """
    cont.save_fits(path)


@classmethod
def disable(cls):
    """Disables the accessibility domain.
        """
    return cls.build_send_payload('disable', {}), None


def PrefixeGrandeur(mantisse, prefixe=''):
    """mantisse -> type float
prefixe  -> type str

retourne la valeur décimale correspondante (type float)

Le symbole du préfixe doit être une des valeurs :
'p' pico, 'n', 'u' ou 'µ' micro, 'm', 'k', 'M' méga, 'G', 'T', '' par défaut

Exemple :
    from dcelectricity import dc_fr as dc
    dc.PrefixeGrandeur(20, 'm')  # retourne 0.02
    dc.PrefixeGrandeur(50, 'k')  # retourne 50000
    dc.PrefixeGrandeur(-10000)   # retourne -10000
"""
    prefixes = {'': 1, 'p': 1e-12, 'n': 1e-09, 'u': 1e-06, 'µ': 1e-06, 'm':
        0.001, 'k': 1000.0, 'M': 1000000.0, 'G': 1000000000.0, 'T':
        1000000000000.0}
    return mantisse * prefixes[prefixe]


def target_move_down():
    """Move particle target down in the list

    """
    pass


def timestep(units='metal'):
    """
    Returns the default timestep value for a LAMMPS unit style option.

    Parameters
    ----------
    units : str, optional
        The LAMMPS unit option.  Default value is 'metal'

    Returns
    -------
    float
        The default timestep value.
    """
    if units == 'lj':
        return 0.005
    elif units == 'real':
        return 1.0
    elif units == 'metal':
        return 0.001
    elif units == 'si':
        return 1e-08
    elif units == 'cgs':
        return 1e-08
    elif units == 'electron':
        return 0.001
    elif units == 'micro':
        return 2.0
    elif units == 'nano':
        return 0.00045
    else:
        raise ValueError('units ' + units + ' not supported')


def msg_unknownresponse():
    """Return the message that is rendered when a javascript request gets
        a response from a different source than a tabbed view.

        This happens when a redirect occurs, for example a redirect to a login
        form due to a session timeout.
        """


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 basename(path):
    """Use for Windows compatibility.

    """
    pass


@classmethod
def get(cls, *args, **kwargs):
    """Get an Association instance"""
    raise NotImplementedError('Implement in subclass')


def find_function_info(func, spec, args):
    """Return function meta-data in a tuple.

    (name, type)"""
    module = getattr(func, '__module__', None)
    name = getattr(func, '__name__', None)
    self = getattr(func, '__self__', None)
    cname = None
    if self:
        cname = self.__name__
    elif len(spec.args) and spec.args[0] == 'self':
        cname = args[0].__class__.__name__
    elif len(spec.args) and spec.args[0] == 'cls':
        cname = args[0].__name__
    if name:
        qname = []
        if module and module != '__main__':
            qname.append(module)
            qname.append('.')
        if cname:
            qname.append(cname)
            qname.append('.')
        qname.append(name)
        name = ''.join(qname)
    return name, None


def _validate_label_map(label_map):
    """Checks if a label map is valid.

    Args:
      label_map: StringIntLabelMap to validate.

    Raises:
      ValueError: if label map is invalid.
    """
    for item in label_map.item:
        if item.id < 0:
            raise ValueError('Label map ids should be >= 0.')
        if (item.id == 0 and item.name != 'background' and item.
            display_name != 'background'):
            raise ValueError(
                'Label map id 0 is reserved for the background label')


def read_radolan_binary_array(fid, size):
    """Read binary data from file given by filehandle

    Parameters
    ----------
    fid : object
        file handle
    size : int
        number of bytes to read

    Returns
    -------
    binarr : string
        array of binary data
    """
    binarr = fid.read(size)
    fid.close()
    if len(binarr) != size:
        raise IOError(
            '{0}: File corruption while reading {1}! \nCould not read enough data!'
            .format(__name__, fid.name))
    return binarr


def delete_application_version(ApplicationName=None, VersionLabel=None,
    DeleteSourceBundle=None):
    """
    Deletes the specified version from the specified application.
    See also: AWS API Documentation

    Examples
    The following operation deletes an application version named 22a0-stage-150819_182129 for an application named my-app:
    Expected Output:

    :example: response = client.delete_application_version(
        ApplicationName='string',
        VersionLabel='string',
        DeleteSourceBundle=True|False
    )

    :type ApplicationName: string
    :param ApplicationName: [REQUIRED]
            The name of the application to which the version belongs.

    :type VersionLabel: string
    :param VersionLabel: [REQUIRED]
            The label of the version to delete.

    :type DeleteSourceBundle: boolean
    :param DeleteSourceBundle: Set to true to delete the source bundle from your storage bucket. Otherwise, the application version is deleted only from Elastic Beanstalk and the source bundle remains in Amazon S3.

    :return: response = client.delete_application_version(
        ApplicationName='my-app',
        DeleteSourceBundle=True,
        VersionLabel='22a0-stage-150819_182129',
    )

    print(response)

    """
    pass


@staticmethod
def address(peers):
    """Return rank in peers communicator"""
    return peers.Get_rank()


def store(filename, fileobj):
    """ Store fileobj as filename into the storage. """


@staticmethod
def is_unsure():
    """
        Verify if the interface state is Unsure
        """
    return True


def add_entry_to_stats(results, project_id, episode_id, task_type_id,
    task_status_id, task_status_short_name, task_status_color, task_count,
    entity_nb_frames):
    """
    Add to stats results, information of given count for given entity, task
    type and task satus.
    """
    episode_id = str(episode_id)
    task_type_id = str(task_type_id)
    task_status_id = str(task_status_id)
    results.setdefault(episode_id, {})
    results[episode_id].setdefault(task_type_id, {})
    results[episode_id][task_type_id].setdefault(task_status_id, {})
    results[episode_id][task_type_id][task_status_id] = {'name':
        task_status_short_name, 'color': task_status_color, 'count':
        task_count, 'frames': entity_nb_frames or 0}
    results[episode_id].setdefault('all', {})
    results[episode_id]['all'].setdefault(task_status_id, {'name':
        task_status_short_name, 'color': task_status_color, 'count': 0,
        'frames': 0})
    results[episode_id]['all'][task_status_id]['count'] += task_count or 0
    results[episode_id]['all'][task_status_id]['frames'
        ] += entity_nb_frames or 0


@staticmethod
def p_var_forbidden_comb_criterion_optional_list(p):
    """var_forbidden_comb_criterion_optional_list : var_forbidden_comb_criterion_optional
                                                      | var_forbidden_comb_criterion_optional var_forbidden_comb_criterion_optional_list"""
    try:
        p[0] = p[1] + p[2]
    except IndexError:
        p[0] = p[1]


def t_CPP_COMMENT1(t):
    """(/\\*(.|\\n)*?\\*/)"""
    ncr = t.value.count('\n')
    t.lexer.lineno += ncr
    t.type = 'CPP_WS'
    t.value = '\n' * ncr if ncr else ' '
    return t


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

        :param HasTeamSharedDropboxValue val:
        :rtype: FeatureValue
        """
    return cls('has_team_shared_dropbox', val)


def psi_Na_Cl_F_MP98(T, P):
    """c-a-a': sodium chloride fluoride [MP98]."""
    psi = 0.0023
    valid = T == 298.15
    return psi, valid


def _log(attrs, inputs, proto_obj):
    """Elementwise log of input array."""
    return 'log', attrs, inputs


def user_metrics_query(table_name='%(table_name)s'):
    """
    Create aggregated features per user, day and hour. E.g. count all
    outgoing sms to create an indicator for that time period called
    og_sms. Incoming events are abbreviated with 'ic'.

    Inputs
    ------
    table_name : Name of the table the query is supposed to run on,
                 defaulting to '%(table_name)s', i.e. no substitution.

    Output
    ------
    Aggregated event counts per user, day and hour.
    """
    query = """
        SELECT
          user_id,
          day,
          hour,
          SUM(IF(direction = 'out' AND interaction = 'text', value, NULL))
           AS og_sms,
          SUM(IF(direction = 'in' AND interaction = 'text', value, NULL))
           AS ic_sms,
          SUM(IF(direction = 'out' AND interaction = 'call', value, NULL))
           AS og_calls,
          SUM(IF(direction = 'in' AND interaction = 'call', value, NULL))
           AS ic_calls,
          SUM(IF(direction = 'out' AND interaction = 'call', vol, NULL))
           AS og_vol,
          SUM(IF(direction = 'in' AND interaction = 'call', vol, NULL))
           AS ic_vol
        FROM
        (
          SELECT
            caller_id as user_id,
            DATE(datetime) as day,
            HOUR(datetime) as hour,
            interaction,
            direction,
            COUNT(*) as value,
            SUM(call_duration) as vol
          FROM %(table_name)s
          GROUP BY caller_id, day, hour, interaction, direction
        )
        GROUP BY user_id, day, hour
    """
    return query % {'table_name': table_name}


def get_adapters(objects, provided, context=None):
    """Look for all matching adapters to a provided interface for objects

        Return a list of adapters that match. If an adapter is named, only the
        most specific adapter of a given name is returned.

        If context is None, an application-defined policy is used to choose
        an appropriate service manager from which to get an 'Adapters'
        service.

        If 'context' is not None, context is adapted to IServiceService,
        and this adapter's 'Adapters' service is used.
        """


def _normalize_header_name(name: str) ->str:
    """
    According to rfc https://www.ietf.org/rfc/rfc2616.txt header names are case insensitive,
    thus they can be normalized to ease usage of Headers class.
    :param name:
    :return:
    """
    name = name.lower()
    if name.startswith('http_'):
        name = name[5:]
    return name.replace('_', '-')


@classmethod
def get_pretty_notification_info(cls, name, filename, line):
    """
        Return a sentence describing when this exception was already seen.
        """
    try:
        return cls.query.filter_by(name=name, filename=filename, line=line
            ).one().pretty_notification_info
    except:
        return 'It is the first time this exception has been seen.\n'


@classmethod
def get_dx_nodes(cls, node, parent_path='', pos=0):
    """
        Creates a list of XmlXdiff.XTypes.DiffxNode from lxml root element for instance.
        """
    cls.dx_nodes = []
    cls.walk(node, parent_path, pos)
    return cls.dx_nodes


def split_files(files, split_train, split_val, use_test):
    """Splits the files along the provided indices
    """
    files_train = files[:split_train]
    files_val = files[split_train:split_val] if use_test else files[split_train
        :]
    li = [(files_train, 'train'), (files_val, 'val')]
    if use_test:
        files_test = files[split_val:]
        li.append((files_test, 'test'))
    return li


def set_elem_attr(element, attrib, data):
    """Set a tag for an XML element if the value is not empty."""
    if attrib in data and data[attrib]:
        element.set(attrib, data[attrib])


def update_document_version(DocumentId=None, VersionId=None, VersionStatus=None
    ):
    """
    Changes the status of the document version to ACTIVE.
    Amazon WorkDocs also sets its document container to ACTIVE. This is the last step in a document upload, after the client uploads the document to an S3-presigned URL returned by  InitiateDocumentVersionUpload .
    See also: AWS API Documentation

    :example: response = client.update_document_version(
        DocumentId='string',
        VersionId='string',
        VersionStatus='ACTIVE'
    )

    :type DocumentId: string
    :param DocumentId: [REQUIRED]
            The ID of the document.

    :type VersionId: string
    :param VersionId: [REQUIRED]
            The version ID of the document.

    :type VersionStatus: string
    :param VersionStatus: The status of the version.

    """
    pass


def apply_pose(pose_index: int=-1):
    """Apply specified Pose Library pose to the rig

    :param pose_index: Pose, Index of the pose to apply (-2 for no change to pose, -1 for poselib active pose)
    :type pose_index: int
    """
    pass


def multi_run_output(hubs, factor):
    """
    Function for collecting the correct info from the multiple EHub models and combining them into one set of results
    :param hubs: the EHub models now containing their solutions
    :param factor: If the models are samples for larger time scales
    """
    absolute_cost = hubs[0].solution_dict['investment_cost']
    for result in hubs:
        absolute_cost += result.solution_dict['maintenance_cost'
            ] * factor + result.solution_dict['operating_cost'] * factor
    return absolute_cost


@classmethod
def deserialize(cls, iodata):
    """
        Take the given IOData and return an instance of the described class, initialized with the data stored in
        io_data.

        Parameters
        ----------
        iodata: IOData

        Returns
        -------
        StoredSweep
        """
    return cls(**iodata.as_kwargs())


@classmethod
def base_url(klass, space_id, webhook_id, **kwargs):
    """
        Returns the URI for the webhook health.
        """
    return 'spaces/{0}/webhooks/{1}/health'.format(space_id, webhook_id)


def catalogMapping(domain, retJson=True):
    """ Return message catalog as a mapping.

        @param domain
        domain of the message catalog

        @param retJson
        format return value to json format or not( default True )

        @return
        a dict with the following format:
        {
            'success': True,
            'msg': 'Get message catalog mapping success.',
            'mapping': {
                u'text1': u'translated text1',
                u'text2': u'translated text2',
                ...
            }
        }

        """


def __ne__(A, other):
    """Returns true if both objects are not equal"""
    return not A == other


@classmethod
def from_json(cls, data, json_schema_class=None):
    """ JSON deserialization method that retrieves a genome instance from its json representation

        If specific json schema is provided, it is utilized, and if not, a class specific is used
        """
    schema = (cls.json_schema if json_schema_class is None else
        json_schema_class())
    return schema.load(data)


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


def get_name(func):
    """
    Returns the name of a callable.

    It handles different types of callable: function, callable object with
    ``__call__`` method and callable objects that provide their name in the
    ``name`` attributes.

    :type func: callable.
    :returns:
        :rtype: str.

    """
    prefix = func.__module__
    if not callable(func):
        raise ValueError('{} is not callable'.format(func))
    if hasattr(func, 'name'):
        name = func.name
    elif hasattr(func, '__name__'):
        name = func.__name__
    else:
        name = func.__class__.__name__
    return '.'.join([prefix, name])


def esc2(string):
    """
    Escape double quotes
    """
    return string.replace('"', '\\"')


def clear_app_reverse_cache():
    """
    Clear the cache for the :func:`app_reverse` function.
    This only has to be called when doing bulk update/delete actions that circumvent the individual model classes.
    """
    from django.core.cache import cache
    from fluent_pages.extensions import page_type_pool
    for model in page_type_pool.get_model_classes():
        cache.delete('fluent_pages.instance_of.{0}'.format(model.__name__))


def merge_images(input_filepath1: str='', input_filepath2: str='',
    output_filepath: str=''):
    """Combine OpenEXR multilayer images rendered with different sampleranges into one image with reduced noise

    :param input_filepath1: Input Filepath, File path for image to merge
    :type input_filepath1: str
    :param input_filepath2: Input Filepath, File path for image to merge
    :type input_filepath2: str
    :param output_filepath: Output Filepath, File path for merged image
    :type output_filepath: str
    """
    pass


def number_freq_plots(runs, map_label):
    """Calculate the number of plots needed for allfreq plots and frequency
    histogram plots

    """
    num_cpu_plots = len(map_label)
    has_devfreq_data = False
    for run in runs:
        if len(run.devfreq_in_power.data_frame) > 0:
            has_devfreq_data = True
            break
    num_freq_plots = num_cpu_plots
    if has_devfreq_data:
        num_freq_plots += 1
    return num_freq_plots


@classmethod
def _addSupportedFilterOptions(cls, parser):
    """ Add all command line parameters for regular expression specification
        for individual fields of a resource"""
    clsName = str(cls)
    for l, s in cls._supportedFilters.items():
        parser.add_argument('--' + l, '-' + s, metavar='REGEX', help=
            """specify
            a regular expression to further narrow down on matches in the """
             + l + ' field in a ' + clsName)


def _probvec(r, out):
    """
    Fill `out` with randomly sampled probability vectors as rows.

    To be complied as a ufunc by guvectorize of Numba. The inputs must
    have the same shape except the last axis; the length of the last
    axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is
    k, then r.shape[-1] must be k-1.

    Parameters
    ----------
    r : ndarray(float)
        Array containing random values in [0, 1).

    out : ndarray(float)
        Output array.

    """
    n = r.shape[0]
    r.sort()
    out[0] = r[0]
    for i in range(1, n):
        out[i] = r[i] - r[i - 1]
    out[n] = 1 - r[n - 1]


@staticmethod
def _key(service=None, env=None):
    """Compute a key with the same format used by the Datadog agent API."""
    service = service or ''
    env = env or ''
    return 'service:' + service + ',env:' + env


def similar_values_iter(v1, v2, e=1e-06):
    """Return True if iterables v1 and v2 are nearly the same."""
    if v1 == v2:
        return True
    for v1, v2 in zip(v1, v2):
        if v1 != v2 and abs(v1 - v2) / max(abs(v1), abs(v2)) > e:
            return False
    return True


def envmap_clear():
    """Discard the environment map and free it from memory

    """
    pass


def message_retry_count(message):
    """ returns the retry_count kepts in the headers
    :param message: the message whose retries needs to be counted
    :returns the value of the retry_count from the header
    """
    return message.header_frame.headers.get('max_retry', None)


def get_code_cell(code, hidden=False):
    """Code cell containing `code` that may be `hidden`."""
    return {'cell_type': 'code', 'execution_count': 0, 'metadata': {
        'hide_input': hidden, 'trusted': True}, 'source': code, 'outputs': []}


@classmethod
def serialize(cls, *args, **kwargs):
    """
                Convert to serializable representation
            :param args: See _ser for details
            :param kwargs: See _ser for details
            :return: Json serializable representation
        """
    return cls._as_list(*cls._ser(*args, **kwargs))


def get_default_resolution_node_name():
    """
    Returns the name of the default resolution Maya node
    :return: str
    """
    return 'defaultResolution'


def psi_K_HSO4_SO4_HMW84(T, P):
    """c-a-a': potassium bisulfate sulfate [HMW84]."""
    psi = -0.0677
    valid = T == 298.15
    return psi, valid


def read_data_from_LMDB(read_db, max_to_read=None):
    """Reads data from LMDB database and returns a list of entries in
    non-human readable form. To convert them to string, use Caffe's tools
    """
    data = []
    with read_db.begin() as txn:
        if max_to_read is None:
            max_to_read = txn.stat()['entries']
        cursor = txn.cursor()
        it = cursor.iternext(keys=False, values=True)
        for counter in range(max_to_read):
            if counter % 100000 == 0:
                print('Reading entry {}'.format(counter))
            data.append(it.item())
            it.next()
    read_db.close()
    return data


def stop_rt_server(serverp):
    """ Stops our own instance of the server. """
    if serverp is not None:
        serverp.terminate()


def save_tikz(commands, path=None, baseline=0, options=None):
    """
    Save a list of tikz commands.
    """
    options = ('baseline=(O.base)' if options is None else
        'baseline=(O.base), ' + options)
    begin = ['\\begin{{tikzpicture}}[{}]\n'.format(options),
        '\\node (O) at (0, {}) {{}};\n'.format(baseline)]
    end = ['\\end{tikzpicture}\n']
    with open(path, 'w+') as file:
        file.writelines(begin + commands + end)


def add_custom_constraint(constr, constraint, ll):
    """Adds a custom range constraint

		constraint shall be on the format (name, minimum, maximum)"""
    name, minimum, maximum = constraint
    m = [minimum, maximum]
    for i in range(2):
        if type(m[i]) == str:
            if not ll is None:
                m[i] = eval(m[i], globals(), ll.__dict__)
            else:
                return
    [minimum, maximum] = m
    constr.add_named(name, None, 'user constraint', [minimum, maximum])


def reassign_root_of_initial_spectra(d, name, root, iteration,
    transition_energy, intensity, wavelength, number, cutoff):
    """
    If the file being searched is run to find the
    roots to take forward, need to know the roots!

    This function reassigns the value in the 'root'
    column to reflect this
    """
    if 'initial_spectra' in d[name]:
        d[name].pop(root)
    new_key = f'initial spectra: root {number + 1}'
    if new_key not in d[name]:
        d[name][new_key] = {}
        d[name][new_key]['peaks'] = {}
        if iteration not in d[name][new_key]['peaks']:
            d[name][new_key]['peaks'][iteration] = []
    if intensity > cutoff:
        d[name][new_key]['peaks'][iteration].append((transition_energy,
            wavelength, intensity))
    return d


def area_of_rect(l, w):
    """
    definition: func(l, w) {...}
    objective: returns you the are of a rectangle on its length and height
                A= length x width
    """
    area = l * w
    return area


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

    Like 'git describe --tags --dirty --always'.

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


def get_default_value(options):
    """
    set default value to para which was not set
    """
    if not options.type_run:
        options.type_run = 'learn'
    if not options.config_file:
        options.config_file = ''
    if not options.seed_value_begin:
        options.seed_value_begin = '1'
    if not options.search_already:
        options.search_already = 'y'
    if not options.cudaid:
        options.cudaid = '-3'
    if not options.gpu_memory_fraction:
        options.gpu_memory_fraction = '0'
    if not options.rd_pr_seed:
        options.rd_pr_seed = 'none'
    if not options.orderf_fill:
        options.orderf_fill = 'none'
    if not options.debug:
        options.debug = 'n'
    if not options.check:
        options.check = 'n'
    if not options.grid_coef_time:
        options.grid_coef_time = '10'
    if not options.cv_coef_time:
        options.cv_coef_time = '4'
    if not options.coef_ini:
        options.coef_ini = '255'
    if not options.metric_selection:
        options.metric_selection = 'roc_auc'
    if not options.parent_folder_img:
        options.parent_folder_img = 'images'
    if not options.original_data_folder:
        options.original_data_folder = 'data'
    if not options.data_name:
        options.data_name = ''
    if not options.parent_folder_results:
        options.parent_folder_results = 'results'
    if not options.save_avg_run:
        options.save_avg_run = 'n'
    if not options.save_labels:
        options.save_labels = 'n'
    if not options.save_d:
        options.save_d = 'n'
    if not options.save_w:
        options.save_w = 'n'
    if not options.suff_fini:
        options.suff_fini = 'ok'
    if not options.save_rf:
        options.save_rf = 'y'
    if not options.save_para:
        options.save_para = 'n'
    if not options.path_config_w:
        options.path_config_w = ''
    if not options.ext_data:
        options.ext_data = ''
    if not options.save_entire_w:
        options.save_entire_w = 'n'
    if not options.save_folds:
        options.save_folds = 'y'
    if not options.sound_fini:
        options.sound_fini = 'n'
    if not options.n_folds:
        options.n_folds = '10'
    if not options.test_ext:
        options.test_ext = 'n'
    if not options.run_time:
        options.run_time = '1'
    if not options.whole_run_time:
        options.whole_run_time = '1'
    if not options.preprocess_img:
        options.preprocess_img = 'none'
    if not options.pretrained_w_path:
        options.pretrained_w_path = ''
    if not options.test_size:
        options.test_size = '1'
    if not options.numfilters:
        options.numfilters = '64'
    if not options.numlayercnn_per_maxpool:
        options.numlayercnn_per_maxpool = '1'
    if not options.nummaxpool:
        options.nummaxpool = '1'
    if not options.dropout_cnn:
        options.dropout_cnn = '0'
    if not options.dropout_fc:
        options.dropout_fc = '0'
    if not options.padding:
        options.padding = 'n'
    if not options.filtersize:
        options.filtersize = '3'
    if not options.poolsize:
        options.poolsize = '2'
    if not options.model:
        options.model = 'fc_model'
    if not options.num_classes:
        options.num_classes = '1'
    if not options.epoch:
        options.epoch = '500'
    if not options.learning_rate:
        options.learning_rate = '-1'
    if not options.batch_size:
        options.batch_size = '16'
    if not options.learning_rate_decay:
        options.learning_rate_decay = '0'
    if not options.momentum:
        options.momentum = '0'
    if not options.optimizer:
        options.optimizer = 'adam'
    if not options.loss_func:
        options.loss_func = 'binary_crossentropy'
    if not options.e_stop:
        options.e_stop = '5'
    if not options.e_stop_consec:
        options.e_stop_consec = 'consec'
    if not options.svm_c:
        options.svm_c = '1'
    if not options.svm_kernel:
        options.svm_kernel = 'linear'
    if not options.rf_n_estimators:
        options.rf_n_estimators = '500'
    if not options.rf_max_features:
        options.rf_max_features = '-2'
    if not options.rf_max_depth:
        options.rf_max_depth = '-1'
    if not options.knn_n_neighbors:
        options.knn_n_neighbors = '5'
    if not options.coeff:
        options.coeff = '1'
    if not options.new_dim:
        options.new_dim = '676'
    if not options.path_vis_learn:
        options.path_vis_learn = ''
    if not options.path_data_vis_learn:
        options.path_data_vis_learn = ''
    if not options.del0:
        options.del0 = 'n'
    if not options.lr_visual:
        options.lr_visual = '100'
    if not options.label_visual:
        options.label_visual = ''
    if not options.iter_visual:
        options.iter_visual = '300'
    if not options.ini_visual:
        options.ini_visual = 'pca'
    if not options.method_lle:
        options.method_lle = 'standard'
    if not options.eigen_solver:
        options.eigen_solver = 'auto'
    if not options.cmap_vmin:
        options.cmap_vmin = '0'
    if not options.cmap_vmax:
        options.cmap_vmax = '1'
    if not options.scale_mode:
        options.scale_mode = ''
    if not options.n_quantile:
        options.n_quantile = '1000'
    if not options.min_scale:
        options.min_scale = '0'
    if not options.max_scale:
        options.max_scale = '1'
    if not options.min_v:
        options.min_v = '0'
    if not options.max_v:
        options.max_v = '1'
    if not options.num_bin:
        options.num_bin = '10'
    if not options.auto_v:
        options.auto_v = 'n'
    if not options.mode_pre_img:
        options.mode_pre_img = 'caffe'
    if not options.channel:
        options.channel = '3'
    if not options.dim_img:
        options.dim_img = '-1'
    if not options.visualize_model:
        options.visualize_model = 'n'
    if not options.algo_redu:
        options.algo_redu = 'none'
    if not options.reduc_perle:
        options.reduc_perle = '10'
    if not options.reduc_ini:
        options.reduc_ini = 'pca'
    if not options.type_emb:
        options.type_emb = 'raw'
    if not options.imp_fea:
        options.imp_fea = 'none'
    if not options.label_emb:
        options.label_emb = '0'
    if not options.emb_data:
        options.emb_data = ''
    if not options.type_bin:
        options.type_bin = ''
    if not options.perlexity_neighbor:
        options.perlexity_neighbor = '5'
    if not options.n_components_emb:
        options.n_components_emb = '2'
    if not options.shape_drawn:
        options.shape_drawn = ','
    if not options.fig_size:
        options.fig_size = '0'
    if not options.point_size:
        options.point_size = '1'
    if not options.colormap:
        options.colormap = ''
    if not options.margin:
        options.margin = '0'
    if not options.alpha_v:
        options.alpha_v = '1'
    if not options.recreate_img:
        options.recreate_img = '0'
    return options


def create_raster_datapackage():
    """Creates raster package for a path"""
    pass


def identical(image):
    """
    Return input image unchanged.

    :param numpy.array image: Should be a numpy array of an image.
    :return: Same as input
    :rtype: Same as input
    """
    return image


def metadata2csv(dataset, fname, **kwargs):
    """Writes metadata to CSV-file.

    With this function, you can write metadata

    Args:
        datamodel (pd.DataFrame): A pandas DataFrame containing metadata, where
            each row stands for one document.
        fname (str): Filename for CSV-file.

    Returns:
        None
    """
    dataset.to_csv(fname, **kwargs)


def check_item_type_uniqueness(tag, previous_tags):
    """
    Check the uniqueness of the 'item type' for an object.
    """
    fail = False
    if not tag.id:
        fail = previous_tags and tag.item_type != previous_tags[0].item_type
    else:
        fail = previous_tags.count() > 1 and tag.item_type != previous_tags[0
            ].item_type
    return fail


@classmethod
def delete(cls, path, **kwargs):
    """Issue a ``DELETE`` request."""
    return cls.request('DELETE', path, **kwargs)


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


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 ignore_det(special_directories, full_path):
    """ Determines if the current directory is to be ignored or not """
    ignore_flag = 1
    for field in special_directories:
        if full_path.startswith(field[0]):
            ignore_flag *= 0
    if ignore_flag == 1:
        return True
    else:
        return False


def two_dec_places(x, pos):
    """
    Adds 1/100th decimal to plot ticks.
    """
    return '%.2f' % x


@classmethod
def teal(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``."""
    return cls(1752220)


def _process_bgp_peers(node_dict, bgp_peer_props):
    """Return fact dict with processed bgp peer properties answer added to it."""
    bgp_peer_dict = bgp_peer_props.frame().to_dict(orient='records')
    for r in bgp_peer_dict:
        node = r.pop('Node')
        ip = r.get('Remote_IP')
        node_dict[node]['BGP']['Neighbors'][str(ip)] = r


@classmethod
def text(cls):
    """A factory method that creates a :class:`Permissions` with all
        "Text" permissions from the official Discord UI set to ``True``."""
    return cls(523328)


def master_then_spare(data):
    """Return the provided satellites list sorted as:
        - alive first,
        - then spare
        - then dead
        satellites.

    :param data: the SatelliteLink list
    :type data: list
    :return: sorted list
    :rtype: list
    """
    master = []
    spare = []
    for sdata in data:
        if sdata.spare:
            spare.append(sdata)
        else:
            master.append(sdata)
    rdata = []
    rdata.extend(master)
    rdata.extend(spare)
    return rdata


def _post_mcs_init(cls):
    """
        Callback for BaseModelMetaclass subclasses to run code just after a
        concrete Model class gets registered with SQLAlchemy.

        This is intended to be used for advanced meta options implementations.
        """


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

        :param str val:
        :rtype: ResendSecondaryEmailResult
        """
    return cls('not_pending', val)


@staticmethod
def get_val(*vals):
    """Return the first True value in `vals` list, otherwise return None."""
    for v in vals:
        if v:
            return v


def flip_top_bottom(data=None, name=None, attr=None, out=None, **kwargs):
    """

    Defined in src/operator/image/image_random.cc:L205

    Parameters
    ----------
    data : Symbol
        The input.

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def list_libraries(library_db, query_start, query_end):
    """returns a list of loaded libraries"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(library_db)
    cur = conn.cursor()
    list_libraries = (
        'SELECT Library FROM "LibraryMetadata" ORDER BY Library LIMIT ?, ?')
    cur.execute(list_libraries, (query_start, query_end))
    conn.commit()
    rows = cur.fetchall()
    conn.close()
    return rows


def strip_trailing_period(s):
    """
    Return the `s` string with trailing periods removed when needed.
    """
    if not s:
        return s
    s = s.strip()
    if not s.endswith('.'):
        return s
    if len(s) < 3:
        return s
    if s[-2].isupper():
        return s
    if s[-3] == '.':
        return s
    if s.lower().endswith(('inc.', 'corp.', 'ltd.', 'llc.', 'co.', 'llp.')):
        return s
    return s.rstrip('.')


def can_enable_dynamic(link, value):
    """
    Can the a dynamic `link` (:class:`SchemeLink`) be enabled for`value`.
    """
    return isinstance(value, link.sink_types())


@staticmethod
def calculate_property(**kwargs):
    """Main function for calculating measurement"""
    raise NotImplementedError()


def normalize(name: str) ->str:
    """Normalize a value name to a valid Python (PEP8 compliant) identifier.

    Args:
        name: The name of a value returned by MPD.

    Returns:
        The normalized name, in all lowercase with - replaced by _.
    """
    return name.lower().replace('-', '_')


def html_escape(string):
    """ Escape HTML special characters ``&<>`` and quotes ``'"``. """
    return string.replace('&', '&').replace('<', '<').replace('>',
        '>').replace('"', '"').replace("'", ''')


def format_moz_error(query, exception):
    """
    Format syntax error when parsing the original query.

    """
    line = exception.lineno
    column = exception.col
    detailed_message = str(exception)
    msg = query.split('\n')[:line]
    msg.append('{indent}^'.format(indent=' ' * (column - 1)))
    msg.append(detailed_message)
    return '\n'.join(msg)


def log(msg):
    """Log a message in the Event Viewer as an informational message"""
    import servicemanager
    servicemanager.LogInfoMsg(str(msg))


def pgettext_tip(msgid: str, msgctxt: str):
    """Try to translate the given msgid (with optional msgctxt), if tooltips’ translation is enabled.

    :param msgid: The string to translate.
    :type msgid: str
    :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).
    :type msgctxt: str
    :return:  The translated string (or msgid if no translation was found).
    """
    pass


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 edge_length_cube(V):
    """
    Calculates the edge length and surface area of a cube given the volume
    """
    a = V ** (1 / 3)
    S = 6 * a ** 2
    return a, S


def _setattr_default(obj, attr, value, default):
    """Set an attribute of an object to a value or default value."""
    if value is None:
        setattr(obj, attr, default)
    else:
        setattr(obj, attr, value)


def AUC_calc(item, TPR):
    """
    Calculate AUC/AUPR (Area under the ROC/PR curve for each class).

    :param item: TNR or PPV
    :type item : float
    :param TPR: sensitivity, recall, hit rate, or true positive rate
    :type TPR : float
    :return: AUC/AUPR as float
    """
    try:
        return (item + TPR) / 2
    except TypeError:
        return 'None'


@staticmethod
def generate(config, spec):
    """Generate Python virtualenv content."""
    spec.macros['venv_cmd'] = '{0} {1}'.format(config.python_venv.cmd, ' '.
        join(config.python_venv.flags if config.python_venv.flags else ()))
    if config.python_venv.python:
        spec.macros['venv_cmd'] = '{0} --python={1}'.format(spec.macros[
            'venv_cmd'], config.python_venv.python)
    spec.macros['venv_name'] = config.python_venv.name
    spec.macros['venv_install_dir'] = '{0}/%{{venv_name}}'.format(config.
        python_venv.path)
    spec.macros['venv_dir'] = '%{buildroot}/%{venv_install_dir}'
    spec.macros['venv_bin'] = '%{venv_dir}/bin'
    spec.macros['venv_python'] = '%{venv_bin}/python'
    spec.macros['venv_pip'
        ] = '%{{venv_python}} %{{venv_bin}}/pip install {0}'.format(' '.
        join(config.python_venv.pip_flags if config.python_venv.pip_flags else
        ()))
    spec.macros['__prelink_undo_cmd'] = '%{nil}'
    spec.globals['__os_install_post'] = (
        "%(echo '%{__os_install_post}' | sed -e 's!/usr/lib[^[:space:]]*/brp-python-bytecompile[[:space:]].*$!!g')"
        )
    spec.tags['AutoReq'] = 'No'
    spec.tags['AutoProv'] = 'No'
    spec.blocks.prep.append('mkdir -p %{buildroot}/%{venv_install_dir}')
    spec.blocks.files.append('/%{venv_install_dir}')
    spec.blocks.install.append('%{venv_cmd} %{venv_dir}')
    for requirement in config.python_venv.requirements:
        spec.blocks.install.extend(('cd %{SOURCE0}', '%{{venv_pip}} -r {0}'
            .format(requirement), 'cd -'))
    if config.python_venv.require_setup_py:
        spec.blocks.install.append('cd %{SOURCE0}')
        if config.python_venv.use_pip_install:
            spec.blocks.install.append('%{venv_pip} .')
        else:
            spec.blocks.install.append('%{venv_python} setup.py install')
        spec.blocks.install.append('cd -')
    if config.python_venv.remove_pycache:
        spec.blocks.install.append(
            'find %{venv_dir} -type d -name "__pycache__" -print0 | xargs -0 rm -rf'
            )
    spec.blocks.install.extend((
        '# RECORD files are used by wheels for checksum. They contain path names which'
        ,
        '# match the buildroot and must be removed or the package will fail to build.'
        , 'find %{buildroot} -name "RECORD" -exec rm -rf {} \\;',
        '# Change the virtualenv path to the target installation direcotry.',
        'venvctrl-relocate --source=%{venv_dir} --destination=/%{venv_install_dir}'
        ))
    if config.python_venv.strip_binaries:
        spec.blocks.install.extend((
            '# Strip native modules as they contain buildroot paths intheir debug information'
            , 'find %{venv_dir}/lib -type f -name "*.so" | xargs -r strip'))
    return spec


@classmethod
def deserialize(cls, conversation):
    """
        Deserialize a :meth:`serialized <serialize>` conversation.
        """
    return cls(**conversation)


@staticmethod
def _handle_emailauth(maildomain='', message=''):
    """ Called when SteamGuard requires authentication via e-mail.
        Asks the user to enter the code.

        Args:
            maildomain: Optional. The mail domain of the e-mail address the SteamGuard
                code is send to.
            message: Optional. A message from Steam service.

        Returns:
            A string containing the code.
        """
    print('SteamGuard requires email authentication...')
    emailauth = input(
        'Please enter the code sent to your mail address at "%s": ' %
        maildomain)
    emailauth.upper()
    return emailauth


def rubygems_api_url(name, version=None, repo='https://rubygems.org/api'):
    """
    Return a package API data URL given a name, an optional version and a base
    repo API URL.

    For instance:
    https://rubygems.org/api/v2/rubygems/action_tracker/versions/1.0.2.json

    If no version, we return:
    https://rubygems.org/api/v1/versions/turbolinks.json

    Unused:
    https://rubygems.org/api/v1/gems/mqlight.json
    """
    repo = repo.rstrip('/')
    if version:
        api_url = '{repo}/v2/rubygems/{name}/versions/{version}.json'
    else:
        api_url = '{repo}/v1/versions/{name}.json'
    return api_url.format(**locals())


def node_count(shape):
    """Total number of nodes.

    The total number of nodes in a structured grid with dimensions given
    by the tuple, *shape*. Where *shape* is the number of node rows and
    node columns.

    >>> from landlab.utils.structured_grid import node_count
    >>> node_count((3, 4))
    12
    """
    assert len(shape) == 2
    return shape[0] * shape[1]


def roundm(x, y):
    """Return x rounded up to the closest multiple of y."""
    return x if x % y == 0 else x + y - x % y


def _filter_split(values, filter_list):
    """Filter space separated list and return iterable."""
    value_set = set(values.split())
    if filter_list:
        value_set &= set(filter_list)
    return sorted(value_set)


def click_extrude():
    """Create a new bone going from the last selected joint to the mouse position

    """
    pass


def _import(subs, shared):
    """Configure the `doorstop import` subparser."""
    info = 'import an existing document or item'
    sub = subs.add_parser('import', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('path', nargs='?', help=
        'path to previously exported document file')
    sub.add_argument('prefix', nargs='?', help='prefix of document for import')
    group = sub.add_mutually_exclusive_group()
    group.add_argument('-d', '--document', nargs=2, metavar='ARG', help=
        'import an existing document by: PREFIX PATH')
    group.add_argument('-i', '--item', nargs=2, metavar='ARG', help=
        'import an existing item by: PREFIX UID')
    sub.add_argument('-p', '--parent', metavar='PREFIX', help=
        'parent document prefix for imported document')
    sub.add_argument('-a', '--attrs', metavar='DICT', help=
        'dictionary of item attributes to import')
    sub.add_argument('-m', '--map', metavar='DICT', help=
        'dictionary of custom item attribute names')


@staticmethod
def _parse_aws_index(tile_info):
    """Parses AWS index from tile info

        :param tile_info: dictionary with information about tile
        :type tile_info: dict
        :return: Index of tile on AWS
        :rtype: int
        """
    return int(tile_info['properties']['s3Path'].split('/')[-1])


def vertices_smooth_laplacian(repeat: int=1, lambda_factor: float=1.0,
    lambda_border: float=5e-05, use_x: bool=True, use_y: bool=True, use_z:
    bool=True, preserve_volume: bool=True):
    """Laplacian smooth of selected vertices

    :param repeat: Number of iterations to smooth the mesh
    :type repeat: int
    :param lambda_factor: Lambda factor
    :type lambda_factor: float
    :param lambda_border: Lambda factor in border
    :type lambda_border: float
    :param use_x: Smooth X Axis, Smooth object along X axis
    :type use_x: bool
    :param use_y: Smooth Y Axis, Smooth object along Y axis
    :type use_y: bool
    :param use_z: Smooth Z Axis, Smooth object along Z axis
    :type use_z: bool
    :param preserve_volume: Preserve Volume, Apply volume preservation after smooth
    :type preserve_volume: bool
    """
    pass


def shutdown(mgr):
    """Shut down the manager."""
    mgr.shutdown()
    mgr.join()


def zpad(keys, values, default=None):
    """zips two lits and pads the second to match the first in length"""
    keys_len = len(keys)
    values_len = len(values)
    if keys_len < values_len:
        raise ValueError('keys must be as long or longer than values')
    values += [default] * (keys_len - values_len)
    return zip(keys, values)


def get_insert_idx(pos_dict, name):
    """Return the position to insert a given function doc in a notebook."""
    keys, i = list(pos_dict.keys()), 0
    while i < len(keys) and str.lower(keys[i]) < str.lower(name):
        i += 1
    if i == len(keys):
        return -1
    else:
        return pos_dict[keys[i]]


@classmethod
def from_data(cls, data):
    """Construct a wrench from its data representation.

        Parameters
        ----------
        data : :obj:`dict`
            The data dictionary.

        Returns
        -------
        :class:`Wrench`
            The constructed wrench.

        Examples
        --------
        >>> data = {"force": [1, 2, 3], "torque": [0.1, 0.2, 0.3]}
        >>> w = Wrench.from_data(data)
        """
    force = data['force']
    torque = data['torque']
    return cls(force, torque)


def complexify_data(data):
    """
    Complexify data packed real, imag.
    """
    return data[(...), ::2] + data[(...), 1::2] * 1.0j


@staticmethod
def _get_points_to_use(data, points_per_side):
    """Get a number of points from the spectrum to use for a fit.

        Slices the list of all data points to have a list of
        points from each side of the spectrum to consider as noise.

        WARNING: The spectral data needs to be provided and/or the percentage
        to use set in a way that no actual peak lies in this range.

        Parameters
        ----------
        data: :class:`list`
            List from which points should be used on each side.

        points_per_side: :class:'int'
            How many points from each end of the list should be used.

        Returns
        -------
        points_to_use: :class:`list`
            List only containing the correct number of points from each side
            and not the points in between.
        """
    left_part = data[:points_per_side + 1]
    right_part = data[len(data) - points_per_side - 1:]
    points_to_use = left_part
    points_to_use.extend(right_part)
    return points_to_use


def p_flag_all_lazy(p):
    """flag : K_ALL K_LAZY
    """
    p[0] = [('all_lazy', ())]


@staticmethod
def translate_tariff(value, dsmr_version):
    """Convert 2/1 to normal/low depending on DSMR version."""
    if dsmr_version in ('5B',):
        if value == '0001':
            value = '0002'
        elif value == '0002':
            value = '0001'
    if value == '0002':
        return 'normal'
    if value == '0001':
        return 'low'
    return None


def describe_ip(ip_address, source='whatismyip'):
    """ a method to get the details associated with an ip address """
    if source == 'nekudo':
        source_url = 'https://geoip.nekudo.com/api/%s' % ip_address
    elif source == 'geoip':
        source_url = 'https://freegeoip.net/json/%s' % ip_address
    elif source == 'whatismyip':
        source_url = 'https://whatismyipaddress.com/ip/%s' % ip_address
    else:
        raise Exception('describe_ip currently only supports queries to nekudo'
            )
    ip_details = {'accuracy_radius': 0, 'asn': '', 'assignment': '', 'city':
        '', 'continent': '', 'country': '', 'hostname': '', 'ip': '', 'isp':
        '', 'latitude': 0.0, 'longitude': 0.0, 'organization': '',
        'postal_code': '', 'region': '', 'timezone': '', 'type': ''}
    import requests
    try:
        response = requests.get(url=source_url)
    except Exception as err:
        from labpack.handlers.requests import handle_requests
        from requests import Request
        request_object = Request(method='GET', url=source_url)
        request_details = handle_requests(request_object)
        raise Exception(request_details['error'])
    if source == 'whatismyip':
        import re
        response_text = response.content.decode()
        table_regex = re.compile(
            '
\n
IP.*?
\n<span\\sstyle', re.S)
        table_search = table_regex.findall(response_text)
        if table_search:
            table_text = table_search[0]
            field_list = ['IP', 'Hostname', 'ISP', 'Organization', 'Type',
                'ASN', 'Assignment', 'Continent', 'Country', 'State/Region',
                'City', 'Latitude', 'Longitude', 'Postal Code']
            for field in field_list:
                field_regex = re.compile('
%s:	(.*?)	' %
                    field, re.S)
                field_search = field_regex.findall(table_text)
                if field_search:
                    ip_details[field.lower().replace(' ', '_')] = field_search[
                        0]
        for field in ('longitude', 'latitude'):
            if field in ip_details.keys():
                coord_regex = re.compile('\\-?\\d+\\.\\d+')
                coord_search = coord_regex.findall(ip_details[field])
                if coord_search:
                    ip_details[field] = float(coord_search[0])
        if 'country' in ip_details.keys():
            country_regex = re.compile('([\\w\\s]+?)($|\\s(.*?)<')
                link_search = link_regex.findall(ip_details[field])
                if link_search:
                    ip_details[field] = link_search[0]
        if 'state/region' in ip_details.keys():
            ip_details['region'] = ip_details['state/region']
            del ip_details['state/region']
    elif source == 'nekudo':
        response_details = response.json()
        ip_details['country'] = response_details['country']['name']
        ip_details['latitude'] = response_details['location']['latitude']
        ip_details['longitude'] = response_details['location']['longitude']
        ip_details['accuracy_radius'] = response_details['location'][
            'accuracy_radius']
        if response_details['city']:
            ip_details['city'] = response_details['city']
        ip_details['ip'] = response_details['ip']
        for key in response_details.keys():
            if key not in ip_details.keys() and key != 'location':
                ip_details[key] = response_details[key]
    else:
        response_details = response.json()
        for field in ('city', 'ip', 'latitude', 'longitude'):
            ip_details[field] = response_details[field]
        ip_details['country'] = response_details['country_name']
        ip_details['region'] = response_details['region_name']
        ip_details['postal_code'] = response_details['zip_code']
        ip_details['timezone'] = response_details['time_zone']
    return ip_details


def shoulder_r1_released(controller):
    """
    Callback function that is triggered, when the shoulder button R1 was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Shoulder R1 released')


def is_choked(p_c, p_e, gamma):
    """Determine whether the nozzle flow is choked.

    See :ref:`choked-flow-tutorial-label` for details.

    Reference: Rocket Propulsion Elements, 8th Edition, Equation 3-20.

    Arguments:
        p_c (scalar): Nozzle stagnation chamber pressure [units: pascal].
        p_e (scalar): Nozzle exit static pressure [units: pascal].
        gamma (scalar): Exhaust gas ratio of specific heats [units: dimensionless].

    Returns:
        bool: True if flow is choked, false otherwise.
    """
    return p_e / p_c < (2 / (gamma + 1)) ** (gamma / (gamma - 1))


def wootric_url(route):
    """helper to build a full wootric API route, handling leading '/'

    >>> wootric_url('v1/responses')
    ''https://api.wootric.com/v1/responses'
    >>> wootric_url('/v1/responses')
    ''https://api.wootric.com/v1/responses'
    """
    route = route.lstrip('/')
    return f'https://api.wootric.com/{route}'


def pad_int_str(int_to_pad: int, n: int=2) ->str:
    """Converts an integer to a string, padding with leading zeros
    to get n characters. Intended for date and time formatting.
    """
    base = str(int_to_pad)
    for k in range(n - 1):
        if int_to_pad < 10 ** (k + 1):
            base = '0' + base
    return base


def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    html_codes = ("'", '''), ('"', '"'), ('>', '>'), ('<', '<'
        ), ('&', '&')
    for code in html_codes:
        s = s.replace(code[1], code[0])
    return s


def shutdown(isdsAppliance, check_mode=False, force=False):
    """
    Shutdown the appliance
    """
    if check_mode is True:
        return isdsAppliance.create_return_object(changed=True)
    else:
        return isdsAppliance.invoke_post('Shutting down appliance',
            '/diagnostics/restart_shutdown/shutdown', {})


def tf2onnx_installed():
    """
    Checks that *tf2onnx* is available.
    """
    try:
        import tf2onnx
        return True
    except ImportError:
        return False


def editor_role(ignored):
    """Return the name of the editor role in in this package."""
    return 'icemac.ab.calexport.ExportEditor'


def update_params(params, param_dict, lineshape='PV', xy_bounds=None):
    """ Update lmfit parameters with values from Peak

        :param params: lmfit parameters
        :type params: lmfit.Parameters object
        :param param_dict: parameters corresponding to each peak in fit
        :type param_dict: dict
        :param lineshape: lineshape (PV, G, L, PV_PV etc.)
        :type lineshape: str
        :param xy_bounds: bounds on xy peak positions
        :type xy_bounds: tuple

        :returns: None
        :rtype: None

        ToDo
          -- deal with boundaries
          -- currently positions in points

    """
    for k, v in param_dict.items():
        params[k].value = v
        if 'center' in k:
            if xy_bounds == None:
                pass
            else:
                if 'center_x' in k:
                    x_bound = xy_bounds[0]
                    params[k].min = v - x_bound
                    params[k].max = v + x_bound
                elif 'center_y' in k:
                    y_bound = xy_bounds[1]
                    params[k].min = v - y_bound
                    params[k].max = v + y_bound
                print('setting limit of %s, min = %.3e, max = %.3e' % (k,
                    params[k].min, params[k].max))
        elif 'sigma' in k:
            params[k].min = 0.0
            params[k].max = 10000.0
        elif 'gamma' in k:
            params[k].min = 0.0
            params[k].max = 10000.0
        elif 'fraction' in k:
            params[k].min = 0.0
            params[k].max = 1.0
            if lineshape == 'G':
                params[k].vary = False
            elif lineshape == 'L':
                params[k].vary = False


def ninja_key_value_pairs(key, values):
    """Add include/subninja fields
    Args:
        key (str): such as "include", "subninja"
        values (list): a list of strings
    Returns:
        a string
    """
    if isinstance(values, list):
        return '\n\n'.join(map(lambda x: '{} {}'.format(key, x), values))
    else:
        return '{} {}'.format(key, values)


def marching_cubes_to_obj(marching_cubes_out, output_file):
    """
    Saves the output of skimage.measure.marching_cubes as an .obj file

    :param marching_cubes_out: tuple
    :param output_file: str

    """
    verts, faces, normals, _ = marching_cubes_out
    with open(output_file, 'w') as f:
        for item in verts:
            f.write(f'v {item[0]} {item[1]} {item[2]}\n')
        for item in normals:
            f.write(f'vn {item[0]} {item[1]} {item[2]}\n')
        for item in faces:
            f.write(
                f'f {item[0]}//{item[0]} {item[1]}//{item[1]} {item[2]}//{item[2]}\n'
                )
        f.close()


def get_text(prompt='', msg=None, input=input):
    """Prompt user to enter multiple lines of text."""
    print((msg or 'Enter text.') + " End with ^D or a '.' as first character.")
    lines = []
    while True:
        try:
            line = input(prompt)
        except EOFError:
            break
        if line == '.':
            break
        lines.append(line)
    return '\n'.join(lines)


def _local_name(element):
    """Strip namespace from the XML element's name"""
    tag = element.tag
    if tag and tag[0] == '{':
        return tag.rpartition('}')[2]
    return tag


@classmethod
def closure_parentref(cls):
    """How to refer to parents in the closure tree"""
    return '%sclosure_children' % cls._toplevel().__name__.lower()


def interface_theme_preset_add(name: str='', remove_name: bool=False,
    remove_active: bool=False):
    """Add or remove a theme preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_name: remove_name
    :type remove_name: bool
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def get_return_data_type(func_name):
    """Return a somewhat-helpful data type given a function name"""
    if func_name.startswith('get_'):
        if func_name.endswith('_list'):
            return 'List'
        elif func_name.endswith('_count'):
            return 'Integer'
    return ''


def check_url(url):
    """
    Helper function to check if a url starts with http or https, if not
    corrects it with https:// in the start of the string.

    :param url:
    :return:
    """
    if url:
        for starts in ['http://', 'https://', 'front:', '/', 'mailto:',
            'tel:', 'sms:']:
            if url.lower().startswith(starts):
                break
        else:
            url = 'https://' + url
    else:
        url = ''
    return url


@classmethod
def run_from_json_file(cls, file_path, neo4j_session, parameters=None):
    """
        Run a job from a JSON file. This will deserialize the job and execute all statements sequentially.
        """
    if not parameters:
        parameters = {}
    job = cls.from_json_file(file_path)
    job.merge_parameters(parameters)
    job.run(neo4j_session)


@classmethod
def set_config(mcs, config_path):
    """Set config which should be used in within Config singleton.

        :param config_path: a path to configuration that should be used
        :type config_path: str
        """
    assert mcs._instance is None
    mcs._config = config_path


def update_animated_transform_constraints(use_convert_to_radians: bool=True):
    """Update fcurves/drivers affecting Transform constraints (use it with files from 2.70 and earlier)

    :param use_convert_to_radians: Convert To Radians, Convert fcurves/drivers affecting rotations to radians (Warning: use this only once!)
    :type use_convert_to_radians: bool
    """
    pass


def HStrainNames(SGData):
    """Needs a doc string"""
    laue = SGData['SGLaue']
    uniq = SGData['SGUniq']
    if laue in ['m3', 'm3m']:
        return ['D11', 'eA']
    elif laue in ['6/m', '6/mmm', '3m1', '31m', '3']:
        return ['D11', 'D33']
    elif laue in ['3R', '3mR']:
        return ['D11', 'D12']
    elif laue in ['4/m', '4/mmm']:
        return ['D11', 'D33']
    elif laue in ['mmm']:
        return ['D11', 'D22', 'D33']
    elif laue in ['2/m']:
        Dij = ['D11', 'D22', 'D33']
        if uniq == 'a':
            Dij += ['D23']
        elif uniq == 'b':
            Dij += ['D13']
        elif uniq == 'c':
            Dij += ['D12']
        return Dij
    else:
        Dij = ['D11', 'D22', 'D33', 'D12', 'D13', 'D23']
        return Dij


def file_format(path):
    """
    Return corresponding file format for a file
    (loop through all the lines, get maximum matched dictionary key)
    usage: input(file path)
    Format Usage with double equal  in control flow ==
    'Window(LF|CR)'  -> for Window MS(dos)
    'Unix/MacOS(LF)' -> for Linux, MacOS
    'Macintosh(CR)' -> for Older version of MacOS
    'Unknown' -> Undefined format
    """
    with open(path, 'rb') as f:
        carriage_dict = {'Unknown': 0, 'Window': 0, 'Linux': 0, 'Macintosh': 0}
        for index, line in enumerate(f, 1):
            if b'\r\n' in line:
                carriage_dict['Window'] += 1
            elif b'\n' in line:
                carriage_dict['Linux'] += 1
            elif b'\r' in line:
                carriage_dict['Macintosh'] += 1
            else:
                carriage_dict['Unknown'] += 1
        return max(carriage_dict, key=carriage_dict.get)


@classmethod
def isPrivate(cls):
    """
        Class method to check the private browsing mode.

        @return flag indicating private browsing mode
        @rtype bool
        """
    return cls._isPrivate


def positive_to_range(exp, a, b):
    """
    Mapping a positive parameter 'exp' from the interval <0, \\infty) to the interval <a,b).
    Suitable e.g. to generate meaningful porosity from a variable with lognormal distribution.
    :param exp: A positive parameter. (LogNormal distribution.)
    :param a, b: Range interval.
    """
    return b * (1 - (b - a) / (b + (b - a) * exp))


def get():
    """Retrieves the extensions results."""


def phaseID_linestyle(phaseID, linestyles=['-', '--', ':', '-.'] * 2):
    """
    Method for generating linestyles for delineating sequential phases
    based on their phase IDs (e.g. olivine_0, olivine_1) .

    Parameters
    -----------
    phasename : :class:`str`
        Phase ID for which to generate a line style.
    linestyles : :class:`list`
        List of line styles for sequential phase ID numbers.
        Added to allow reconfiguraiton where needed.

    Returns
    ---------
    :class:`str`
        Line style for the phase ID.
    """
    if '_' in phaseID:
        return linestyles[int(phaseID[-1])]
    else:
        return linestyles[0]


def extract_patch(image, pshape, r, c):
    """
    Extract a patch of given shape, centered at r,c of given shape from image.

    Note that there is no checking if the patch region is inside the image.

    >>> image = np.reshape(np.arange(16, dtype='uint8'), (4, 4))
    >>> extract_patch(image, (2, 3), 2, 2)
    array([[ 5,  6,  7],
           [ 9, 10, 11]], dtype=uint8)

    :param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
       Can be of shapes MxN, MxNxC.
    :param tuple pshape: Shape of patch. #Dimensions must match image.
    :param int r: Row for center of patch
    :param int c: Column for center of patch
    :return: numpy array with shape pshape
    :rtype: numpy array with range [0,255] and dtype 'uint8'
    """
    h, w = pshape[0], pshape[1]
    r, c = int(r - h // 2), int(c - w // 2)
    return image[r:r + h, c:c + w]


@staticmethod
def rotate(word):
    """ rotate a sequence of bytes eight bits to the left """
    return word[1:] + word[:1]


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.stages.TimeIntervalMiniBatchTransformer'


def _handle_inplace_replacements(document, link, link_ancestors):
    """
    Given a new document, and the link/ancestors it was created,
    determine if we should:

    * Make an inline replacement and then return the modified document tree.
    * Return the new document as-is.
    """
    if not link.transform:
        if link.action.lower() in ('put', 'patch', 'delete'):
            transform = 'inplace'
        else:
            transform = 'new'
    else:
        transform = link.transform
    if transform == 'inplace':
        root = link_ancestors[0].document
        keys_to_link_parent = link_ancestors[-1].keys
        if document is None:
            return root.delete_in(keys_to_link_parent)
        return root.set_in(keys_to_link_parent, document)
    return document


def set_trainable(model, recompile=True, **kwargs):
    """Set all layers of model trainable and recompile it

    Note:
        Model is recompiled using same optimizer, loss and metrics::

            model.compile(
                model.optimizer,
                loss=model.loss,
                metrics=model.metrics,
                loss_weights=model.loss_weights,
                sample_weight_mode=model.sample_weight_mode,
                weighted_metrics=model.weighted_metrics,
            )

    Args:
        model (``keras.models.Model``): instance of keras model

    """
    for layer in model.layers:
        layer.trainable = True
    if recompile:
        model.compile(model.optimizer, loss=model.loss, metrics=model.
            metrics, loss_weights=model.loss_weights, sample_weight_mode=
            model.sample_weight_mode, weighted_metrics=model.weighted_metrics)


def activate_multi_threading():
    """ activate multi-threading for all app instances (normally done at main app startup). """
    global _multi_threading_activated
    _multi_threading_activated = True


def err_response(reqid, code, msg, data=None):
    """
    Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error'
    """
    err = {'code': code, 'message': msg}
    if data:
        err['data'] = data
    return {'jsonrpc': '2.0', 'id': reqid, 'error': err}


@staticmethod
def _skip_useless_lines(sequence):
    """Yields only lines that do not begin with '#'.

        Also skips any blank lines at the beginning of the input.
        """
    at_beginning = True
    for line in sequence:
        if isinstance(line, bytes):
            if line.startswith(b'#'):
                continue
        elif line.startswith('#'):
            continue
        if at_beginning:
            if isinstance(line, bytes):
                if not line.rstrip(b'\r\n'):
                    continue
            elif not line.rstrip('\r\n'):
                continue
            at_beginning = False
        yield line


def delete_attribute(halo, attribute):
    """
    Delete attribute from halo object.

    Parameters
    ----------
    halo : Halo object
        The Halo object to be provided by the HaloCatalog.
    attribute : string
        The attribute to be deleted.

    """
    if hasattr(halo, attribute):
        delattr(halo, attribute)


def make_timestamp_range(start, end, start_timestamp_op=None,
    end_timestamp_op=None):
    """Create the query document to find timestamps within that range.

    This is done by given two possible datetimes and their operations.
    By default, using $gte for the lower bound and $lt for the upper bound.
    """
    ts_range = {}
    if start:
        if start_timestamp_op == 'gt':
            start_timestamp_op = '$gt'
        else:
            start_timestamp_op = '$gte'
        ts_range[start_timestamp_op] = start
    if end:
        if end_timestamp_op == 'le':
            end_timestamp_op = '$lte'
        else:
            end_timestamp_op = '$lt'
        ts_range[end_timestamp_op] = end
    return ts_range


def py2sqlite(data):
    """
    Return an sqlite type name based on the type of the input data

    Can try to support numpy later
    """
    if isinstance(data, int):
        return 'integer'
    elif isinstance(data, float):
        return 'real'
    elif isinstance(data, str):
        return 'text'
    else:
        message = (
            'Error: python data must be one of the following types: int, float, str'
            )
        raise ValueError(message)


def freestyle_modifier_copy():
    """Duplicate the modifier within the list of modifiers

    """
    pass


def is_16bit_oper_register(x):
    """ Returns whether the given string x is a 16 bit register. These are any 16 bit register
    which belongs to the normal (documented) Z80 instruction set as operands.
    """
    return x.lower() in {'af', "af'", 'bc', 'de', 'hl', 'ix', 'iy', 'sp'}


def theta_H_Mg_HMW84(T, P):
    """c-c': hydrogen magnesium [HMW84]."""
    theta = 0.1
    valid = T == 298.15
    return theta, valid


def retry_until_value(value, retries=3, delay=1):
    """Retries a function or method until it returns a specific value

        delay sets the initial delay in seconds, and backoff sets the factor by which
        the delay should lengthen after each failure. backoff must be greater or equal ot 1.
        tries must be at least 0, and delay
        greater than 0."""


def print_vec(vector, prec=5, retS=False, vertical=False):
    """ Print vector (1D array) to the console or return as formatted string

    Parameters
    ----------
        vector : (M,) array_like
        prec : int
            the precision of the output
        vertical : bool
            print out vertical or not
        retS : bool
            print or return string

    Returns
    -------
        s : str
            if retS is True

    """
    if vertical:
        t = '\n'
    else:
        t = '\t'
    s = ''.join([('%1.*g %s' % (int(prec), s, t)) for s in vector])
    if retS:
        return s
    else:
        print(s)


def removeNullTerminator(bytestring):
    """Remove null terminator from bytestring."""
    bytesOut = bytestring.rstrip(b'\x00')
    return bytesOut


def specialInterpretValue(value, index, *args, **kwargs):
    """Interprets a passed value. In this order:
     - If it's callable, call it with the parameters provided
     - If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict
     - Else, just return it
     """
    if callable(value):
        return value(*args, **kwargs)
    if index is not None and (isinstance(value, tuple) or isinstance(value,
        list) or isinstance(value, dict)):
        return value[index]
    return value


def _eq(prop_value, cmp_value, ignore_case=False):
    """
    Helper function that take two arguments and checks if :param prop_value:
    equals :param cmp_value:

    :param prop_value: Property value that you are checking.
    :type prop_value: :class:`str`
    :param cmp_value: Value that you are checking if they are equal.
    :type cmp_value: :class:`str`
    :param ignore_case: True to run using incase sensitive.
    :type ignore_case: :class:`bool`
    :returns: True if :param prop_value: and :param cmp_value: are
        equal.
    :rtype: class:`bool`
    """
    if ignore_case is True:
        prop_value = prop_value.lower()
        cmp_value = cmp_value.lower()
    return cmp_value == prop_value


def key2mongo(tup):
    """Return a string given an (int, string) plate-well key.

    Parameters
    ----------
    tup : (int, string) tuple
        A (plate, well) identifier.

    Returns
    -------
    mongo_id : string
        A string, suitable for representing a mongodb _id field.

    Examples
    --------
    >>> tup = (2490688, 'C04')
    >>> key2mongo(tup)
    '2490688-C04'
    """
    return str(tup[0]) + '-' + tup[1]


def format_num(num, unit='bytes'):
    """
    Returns a human readable string of a byte-value.
    If 'num' is bits, set unit='bits'.
    """
    if unit == 'bytes':
        extension = 'B'
    else:
        extension = 'Bit'
    for dimension in (unit, 'K', 'M', 'G', 'T'):
        if num < 1024:
            if dimension == unit:
                return f'{num:3.1f} {dimension}'
            return f'{num:3.1f} {dimension}{extension}'
        num /= 1024
    return f'{num:3.1f} P{extension}'


@classmethod
def lowest(cls):
    """Returns a specific ``lowest`` version which always evaluates as older.

        You shall use this value in your :py:class:`VersionPick` dictionaries to match the oldest
        possible version of the product.
        """
    try:
        return cls._lowest
    except AttributeError:
        cls._lowest = cls('lowest')
        return cls._lowest


def isBuildConfFake(conf):
    """
    Return True if loaded buildconf is a fake module.
    """
    return conf.__name__.endswith('fakeconf')


def _format_error_type(error_type):
    """
    Format the text to print at the top of the assertion block.
    :param error_type: The assertion function name.
    :return:
    """
    return '{} failed:'.format(error_type.replace('_', ' ')).upper()


def parse_dformat(dformat, check=True):
    """Return `dformat` or raise if it is not 'dense' or 'sparse'"""
    if check and dformat not in ['dense', 'sparse']:
        raise IOError(
            "{} is a bad features format, please choose 'dense' or 'sparse'"
            .format(dformat))
    return dformat


def bfs(start):
    """
    Breadth first search

    Yields all nodes found from the starting point

    :param start: start node
    """
    to_visit = [start]
    visited = set([start])
    while to_visit:
        node = to_visit.pop(0)
        yield node
        if node.exception_analysis:
            for _, _, exception in node.exception_analysis.exceptions:
                if exception not in visited:
                    to_visit.append(exception)
                    visited.add(exception)
        for _, _, child in node.childs:
            if child not in visited:
                to_visit.append(child)
                visited.add(child)


@classmethod
def from_directive(cls, directive, app):
    """Return one of these whose state is all derived from a directive.

        This is suitable for top-level calls but not for when a renderer is
        being called from a different renderer, lest content and such from the
        outer directive be duplicated in the inner directive.

        :arg directive: The associated Sphinx directive
        :arg app: The Sphinx global app object. Some methods need this.

        """
    return cls(directive, app, arguments=directive.arguments, content=
        directive.content, options=directive.options)


@classmethod
def _parse_parameters(cls, spec: str):
    """Parse key=value;key=value;key=value into a dict"""
    fields = spec.split(';')
    result = dict()
    for field in fields:
        field = field.strip()
        if not field:
            continue
        key, equals, value = field.partition('=')
        if equals == '=' and value == '':
            raise ValueError('No value given')
        key = key.strip()
        if key not in cls.allowed_parameters:
            raise KeyError('Unknown parameter {}'.format(key))
        while cls.allowed_parameters[key] is not None:
            key = cls.allowed_parameters[key]
        value = value.strip()
        if value == '':
            value = True
        else:
            try:
                value = int(value)
            except ValueError:
                value = float(value)
        if key in result:
            raise KeyError('Key {} specified twice'.format(key))
        result[key] = value
    if 'optional' in result and 'required' in result:
        raise ValueError(
            "'optional' and 'required' cannot be specified at the same time")
    if 'optional' in result:
        result['required'] = False
        del result['optional']
    return result


@classmethod
def from_starfit(cls, cube, pos, **kwargs):
    """Compute FSF by fitting a point source on a datacube"""
    raise NotImplementedError


def print_test(a):
    """
    Added for get_input parameter injection testing.

    :param a: input
    :type a: int
    :return: len(a) as str
    """
    return str(len(a))


@classmethod
def from_dict(cls, data):
    """
        Creates a JaffleSession from a dict.

        Parameters
        ----------
        data : dict
            Python dict to initialize JaffleSession.

        Returns
        -------
        session : JaffleSession.
            Jaffle session.
        """
    return cls(id=data.get('id'), name=data.get('name'), kernel=data.get(
        'kernel'))


def hsla_to_rgba(h, s, l, alpha=1.0):
    """Converts a color given by its HSLA coordinates (hue, saturation,
    lightness, alpha) to RGBA coordinates.

    Each of the HSLA coordinates must be in the range [0, 1].
    """
    c = s * (1 - 2 * abs(l - 0.5))
    h1 = h * 6 % 6
    x = c * (1 - abs(h1 % 2 - 1))
    m = l - c / 2.0
    h1 = int(h1)
    if h1 < 3:
        if h1 < 1:
            return c + m, x + m, m, alpha
        elif h1 < 2:
            return x + m, c + m, m, alpha
        else:
            return m, c + m, x + m, alpha
    elif h1 < 4:
        return m, x + m, c + m, alpha
    elif h1 < 5:
        return x + m, m, c + m, alpha
    else:
        return c + m, m, x + m, alpha


def html_escape(string):
    """ Escape HTML special characters ``&<>`` and quotes ``'"``. """
    return string.replace('&', '&').replace('<', '<').replace('>',
        '>').replace('"', '"').replace("'", ''')


def abort_if_false(ctx, param, value):
    """Abort the command if the value resolves to be false."""
    if not value:
        ctx.abort()


def randomize_unitofwork():
    """Use random-ordering sets within the unit of work in order
    to detect unit of work sorting issues.

    This is a utility function that can be used to help reproduce
    inconsistent unit of work sorting issues.   For example,
    if two kinds of objects A and B are being inserted, and
    B has a foreign key reference to A - the A must be inserted first.
    However, if there is no relationship between A and B, the unit of work
    won't know to perform this sorting, and an operation may or may not
    fail, depending on how the ordering works out.   Since Python sets
    and dictionaries have non-deterministic ordering, such an issue may
    occur on some runs and not on others, and in practice it tends to
    have a great dependence on the state of the interpreter.  This leads
    to so-called "heisenbugs" where changing entirely irrelevant aspects
    of the test program still cause the failure behavior to change.

    By calling ``randomize_unitofwork()`` when a script first runs, the
    ordering of a key series of sets within the unit of work implementation
    are randomized, so that the script can be minimized down to the
    fundamental mapping and operation that's failing, while still reproducing
    the issue on at least some runs.

    This utility is also available when running the test suite via the
    ``--reversetop`` flag.

    .. versionadded:: 0.8.1 created a standalone version of the
       ``--reversetop`` feature.

    """
    from sqlalchemy.orm import unitofwork, session, mapper, dependency
    from sqlalchemy.util import topological
    from sqlalchemy.testing.util import RandomSet
    (topological.set) = (unitofwork.set) = (session.set) = (mapper.set) = (
        dependency.set) = RandomSet