@classmethod
def from_table(cls, table):
    """Read from `~astropy.table.Table`."""
    return cls(energy_lo=table['ENERG_LO'].quantity[0], energy_hi=table[
        'ENERG_HI'].quantity[0], offset_lo=table['THETA_LO'].quantity[0],
        offset_hi=table['THETA_HI'].quantity[0], data=table['EFFAREA'].
        quantity[0].transpose(), meta=table.meta)


def diff_lint_report(diff_lint_dict: dict) ->str:
    """Generate report in same format as pylint, but for diff only

    :param diff_lint_dict: dict as produced by :func:`~diff_cov_lint.lint.filter_lint`
    :type diff_lint_dict: dict
    :return: output with errors in diff only
    :rtype: str
    """
    ans = '=' * 26 + ' DIFF LINT ' + '=' * 26 + '\n'
    for filename in diff_lint_dict:
        for line in diff_lint_dict[filename]:
            ans += f"""{filename}:{line}:0 {diff_lint_dict[filename][line]['error']}: {diff_lint_dict[filename][line]['msg']}
"""
    return ans


def setTcpNoDelay(enabled):
    """
        Enable/disable C{TCP_NODELAY}.

        Enabling C{TCP_NODELAY} turns off Nagle's algorithm. Small packets are
        sent sooner, possibly at the expense of overall throughput.
        """


def add_years(date, years):
    """Add `years` number of years to date."""
    try:
        return date.replace(year=date.year + years)
    except ValueError:
        return date.replace(year=date.year + years, day=date.day - 1)


@classmethod
def create_from_url(cls, url: str, content_type: str=''):
    """
        Create a FeedInfo object from a Url

        :param url: Url string
        :param content_type: Content-Type of returned Url
        :return: FeedInfo
        """
    return cls(url=url, content_type=content_type)


def glRect(x1, y1, x2, y2, v1, v2):
    """Draw a rectangle

    :param y1: Specify one vertex of a rectangle
    :param y2: Specify the opposite vertex of the rectangle
    :param v2: Specifies a pointer to one vertex of a rectangle and the pointer to the opposite vertex of the rectangle
    """
    pass


@classmethod
def _eager_b(cls, eager):
    """
        Builds the provided list of eager values, preparing them
        according to the current model rules.

        The composition process includes the extension of the provided
        sequence of eager values with the base ones defined in the
        model, if not handled correctly this is an expensive operation.

        :type eager: List/Tuple
        :param eager: The base sequence containing the various fields
        that should be eagerly loaded for the operation.
        :rtype: Tuple
        :return: The "final" resolved tuple that may be used for the eager
        loaded operation performance.
        """
    eager = list(eager) if eager else []
    eagers = cls.eagers()
    eager.extend(eagers)
    if not eager:
        return eager
    eager = tuple(set(eager))
    return eager


def gpencil_modifier_copy(modifier: str=''):
    """Duplicate modifier at the same position in the stack

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def get_hostname(request):
    """ Extract hostname from request.
    The scrip is taken from http://docs.plone.org/develop/plone/serving/http_request_and_response.html#hostname
    and includes virtualhost support.
    """
    if 'HTTP_X_FORWARDED_HOST' in request.environ:
        host = request.environ['HTTP_X_FORWARDED_HOST']
    elif 'HTTP_HOST' in request.environ:
        host = request.environ['HTTP_HOST']
    else:
        return ''
    host = host.split(':')[0].lower()
    return host


def google_text_emphasis(style):
    """return a list of all emphasis modifiers of the element"""
    emphasis = []
    if 'text-decoration' in style:
        emphasis.append(style['text-decoration'])
    if 'font-style' in style:
        emphasis.append(style['font-style'])
    if 'font-weight' in style:
        emphasis.append(style['font-weight'])
    return emphasis


def writegive(giveup, g):
    """Write giveup data."""
    try:
        outfile = open(giveup, 'w')
    except Exception:
        print('Unable to write a file:', giveup)
        return
    for i in range(3):
        for j in g[i]:
            outfile.write(j.strip() + '\n')
    for i in g[3]:
        outfile.write('g ' + str(i[0]) + ' ' + i[1] + '\n')
    outfile.close
    return


def hm_to_float(h, m):
    """Convert 7, 30 to 7.5 hours."""
    return float(h) + float(m) / 60.0


@classmethod
def _IsSimpleTypeContent(cls):
    """CTDs with simple content are simple; other CTDs are not."""
    return cls._CT_SIMPLE == cls._ContentTypeTag


def left_pad(input, length, fill_character=' '):
    """
    Returns a string, which will be padded on the left with characters if necessary. If the input string is longer
    than the specified length, it will be returned unchanged.

    >>> left_pad('foo', 5)
    '  foo'

    >>> left_pad('foobar', 6)
    'foobar'

    >>> left_pad('toolong', 2)
    'toolong'

    >>> left_pad(1, 2, '0')
    '01'

    >>> left_pad(17, 5, 0)
    '00017'

    :param input:
    :param length: The return string's desired length.
    :param fill_character:
    :rtype str:
    """
    return str(input).rjust(length, str(fill_character))


def minify(content):
    """
    Remove whitespace in provided content.
    """
    content = content.replace('\n', ' ')
    content = content.replace('\t', ' ')
    content = content.replace('   ', ' ')
    content = content.replace('  ', ' ')
    return content


def dict_from_cookiejar(cj):
    """Returns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    """
    cookie_dict = {}
    for cookie in cj:
        cookie_dict[cookie.name] = cookie.value
    return cookie_dict


@classmethod
def import_module(cls):
    """Import the DB engine module."""
    raise NotImplementedError


def update_config_data(msg, cfg):
    """
    Updates the profile's config entry with values set in each attr by the
    user.  This will overwrite existing values.

    Args:
        :msg: (Message class) an instance of a message class.
        :cfg: (jsonconfig.Config) config instance.
    """
    for attr in msg:
        if attr in cfg.data[msg.profile] and attr is not 'auth':
            cfg.data[msg.profile][attr] = getattr(msg, attr)


def get_index(lang, index):
    """
    Given an integer index this function will return the proper string
    version of the index based on the language and other considerations

    Parameters
    ----------
    lang : str
        One of the supported languages, {'c', 'cuda', 'fortran', 'matlab'}
    index : int

    Returns
    -------
    str
        The string corresponding to the correct index to be formatted into the code

    """
    retval = None
    if lang in ['fortran', 'matlab']:
        return str(index + 1)
    if lang in ['c', 'cuda']:
        return str(index)


def extract_zip(archive, compression, cmd, verbosity, interactive, outdir):
    """Extract a ZIP archive."""
    cmdlist = [cmd]
    if verbosity > 1:
        cmdlist.append('-v')
    cmdlist.extend(['--', archive, '-d', outdir])
    return cmdlist


def _node_text(etree, xpath):
    """
    shortcut function
    """
    return etree.find(xpath).text


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


@classmethod
def get_accept(cls):
    """ Load the framework-specific Accept header """
    raise NotImplementedError


@classmethod
def _extract_error_message(cls, e):
    """Extract error message for queries"""
    message = str(e)
    try:
        if isinstance(e.args, tuple) and len(e.args) > 1:
            message = e.args[1]
    except Exception:
        pass
    return message


def clear_change_event_tracers():
    """ Clear the global trait change event tracer. """
    global _pre_change_event_tracer
    global _post_change_event_tracer
    _pre_change_event_tracer = None
    _post_change_event_tracer = None


def ChargeColorMapping(maptype='jet', reverse=False):
    """Maps amino-acid charge at neutral pH to colors.
    Currently does not use the keyword arguments for *maptype*
    or *reverse* but accepts these arguments to be consistent
    with KyteDoolittleColorMapping and MWColorMapping for now."""
    pos_color = '#FF0000'
    neg_color = '#0000FF'
    neut_color = '#000000'
    mapping_d = {'A': neut_color, 'R': pos_color, 'N': neut_color, 'D':
        neg_color, 'C': neut_color, 'Q': neut_color, 'E': neg_color, 'G':
        neut_color, 'H': pos_color, 'I': neut_color, 'L': neut_color, 'K':
        pos_color, 'M': neut_color, 'F': neut_color, 'P': neut_color, 'S':
        neut_color, 'T': neut_color, 'W': neut_color, 'Y': neut_color, 'V':
        neut_color}
    return None, mapping_d, None


def lookupbranch(key):
    """Look up the branch name of the given revision or branch name."""


@classmethod
def table_name_col(cls):
    """
        Returns the name of the metadata column used to store the
        the feature table name.
        """
    return 'table_name'


def userpref_show():
    """Show user preferences

    """
    pass


def getInfoData():
    """ Return a lazy mapping of the data needed to create an
            IActionInfo object.

        o Returned value is actually a tuple, '(lazy_map, lazy_keys)'.

        o Default keys are: 'id', 'category', 'title', 'description', 'url',
          'icon', 'available', 'permissions' and 'visible'.

        o Instead of computed values callable expression objects or methods
          are returned. For performance reasons, these objects are called
          later and only if the values are actually needed. The keys for all
          these lazy values are registered in a separate list.
        """


def save_spacy_model(model, path):
    """ Save spacy model to file

    Parameters
    ----------
    model : :obj:`spacy.lang`
        SpaCy language model
    path  : :obj:`str`
        file path to save model

    Returns
    -------
    """
    model.to_disk(path)
    return None


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


def increase(value: int) ->int:
    """
    Return increased by 1 argument.

    :param value:
    :type value: Int
    :returns:
    :rtype: Int
    """
    return value + 1


def get_url(path, scheme='http'):
    """ Return the full InfoQ URL """
    return scheme + '://www.infoq.com' + path


def make_gffutils_db(gtf, db):
    """
    Make database for gffutils.

    Parameters
    ----------
    gtf : str
        Path to Gencode gtf file.

    db : str
        Path to save database to.

    Returns
    -------
    out_db : gffutils.FeatureDB
        gffutils feature database.

    """
    import gffutils
    out_db = gffutils.create_db(gtf, db, keep_order=True, infer_gene_extent
        =False)
    return out_db


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

        :param TfaAddExceptionType val:
        :rtype: EventType
        """
    return cls('tfa_add_exception', val)


def _updatePolicyElements(policy_item, regkey):
    """
    helper function to add the reg key to each policies element definitions if
    the key attribute is not defined to make xpath searching easier for each
    child in the policy <elements> item
    """
    for child in policy_item.getiterator():
        if 'valueName' in child.attrib:
            if 'key' not in child.attrib:
                child.attrib['key'] = regkey
    return policy_item


def request_tree(point, kd_tree, nb_neighbors=None, radius=None):
    """Extract a point neighborhood by the way of a KDTree method

    At least one parameter amongst 'nb_neighbors' and 'radius' much be
    valid. 'nb_neighbors' is considered first.

    Parameters
    ----------
    point : numpy.array
        Coordinates of the reference point (x, y, z)
    tree : scipy.spatial.KDTree
        Tree representation of the point cloud
    nb_neighbors : int
        Number of neighboring points to consider
    radius : float
        Radius that defines the neighboring ball around a given point

    Returns
    -------
    tuple
        Neighborhood, decomposed as a mean distance between the reference point
    and its neighbors and an array of neighbor indices within the point
    cloud. Get `nb_neighborhood + 1` in order to have the reference point and
    its k neighbors. If the neighborhood is recovered through radius, distances
    are not computed.
    """
    if nb_neighbors is not None:
        return kd_tree.query(point, k=nb_neighbors + 1)
    if radius is not None:
        return None, kd_tree.query_ball_point(point, r=radius)
    raise ValueError(
        "Kd-tree request error: nb_neighbors and radius can't be both None.")


@classmethod
def task_convert(cls, task_name: str, pre_task=True, **kwargs) ->dict:
    """
        Run the argument conversion for a given task.

        :param task_name: the short name of the task. If long name is given, it will be reduced to that short name
        :param pre_task: Converters can be registered to run before or after a task runs
        :param kwargs: the argument dict to be converted
        """
    task_short_name = task_name.split('.')[-1]
    if task_short_name not in cls._task_instances:
        return kwargs
    task = cls._task_instances[task_short_name]
    return task.convert(pre_task=pre_task, **kwargs)


def date_to_ISO_string(aDate):
    """ Take a datetime and convert to string of the form YYYY-MM-DD
    """
    return aDate.strftime('%Y-%m-%d')


def twolens_efl(efl1, efl2, separation):
    """Use thick lens equations to compute the focal length for two elements separated by some distance.

    Parameters
    ----------
    efl1 : `float`
        EFL of the first lens
    efl2 : `float`
        EFL of the second lens

    separation : `float`
        separation of the two lenses

    Returns
    -------
    `float`
        focal length of the two lens system

    """
    phi1, phi2, t = 1 / efl1, 1 / efl2, separation
    phi_tot = phi1 + phi2 - t * phi1 * phi2
    return 1 / phi_tot


def validate_master_id(org_client, spec):
    """
    Don't mangle the wrong org by accident
    """
    master_account_id = org_client.describe_organization()['Organization'][
        'MasterAccountId']
    if master_account_id != spec['master_account_id']:
        errmsg = (
            "The Organization Master Account Id '%s' does not match the 'master_account_id' set in the spec-file"
             % master_account_id)
        raise RuntimeError(errmsg)
    return


def log(rv):
    """
    Returns the natural logarithm of a random variable
    """
    return rv.log()


def make_constrained_arc_fns(states, costates, costates_rates, controls,
    parameters, constants, quantity_vars, hamiltonian):
    """
    Creates constrained arc control functions. Deprecated.

    :param states:
    :param costates:
    :param costates_rates:
    :param controls:
    :param parameters:
    :param constants:
    :param quantity_vars:
    :param hamiltonian:
    :return:
    """
    raise NotImplementedError


def duplicate_move_linked(OBJECT_OT_duplicate=None, TRANSFORM_OT_translate=None
    ):
    """Duplicate selected objects and move them

    :param OBJECT_OT_duplicate: Duplicate Objects, Duplicate selected objects
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def truncate(text, length=30, indicator='...', whole_word=False):
    """Truncate ``text`` with replacement characters.

    ``length``
        The maximum length of ``text`` before replacement
    ``indicator``
        If ``text`` exceeds the ``length``, this string will replace
        the end of the string
    ``whole_word``
        If true, shorten the string further to avoid breaking a word in the
        middle.  A word is defined as any string not containing whitespace.
        If the entire text before the break is a single word, it will have to
        be broken.

    Example::

        >>> truncate('Once upon a time in a world far far away', 14)
        'Once upon a...'

    """
    if not text:
        return ''
    if len(text) <= length:
        return text
    short_length = length - len(indicator)
    if not whole_word:
        return text[:short_length] + indicator
    i = short_length
    while i >= 0 and not text[i].isspace():
        i -= 1
    while i >= 0 and text[i].isspace():
        i -= 1
    if i <= 0:
        return text[:short_length] + indicator
    return text[:i + 1] + indicator


@classmethod
def set_allocator_library(cls, path):
    """ Change the allocator used by Xlnk instances

        This should only be called when there are no allocated buffers -
        using or freeing any pre-allocated buffers after calling this
        function will result in undefined behaviour. This function
        is needed for SDx based designs where it is desired that PYNQ
        and SDx runtime share an allocator. In this case, this function
        should be called with the SDx compiled shared library prior to
        any buffer allocation

        If loading of the library fails an exception will be raised,
        Xlnk.libxlnk_path will be unchanged and the old allocator will
        still be in use.

        Parameters
        ----------
        path : str
            Path to the library to load

        """
    cls._open_library(path)
    cls.libxlnk_path = path


@classmethod
def from_simple(cls, color, fg=True):
    """Creates a color from simple name or color number"""
    self = cls(fg=fg)
    self._from_simple(color)
    return self


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

        :param LogoutDetails val:
        :rtype: EventDetails
        """
    return cls('logout_details', val)


def sqrt(data=None, out=None, name=None, **kwargs):
    """Returns element-wise square-root value of the input.

    .. math::
       \\textrm{sqrt}(x) = \\sqrt{x}

    Example::

       sqrt([4, 9, 16]) = [2, 3, 4]

    The storage type of ``sqrt`` output depends upon the input storage type:

       - sqrt(default) = default
       - sqrt(row_sparse) = row_sparse
       - sqrt(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L142

    Parameters
    ----------
    data : NDArray
        The input array.

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

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


def _count_of_curr_and_next(rule):
    """Count tokens to be matched and those to follow them in rule."""
    return len(rule.tokens) + len(rule.next_tokens or []) + len(rule.
        next_classes or [])


def get_all(isamAppliance, check_mode=False, force=False):
    """
    Get information on existing groups
    """
    return isamAppliance.invoke_get('Retrieving groups',
        '/sysaccount/groups/v1')


def linalg_potrf(A=None, out=None, name=None, **kwargs):
    """Performs Cholesky factorization of a symmetric positive-definite matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, the Cholesky factor *B* of the symmetric, positive definite matrix *A* is
    computed. *B* is triangular (entries of upper or lower triangle are all zero), has
    positive diagonal entries, and:

      *A* = *B* \\* *B*\\ :sup:`T`  if *lower* = *true*
      *A* = *B*\\ :sup:`T` \\* *B*  if *lower* = *false*

    If *n>2*, *potrf* is performed separately on the trailing two dimensions for all inputs
    (batch mode).

    .. note:: The operator supports float32 and float64 data types only.

    Examples::

       Single matrix factorization
       A = [[4.0, 1.0], [1.0, 4.25]]
       potrf(A) = [[2.0, 0], [0.5, 2.0]]

       Batch matrix factorization
       A = [[[4.0, 1.0], [1.0, 4.25]], [[16.0, 4.0], [4.0, 17.0]]]
       potrf(A) = [[[2.0, 0], [0.5, 2.0]], [[4.0, 0], [1.0, 4.0]]]

    Defined in src/operator/tensor/la_op.cc:L214

    Parameters
    ----------
    A : NDArray
        Tensor of input matrices to be decomposed

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

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


def getValue(currency=None):
    """returns the value in the appropriate currency"""


def to_mb(bytes):
    """Express bytes in Mb"""
    return round(bytes / 2 ** (10 * 2), 1)


def ms_demo_params_to_dadi(nu_ms, tau_ms):
    """
    convert from ms parameters (which use current pop size) for nu and tau to dadi parameters (which use ancestral pop size)
    """
    return 1.0 / nu_ms, 2 * tau_ms / nu_ms


@staticmethod
def reduce_deg(deg):
    """Takes a degree value in decimal format and converts it to a float
        value in the +/-[0:360) range.

        :param deg: Input degree angle in decimal format.
        :type deg: int, float, :py:class:`Angle`

        :returns: Float value of the angle in the +/-[0:360) range.
        :rtype: float

        >>> a = 386.3
        >>> b = Angle.reduce_deg(a)
        >>> print(round(b, 1))
        26.3
        """
    if abs(deg) >= 360.0:
        sign = 1.0 if deg >= 0 else -1.0
        frac = abs(deg) % 1
        deg = int(abs(deg)) % 360
        deg = sign * (deg + frac)
    return float(deg)


def convertPythonIndexToRowCol(s, i):
    """Convert index i into string s into zero-based row/col indices."""
    if not s or i <= 0:
        return 0, 0
    i = min(i, len(s))
    row = s.count('\n', 0, i)
    if row == 0:
        return row, i
    prevNL = s.rfind('\n', 0, i)
    return row, i - prevNL - 1


def _get_or_create_ospf_processes(node_dict, node):
    """
    Get the OSPF processes dict under the specified node.

    If it or any of its parents does not already exist, create them.
    """
    return node_dict.setdefault(node, {}).setdefault('OSPF', {}).setdefault(
        'Processes', {})


def formatFileSize(size):
    """
    Format the given file size in bytes to human readable format.
    """
    if size < 1024:
        return '%iB' % size
    elif size < 1024 ** 2:
        return '%iK' % (size / 1024)
    elif size < 1024 ** 3:
        return '%iM' % (size / 1024 ** 2)
    else:
        return '%iG' % (size / 1024 ** 3)


@classmethod
def from_dict(cls, dict_obj):
    """ Creates a yalchemy ForeignKey from a dictionary.

        The dictionary has the following specification::

            {
                # The name of the column
                'column': str(required),

                # The name of the remote table
                'remote_table': str(required),

                # The name of the remote column
                'remote_column': str(required),
            }

        .. note:: The ``column`` and ``remote_column`` arguments can
            be list of strings in the case of creating foreign keys on
            combinations of columns.
        """
    return cls(**dict_obj)


@classmethod
def _postrun(cls, span, obj, **kwargs):
    """ Trigger to execute just before closing the span

        :param opentracing.span.Span  span: the SpanContext instance
        :param Any obj: Object to use as context
        :param dict kwargs: additional data
        """
    span.set_tag('response.status_code', obj.status_code)
    span.set_tag('response.content_lenght', len(getattr(obj, 'content', '')))


def load_hdf5_model(local_dir, filename, extension='.h5', custom_objects=None):
    """
    Loads a Keras model that was saved in ".h5" format

    :param string local_dir: Local directory where the model is saved
    :param string filename: Filename with which the model is saved
    :param string extension: Extension to the filename with which the model is saved
    :param dict custom_objects: Any custom objects  (such as custom loss functions) that were included when the model was saved
    :return: A Keras model
    """
    from tensorflow.keras.models import load_model
    return load_model(local_dir + '/' + filename + extension,
        custom_objects=custom_objects)


def _cigar_to_variants(seq, mature, cigar):
    """From mature based cigar get variants"""
    return None


def parse_ieee_block_header(block):
    """Parse the header of a IEEE block.

    Definite Length Arbitrary Block:
    #<header_length><data_length><data>

    The header_length specifies the size of the data_length field.
    And the data_length field specifies the size of the data.

    Indefinite Length Arbitrary Block:
    #0<data>

    In this case the data length returned will be 0. The actual length can be
    deduced from the block and the offset.

    :param block: IEEE block.
    :type block: bytes | bytearray
    :return: (offset, data_length)
    :rtype: (int, int)
    """
    begin = block.find(b'#')
    if begin < 0:
        raise ValueError(
            'Could not find hash sign (#) indicating the start of the block.')
    try:
        header_length = int(block[begin + 1:begin + 2])
    except ValueError:
        header_length = 0
    offset = begin + 2 + header_length
    if header_length > 0:
        data_length = int(block[begin + 2:offset])
    else:
        data_length = 0
    return offset, data_length


@classmethod
def error(cls, name, message, *args):
    """
        Convenience function to log a message at the ERROR level.

        :param name:    The name of the logger instance in the VSG namespace (VSG.<name>)
        :param message: A message format string.
        :param args:    The arguments that are are merged into msg using the string formatting operator.
        :..note:        The native logger's `kwargs` are not used in this function.
        """
    cls.getLogger(name).error(message, *args)


def p_quoting(p):
    """unary_expression : PHRASE"""
    p[0] = p[1]


def to_iso8601(dt):
    """
    Convert a datetime instance to a ISO-8601 compliant string.
    :param dt: A datetime instance
    :return: The corresponding ISO-8601 formatted string
    """
    return '%04d%02d%02dT%02d%02d%02dZ' % (dt.year, dt.month, dt.day, dt.
        hour, dt.minute, dt.second)


def LITERAL(value):
    """
    Returns a value without parsing. Use for values that the aggregation pipeline may interpret as an expression.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/literal/
    for more details
    :param value: The expression or variable
    :return: Aggregation operator
    """
    return {'$literal': value}


def get_env_with_cmd_linux(var_name, whole_machine: bool):
    """
    TODO: Similar to os.environ[var_name] but reads the environment variable as defined at the os MACHINE/SYSTEM level,
    not the value of the environment variable in the current process context

    :param var_name:
    :param whole_machine: if True the env variables will be read from the MACHINE level. If False it will be read from
    USER level
    :return:
    """
    raise NotImplementedError()


@staticmethod
def p_number_number_string_value(p):
    """number_number_string_value : NUMERIC NUMERIC STRING"""
    p[0] = p[1], p[2], p[3]


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 _resolve_name(name, package, level):
    """Resolve a relative module name to an absolute one."""
    bits = package.rsplit('.', level - 1)
    if len(bits) < level:
        raise ValueError('attempted relative import beyond top-level package')
    base = bits[0]
    return '{}.{}'.format(base, name) if name else base


def describe_stream(StreamArn=None, Limit=None, ExclusiveStartShardId=None):
    """
    Returns information about a stream, including the current status of the stream, its Amazon Resource Name (ARN), the composition of its shards, and its corresponding DynamoDB table.
    Each shard in the stream has a SequenceNumberRange associated with it. If the SequenceNumberRange has a StartingSequenceNumber but no EndingSequenceNumber , then the shard is still open (able to receive more stream records). If both StartingSequenceNumber and EndingSequenceNumber are present, then that shard is closed and can no longer receive more data.
    See also: AWS API Documentation

    Examples
    The following example describes a stream with a given stream ARN.
    Expected Output:

    :example: response = client.describe_stream(
        StreamArn='string',
        Limit=123,
        ExclusiveStartShardId='string'
    )

    :type StreamArn: string
    :param StreamArn: [REQUIRED]
            The Amazon Resource Name (ARN) for the stream.

    :type Limit: integer
    :param Limit: The maximum number of shard objects to return. The upper limit is 100.

    :type ExclusiveStartShardId: string
    :param ExclusiveStartShardId: The shard ID of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedShardId in the previous operation.

    :rtype: dict
    :return: {
        'StreamDescription': {
            'StreamArn': 'string',
            'StreamLabel': 'string',
            'StreamStatus': 'ENABLING'|'ENABLED'|'DISABLING'|'DISABLED',
            'StreamViewType': 'NEW_IMAGE'|'OLD_IMAGE'|'NEW_AND_OLD_IMAGES'|'KEYS_ONLY',
            'CreationRequestDateTime': datetime(2015, 1, 1),
            'TableName': 'string',
            'KeySchema': [
                {
                    'AttributeName': 'string',
                    'KeyType': 'HASH'|'RANGE'
                },
            ],
            'Shards': [
                {
                    'ShardId': 'string',
                    'SequenceNumberRange': {
                        'StartingSequenceNumber': 'string',
                        'EndingSequenceNumber': 'string'
                    },
                    'ParentShardId': 'string'
                },
            ],
            'LastEvaluatedShardId': 'string'
        }
    }

    :returns:
    the AWS customer ID.
    the table name
    the StreamLabel

    """
    pass


def mask_expand(invert: bool=True, use_cursor: bool=True, update_pivot:
    bool=True, smooth_iterations: int=2, mask_speed: int=5, use_normals:
    bool=True, keep_previous_mask: bool=False, edge_sensitivity: int=300):
    """Expands a mask from the initial active vertex under the cursor

    :param invert: Invert, Invert the new mask
    :type invert: bool
    :param use_cursor: Use Cursor, Expand the mask to the cursor position
    :type use_cursor: bool
    :param update_pivot: Update Pivot Position, Set the pivot position to the mask border after creating the mask
    :type update_pivot: bool
    :param smooth_iterations: Smooth iterations
    :type smooth_iterations: int
    :param mask_speed: Mask speed
    :type mask_speed: int
    :param use_normals: Use Normals, Generate the mask using the normals and curvature of the model
    :type use_normals: bool
    :param keep_previous_mask: Keep Previous Mask, Generate the new mask on top of the current one
    :type keep_previous_mask: bool
    :param edge_sensitivity: Edge Detection Sensitivity, Sensitivity for expanding the mask across sculpted sharp edges when using normals to generate the mask
    :type edge_sensitivity: int
    """
    pass


def int_or_str(text):
    """Helper function for argument parsing."""
    try:
        return int(text)
    except ValueError:
        return text


def fitsdate(date):
    """
-----------------------------------------------------------------------
Purpose:   Given a string from a FITS file, try to parse it and
           convert the string into three parts: an integer year, an
           integer month and a fractional day.
Input:     A string, representing a date in FITS format
Returns:   Integer year, integer month, fractional day.
Reference: -
Notes:     Process the FITS dates as part of the 'epochs' function.
           It processes the following formats:
           DD/MM/YY or DD/MM/19YY
           YYYY-MM-DD
           YYYY-MM-DDTHH:MM:SS
-----------------------------------------------------------------------
   """
    parts = date.split('/')
    if len(parts) == 3:
        return int(parts[2]) % 1900 + 1900, int(parts[1]), float(parts[0])
    parts = date.split('T')
    if len(parts) == 2:
        date = parts[0]
        parts = parts[1].split(':')
        facts = 3600.0, 60.0, 1.0
        time = 0.0
        for i in range(len(parts)):
            time += float(parts[i]) * facts[i]
    else:
        time = 0.0
    parts = date.split('-')
    return int(parts[0]), int(parts[1]), float(parts[2]) + time / 86400.0


@staticmethod
def _calc_vpp_workers(node, vpp_workers, numa_node, other_cpus_end,
    total_vpp_workers, reserve_vpp_main_core):
    """
        Calculate the VPP worker information

        :param node: Node dictionary
        :param vpp_workers: List of VPP workers
        :param numa_node: Numa node
        :param other_cpus_end: The end of the cpus allocated for cores
        other than vpp
        :param total_vpp_workers: The number of vpp workers needed
        :param reserve_vpp_main_core: Is there a core needed for
        the vpp main core
        :type node: dict
        :type numa_node: int
        :type other_cpus_end: int
        :type total_vpp_workers: int
        :type reserve_vpp_main_core: bool
        :returns: Is a core still needed for the vpp main core
        :rtype: bool
        """
    cpus = node['cpu']['cpus_per_node'][numa_node]
    for cpu in cpus:
        start = cpu[0]
        end = cpu[1]
        if start <= other_cpus_end:
            start = other_cpus_end + 1
        if reserve_vpp_main_core:
            start += 1
        workers_end = start + total_vpp_workers - 1
        if workers_end <= end:
            if reserve_vpp_main_core:
                node['cpu']['vpp_main_core'] = start - 1
            reserve_vpp_main_core = False
            if total_vpp_workers:
                vpp_workers.append((start, workers_end))
            break
    if reserve_vpp_main_core:
        node['cpu']['vpp_main_core'] = other_cpus_end + 1
    return reserve_vpp_main_core


def console_output(access_key_id, secret_access_key, session_token, verbose):
    """ Outputs STS credentials to console """
    if verbose:
        print('Use these to set your environment variables:')
    exports = '\n'.join(['export AWS_ACCESS_KEY_ID=%s' % access_key_id,
        'export AWS_SECRET_ACCESS_KEY=%s' % secret_access_key,
        'export AWS_SESSION_TOKEN=%s' % session_token])
    print(exports)
    return exports


def HasShortCadence(ID, season=None):
    """
  Returns `True` if short cadence data is available for this target.

  :param int ID: The target ID number
  :param int season: The season number. Default :py:obj:`None`

  """
    raise NotImplementedError('This mission is not yet supported.')


def clear_empty_values(args):
    """
    Scrap junk data from a dict.
    """
    result = {}
    for param in args:
        if args[param] is not None:
            result[param] = args[param]
    return result


def yesno(prompt, default=None):
    """
    Prompt the user for a yes or no.

    Can optionally specify a default value, which will only be
    used if they enter a blank line.

    Unrecognised input (anything other than "y", "n", "yes",
    "no" or "") will return None.
    """
    answer = input(prompt).strip().lower()
    if answer == 'y' or answer == 'yes':
        return True
    elif answer == 'n' or answer == 'no':
        return False
    elif answer == '':
        return default
    else:
        return None


def get_stride(resnet_unit_id, block_id):
    """
    Determines the convolution stride.

    :param int resnet_unit_id: Which resnet unit
    (e.g. 0 is conv2_x, 1 is conv3_x)
    :param int block_id: Which block in the resnet unit (i.e. in the third
    unit of a 152-layer resnet, block_id=36)
    :return: Stride
    """
    if resnet_unit_id == 0 or block_id != 0:
        return 1
    else:
        return 2


@classmethod
def get_or_create(cls, file_path=None):
    """
        Returns the instance of the class (representing the singleton)
        or instantiate it if no instance already exists.
        If `file_path` is provided, starts to read it.
        """
    if cls._instance is None:
        cls._instance = cls(file_path)
    elif file_path is not None:
        cls._instance.open_file(file_path)
    return cls._instance


def setVerbosity(verbosity_level):
    """Copy verbosity to a variable that is global for this file.

        Parameters
        ----------
        verbosity_level: int
            an integer value indicating the level of verbosity

        """
    global verbosity
    verbosity = verbosity_level


def get_z_variable(nc):
    """
    Returns the name of the variable that defines the Z axis or height/depth

    :param netCDF4.Dataset nc: netCDF dataset
    """
    axis_z = nc.get_variables_by_attributes(axis='Z')
    if axis_z:
        return axis_z[0].name
    valid_standard_names = 'depth', 'height', 'altitude'
    z = nc.get_variables_by_attributes(standard_name=lambda x: x in
        valid_standard_names)
    if z:
        return z[0].name
    return


def partitioned(items, n=3):
    """Partition items into n buckets."""
    max_items_per_bucket, rem = divmod(len(items), n)
    if rem:
        max_items_per_bucket += 1
    bucket = []
    for item in items:
        if len(bucket) >= max_items_per_bucket:
            yield bucket
            bucket = []
        bucket.append(item)
    yield bucket


@classmethod
def parse(cls, value, evpn_overlay=False):
    """
        +---------------------------------+
        |  Flags (1 octet)                |
        +---------------------------------+
        |  Tunnel Type (1 octets)         |
        +---------------------------------+
        |  MPLS Label (3 octets)          |
        +---------------------------------+
        |  Tunnel Identifier (variable)   |
        +---------------------------------+
        :param value raw hex value
        """
    flag = ord(value[0:1])
    tunnel_type = ord(value[1:2])
    if evpn_overlay:
        mpls_label = cls.parse_vni(value[2:5])
    else:
        mpls_label = cls.parse_mpls_label(value[2:5])
    tunnel_id = cls.parse_tunnel_id(tunel_type=tunnel_type, tunel_data=
        value[5:])
    return {'leaf_info_required': flag, 'tunnel_type': tunnel_type,
        'mpls_label': [mpls_label], 'tunnel_id': tunnel_id}


def get_device_info(bigip):
    """Get device information for the current device being queried

    :param bigip: ManagementRoot object --- device to query
    :returns: ManagementRoot object
    """
    coll = bigip.tm.cm.devices.get_collection()
    device = [device for device in coll if device.selfDevice == 'true']
    return device[0]


@staticmethod
def escape(expression, quote=True):
    """
        >>> Syntax.escape("SELECT 'abcdefgh' FROM foobar") == u"SELECT 'abcdefgh' FROM foobar"
        True
        """
    return expression


def execute_statement(cursor, sql, params=None):
    """
    Executes a dml or ddl statement.
    If the input statement is not dml/ddl, then the statement is executed and nothing is returned.
    :param cursor: The input cursor.
    :param sql:    The sql to be executed
    :param params: The parameters
    :return:
    """
    cursor.execute(sql, params if params else {})


def add_list_parser(sub_parser):
    """
    Adds a sub-parser for the "list" sub-command to the parser provided.

    :param sub_parser: the parser to add to
    :type sub_parser: <class 'argparse.ArgumentParser'>
    """
    list_parser = sub_parser.add_parser('list', help='List file in remote')
    list_parser.add_argument('remote', help='remote to list')


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

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


@classmethod
def assert_equal(cls, old, new):
    """
        This method is used by asdf to test that to_tree > from_tree gives an
        equivalent object.
        """
    assert new == old


def safe_string_strip(value):
    """
    Returns the supplied string with leading and trailing whitespace removed
    If the supplied argument is not of type string the argument will gracefully be returned (no exception raised)
    """
    return value.strip() if value != None and type(value) is str else value


def tnuc_region_in_exon(np, beg, end):
    """ region in tnuc positions """
    if beg.tpos != 0:
        return False
    if end.tpos != 0:
        return False
    for i in range(beg.pos, end.pos - 1):
        if abs(np[i] - np[i + 1]) != 1:
            return False
    return True


def saymod1():
    """say mod 1 example"""
    return 'mod 1'


def childDataReceived(childFD, data):
    """
        Called when data arrives from the child process.

        @type childFD: L{int}
        @param childFD: The file descriptor from which the data was
            received.

        @type data: L{bytes}
        @param data: The data read from the child's file descriptor.
        """


def every(predicate, iterable):
    """Determines whether the predicate is true for all elements in the iterable.

  :param predicate:
      Predicate function of the form::

          f(x) -> bool
  :param iterable:
      Iterable sequence.
  :returns:
      ``True`` if the predicate is true for all elements in the iterable.
  """
    for item in iterable:
        if not predicate(item):
            return False
    return True


def _bool(val):
    """A wrapper around standard bool() which doesn't throw on NumPy arrays"""
    try:
        return bool(val)
    except ValueError:
        return False


def architecture_is_32bit(arch):
    """
	Check if the architecture specified in *arch* is 32-bit.

	:param str arch: The value to check.
	:rtype: bool
	"""
    return bool(arch.lower() in ('i386', 'i686', 'x86'))


def _pluralize(value, item_key):
    """"Force the value of a datacite3 key to be a list.

    >>> _pluralize(xml_input['authors'], 'author')
    ['Sick, Jonathan', 'Economou, Frossie']

    Background
    ----------
    When `xmltodict` proceses metadata, it turns XML tags into new key-value
    pairs whenever possible, even if the value should semantically be treated
    as a `list`.

    For example

    .. code-block:: xml

       <authors>
         <author>Sick, Jonathan</author>
       </authors

    Would be rendered by `xmltodict` as::

       {'authors': {'author': 'Sick, Jonathan'}}

    While

    .. code-block:: xml

       <authors>
         <author>Sick, Jonathan</author>
         <author>Economou, Frossie</author>
       </authors

    is rendered by `xmltodict` as::

       {'authors': [{'author': ['Sick, Jonathan', 'Economou, Frossie']}}

    This function ensures that values are *always* lists so that they can be
    treated uniformly.

    Parameters
    ----------
    value : obj
        The value of a key from datacite metadata extracted by `xmltodict`.
        For example, `xmldict['authors']`.
    item_key : str
        Name of the tag for each item; for example, with the `'authors'` key
        the item key is `'author'`.

    Returns
    -------
    item_values : list
        List of values of all items.
    """
    v = value[item_key]
    if not isinstance(v, list):
        return [v]
    else:
        return v


def bytes_to_str(input_bytes):
    """Convert bytes to string.
  """
    return input_bytes.decode()


def copycache(srcrepo, destrepo):
    """Copy cached attributes from srcrepo to destrepo"""
    destfilecache = destrepo._filecache
    srcfilecache = srcrepo._filecache
    if b'changelog' in srcfilecache:
        destfilecache[b'changelog'] = ce = srcfilecache[b'changelog']
        ce.obj.opener = ce.obj._realopener = destrepo.svfs
    if b'obsstore' in srcfilecache:
        destfilecache[b'obsstore'] = ce = srcfilecache[b'obsstore']
        ce.obj.svfs = destrepo.svfs
    if b'_phasecache' in srcfilecache:
        destfilecache[b'_phasecache'] = ce = srcfilecache[b'_phasecache']
        ce.obj.opener = destrepo.svfs


def edir(calc, val):
    """https://www.quantum-espresso.org/Doc/INPUT_PW.html#edir
    """
    assert isinstance(val, int)
    assert val in [1, 2, 3]


def _table_set_column(table, name, expr):
    """
    Replace an existing column with a new expression

    Parameters
    ----------
    name : string
      Column name to replace
    expr : value expression
      New data for column

    Returns
    -------
    set_table : TableExpr
      New table expression
    """
    expr = table._ensure_expr(expr)
    if expr._name != name:
        expr = expr.name(name)
    if name not in table:
        raise KeyError('{0} is not in the table'.format(name))
    proj_exprs = []
    for key in table.columns:
        if key == name:
            proj_exprs.append(expr)
        else:
            proj_exprs.append(table[key])
    return table.projection(proj_exprs)


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

        :param PaperDocEditCommentDetails val:
        :rtype: EventDetails
        """
    return cls('paper_doc_edit_comment_details', val)


def listenUDP(port, protocol, interface='', maxPacketSize=8192):
    """
        Connects a given DatagramProtocol to the given numeric UDP port.

        @return: object which provides L{IListeningPort}.
        """


def instance(cls, *args, **kwargs):
    """Alternate constructor that returns a fresh instance"""
    return type.__call__(cls, *args, **kwargs)


def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


def eliminate_self_loops(A):
    """Remove self-loops from the adjacency matrix."""
    A = A.tolil()
    A.setdiag(0)
    A = A.tocsr()
    A.eliminate_zeros()
    return A


@classmethod
def from_json(Profile, n):
    """
        Creates a Profile object from a dictionary that contains keys values equivalent to the name of the instance variables of the Profile class

        :param i: Dictionary containing key-value pairs, where the keys values are equivalent to the name of the instance variables in the Profile class
        :type i: dict

        :return: Profile whose instance variables contain the values from the dictionary
        :rtype: Profile
        """
    profile = Profile(id=n.get('id'), active=n.get('active'), password=n.
        get('password'), number=n.get('number'), tcdate=n.get('tcdate'),
        tmdate=n.get('tmdate'), referent=n.get('referent'), packaging=n.get
        ('packaging'), invitation=n.get('invitation'), readers=n.get(
        'readers'), nonreaders=n.get('nonreaders'), signatures=n.get(
        'signatures'), writers=n.get('writers'), content=n.get('content'),
        metaContent=n.get('metaContent'), tauthor=n.get('tauthor'))
    return profile


def delete_replication_task(ReplicationTaskArn=None):
    """
    Deletes the specified replication task.
    See also: AWS API Documentation

    :example: response = client.delete_replication_task(
        ReplicationTaskArn='string'
    )

    :type ReplicationTaskArn: string
    :param ReplicationTaskArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the replication task to be deleted.

    :rtype: dict
    :return: {
        'ReplicationTask': {
            'ReplicationTaskIdentifier': 'string',
            'SourceEndpointArn': 'string',
            'TargetEndpointArn': 'string',
            'ReplicationInstanceArn': 'string',
            'MigrationType': 'full-load'|'cdc'|'full-load-and-cdc',
            'TableMappings': 'string',
            'ReplicationTaskSettings': 'string',
            'Status': 'string',
            'LastFailureMessage': 'string',
            'StopReason': 'string',
            'ReplicationTaskCreationDate': datetime(2015, 1, 1),
            'ReplicationTaskStartDate': datetime(2015, 1, 1),
            'ReplicationTaskArn': 'string',
            'ReplicationTaskStats': {
                'FullLoadProgressPercent': 123,
                'ElapsedTimeMillis': 123,
                'TablesLoaded': 123,
                'TablesLoading': 123,
                'TablesQueued': 123,
                'TablesErrored': 123
            }
        }
    }

    """
    pass


def _run_sync(context, callback, *args, **kwargs):
    """ runs command for each instance in @all synchronously """
    config = context.obj.config
    logger = context.obj.logger
    results = []
    for instance_name in config.get_instances():
        logger.debug('running {} for instance: {}'.format(context.command.
            name, instance_name))
        config['current_instance'] = instance_name
        config['multi'] = True
        kwargs.update(context.params)
        result = callback(*args, **kwargs)
        results.append(result)
    return results


def isproperty(obj):
    """
    Is this a property?

    >>> class Foo:
    ...     def got(self):
    ...         return 2
    ...     def get(self):
    ...         return 1
    ...     get = property(get)

    >>> isproperty(Foo.got)
    False
    >>> isproperty(Foo.get)
    True
    """
    return type(obj) == property


def remove_suffix(string):
    """Removes suffixes

          Args:
              string:str
          Returns:
              returns str
          """
    suffixes = ['Esq', 'Ii', 'Iii', 'Iiii', 'Iv', 'Jnr', 'Jr', 'Sr']
    string = string.replace(' ', '')
    string = string.replace('.', '')
    string = string.replace(',', '')
    for suffix in suffixes:
        if string.endswith(suffix):
            string = string[:-len(suffix)]
            return string
    return string


def _print_results(tofiles):
    """Print git relations in human readable form"""
    sortable = []
    for filename, count in tofiles.items():
        sortable.append((count, filename))
    sortable.sort(reverse=True)
    for count, tofile in sortable[:10]:
        print('  {}  {}'.format(count, tofile))


def attach_ext(name, directory, extension):
    """Attach Extension to File."""
    return directory / (name + '.' + extension)


def learning_rate_warmup_distributed(learning_rate, epoch, warmup_epochs,
    num_workers, curr_step, steps_per_epoch):
    """Implements gradual learning rate warmup:
    `lr = initial_lr / hvd.size()` ---> `lr = initial_lr`
     `initial_lr` is the learning rate of the model optimizer at the start
     of the training. This technique was described in the paper
     "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour".
     See https://arxiv.org/pdf/1706.02677.pdf for details.

     Inspired by Horovod's implementation:
     https://github.com/uber/horovod/blob/master/horovod/keras/callbacks.py#L202
     Math recap:
                                                   curr_step
            epoch               = full_epochs + ---------------
                                                steps_per_epoch
                                   lr     size - 1
            lr'(epoch)          = ---- * (-------- * epoch + 1)
                                  size     warmup
                                   lr
            lr'(epoch = 0)      = ----
                                  size
            lr'(epoch = warmup) = lr
    """
    if epoch > warmup_epochs:
        return learning_rate
    else:
        epoch_adjusted = float(epoch) + curr_step / steps_per_epoch
        return learning_rate / num_workers * (epoch_adjusted * (num_workers -
            1) / warmup_epochs + 1)


def edit_mesh_extrude_move_shrink_fatten():
    """Extrude region together along local normals

    """
    pass


def _compressbits(bitvector, wordsize=32):
    """Compress binary vector into vector of long ints.

    This function is used by the Fingerprint class.

    >>> _compressbits([0, 1, 0, 0, 0, 1], 2)
    [2, 0, 2]
    """
    ans = []
    for start in range(0, len(bitvector), wordsize):
        compressed = 0
        for i in range(wordsize):
            if i + start < len(bitvector) and bitvector[i + start]:
                compressed += 2 ** i
        ans.append(compressed)
    return ans


def pairiter(seq):
    """Returns an iterator that yields consecutive pairs from seq."""
    it = iter(seq)
    while True:
        try:
            yield [next(it), next(it)]
        except (RuntimeError, StopIteration):
            return


def console_command(parameters):
    """
        Handle a command.

        :param list parameters: additional parameters passed to the command

        :returns: a generator object or other iterable yielding lines
        """


@staticmethod
def _fix_quoting(text):
    """fix broken Thunderbird quoting"""
    import re
    text = re.sub(re.compile('^=3D', flags=re.MULTILINE), '=', text)
    return text


def make_vector(dim, init_value):
    """
    Return a list of dim copies of init_value
    """
    return [init_value] * dim


def prepare_lookup_value(key, value):
    """
    Returns a lookup value prepared to be used in queryset filtering.
    """
    if key.endswith('__in'):
        value = value.split(',')
    if key.endswith('__isnull') and type(value) == str:
        if value.lower() in ('', 'false'):
            value = False
        else:
            value = True
    return value


@classmethod
def from_stream(cls, stream, marker_code, offset):
    """
        Extract the horizontal and vertical dots-per-inch value from the APP1
        header at *offset* in *stream*.
        """
    segment_length = stream.read_short(offset)
    if cls._is_non_Exif_APP1_segment(stream, offset):
        return cls(marker_code, offset, segment_length, 72, 72)
    tiff = cls._tiff_from_exif_segment(stream, offset, segment_length)
    return cls(marker_code, offset, segment_length, tiff.horz_dpi, tiff.
        vert_dpi)


def __call__():
    """Shortcut to new()"""


def my_callback(file_path):
    """Callback for new file"""
    print('New File Created: {:s}'.format(file_path))


def get_content_type(content_type, package='.'):
    """ Get Content from kotti package.

    :param content_type:       Class name of the content type
    :param package:            Package path of the content type
    :returns:                  Content type

    """
    imported = getattr(__import__(package, fromlist=[content_type]),
        content_type)
    return imported


def sig_code(p_value):
    """create a significance code in the style of R's lm

    Arguments
    ---------
    p_value : float on [0, 1]

    Returns
    -------
    str
    """
    assert 0 <= p_value <= 1, 'p_value must be on [0, 1]'
    if p_value < 0.001:
        return '***'
    if p_value < 0.01:
        return '**'
    if p_value < 0.05:
        return '*'
    if p_value < 0.1:
        return '.'
    return ' '


def format_traceback(traceback_string):
    """Format traceback."""
    formatted_lines = traceback_string.splitlines()
    formatted_lines.pop(1)
    formatted_lines.pop(1)
    formatted_error_string = '\n'.join(formatted_lines)
    formatted_error_string = formatted_error_string.replace('File "<string>"',
        'Plugin script')
    return formatted_error_string


@classmethod
def content_info(cls, options):
    """Get current capsule synchronization status."""
    cls.command_sub = 'content info'
    result = cls.execute(cls._construct_command(options), output_format='json')
    return result


def with_version(p):
    """with_version adds a --version flag"""
    p.add_argument('--version', help='show version info', action='store_true')
    return p


def add(parent, data, mimetype=None, filename=None):
    """ add blob return uri """


def copula_mv_archimedean(u, transform, args=(), axis=-1):
    """generic multivariate Archimedean copula
    """
    phi = transform.evaluate
    phi_inv = transform.inverse
    cdfv = phi_inv(phi(u, *args).sum(axis), *args)
    return cdfv


def scroll_left(deltax: int=0, deltay: int=0):
    """Scroll the view left

    :param deltax: Delta X
    :type deltax: int
    :param deltay: Delta Y
    :type deltay: int
    """
    pass


def initial():
    """all incoming things except the last thing"""


def update_filter(filter_in):
    """
    Function to update a filter ID from the Vizier Photometry viewer VOTable to the filter ID from
    the SVO Filter Profile Service.

    Parameters
    ----------
    filter_in : str
        Filter ID in the format of the Vizier Photometry viewer.

    Returns
    -------
    str
        Filter ID in the format of the SVO Filter Profile Service.
    """
    if filter_in[0:5] == b'2MASS':
        filter_out = str(b'2MASS/2MASS.' + filter_in[6:])
    elif filter_in[0:4] == b'WISE':
        filter_out = str(b'WISE/WISE.' + filter_in[5:])
    elif filter_in[0:10] == b'GAIA/GAIA2':
        filter_out = str(filter_in[0:9] + b'0' + filter_in[10:])
    else:
        filter_out = None
    return filter_out


def invalidate(obj, func):
    """Invalidate cache for memoized function."""
    key = '_' + func
    try:
        delattr(obj, key)
    except AttributeError:
        pass


def return_empty():
    """return empty value"""
    pass


def escapeNewlinesCallback(u_match):
    """
	u_match: instance of _sre.SRE_Match
	"""
    ch = u_match.group(0)
    if ch == '\n':
        return '\\n'
    if ch == '\r':
        return '\\r'
    if ch == '\\':
        return '\\\\'
    return ch


def create_soil_type(s):
    """
    Function to create the description of the soil type.

    :param s: (str) Soil code.
    :return: (str) Description of the soil code.
    """
    string_noquote = s.replace("'", '')
    split_letters = list(string_noquote)
    dict_name = {'G': 'gravel', 'K': 'clay', 'L': 'loam', 'V': 'peat', 'Z':
        'sand'}
    dict_addition = {'z': 'sand', 's': 'silt', 'm': 'mineral', 'k': 'clay',
        'g': 'gravel', 'h': 'humeus'}
    dict_intensity = {'1': 5, '2': 10, '3': 15, '4': 20}
    dict_exceptions = {'GM': 'layer information missing', 'NBE':
        'soil cannot be classified properly', 'W': 'water'}
    soil_name = ''
    try:
        if string_noquote is not '':
            if string_noquote in dict_exceptions:
                soil_name = soil_name + dict_exceptions[string_noquote]
            else:
                sum_addition = 0
                percentage_main_component = 100
                main_component = dict_name[split_letters[0]]
                soil_additions = ''
                for i in range(1, len(split_letters)):
                    if split_letters[i] in dict_addition:
                        soil_additions = (soil_additions + ' with ' +
                            dict_addition[split_letters[i]])
                    elif split_letters[i] in dict_intensity:
                        soil_additions = soil_additions + ' ' + str(
                            dict_intensity[split_letters[i]]) + '%'
                        sum_addition = sum_addition + dict_intensity[
                            split_letters[i]]
                if sum_addition > 0:
                    percentage_main_component = (percentage_main_component -
                        sum_addition)
                soil_name = main_component + ' ' + str(
                    percentage_main_component) + '%' + soil_additions
        else:
            soil_name = 'soil_not_defined'
    except KeyError:
        soil_name = 'soil_not_according_with_NEN_classification'
    return soil_name


def __call__():
    """boolean if item is by default excluded from navigation or not.
        """


@staticmethod
def clean_id(function_identifier):
    """
        Clean the funciton identifier string.
        """
    if function_identifier.startswith('__be_'):
        function_identifier = function_identifier[len('__be_'):]
    if '.' in function_identifier:
        function_identifier = function_identifier.split('.')[0]
    return function_identifier


def output_results(result_rows):
    """Output the results to STDOUT"""
    for row in result_rows:
        print(row + ';')


def p_class_statement_list(p):
    """class_statement_list : class_statement_list class_statement
                            | empty"""
    if len(p) == 3:
        p[0] = p[1] + [p[2]]
    else:
        p[0] = []


def extract_label(oLine):
    """
    Returns the label.

    Parameters:

       oLine: (line object)

    Returns: (one element list of strings)
    """
    return [oLine.line.replace(' ', '').split(':')[0]]


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 is_channel(string):
    """
    Return True if input string is a channel
    """
    return string and string[0] in '#&+!'


def v_relative(v, met):
    """ Estimates the relative air velocity which combines the average air velocity of the space plus the relative air velocity caused by the body movement.

    Parameters
    ----------
    v : float
        air velocity measured by the sensor, [m/s]
    met : float
        metabolic rate, [met]

    Returns
    -------
    vr  : float
        relative air velocity, [m/s]
    """
    if met > 1:
        return round(v + 0.3 * (met - 1), 3)
    else:
        return v


def items():
    """Return '(key, value)' pairs for the keys in the container.
        """


def mk_part_uri(uri: str, idx: int) ->str:
    """ Appends fragment part to the uri recording index of the part
    """
    return '{}#part={:d}'.format(uri, idx)


def rm(client, access_key):
    """Remove security credentials."""
    credentials = client.user.credentials(method='DELETE', accessKey=access_key
        )
    return credentials


def _byteshr(bytes):
    """Human-readable version of bytes count"""
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if bytes < 1024.0:
            return '%3.1f%s' % (bytes, x)
        bytes /= 1024.0
    raise ValueError('cannot find human-readable version')


def separate():
    """Isolate selected bones into a separate armature

    """
    pass


def seconds_to_timecode(seconds):
    """
    Converts seconds into a conditioned and simplified timecode string
    :param seconds: float, seconds
    :return: string, timecode in 'HH:MM:SS.SSS' format
    """
    h, s = divmod(seconds, 3600)
    m, s = divmod(s, 60)
    s = round(s * 1000) / 1000
    hh = str(int(h))
    mm = str(int(m))
    ss = str(s)
    if len(hh) < 2:
        hh = '0' + hh
    if len(mm) < 2:
        mm = '0' + mm
    if ss.find('.') > 1:
        wholes, decimals = ss.split('.')
    else:
        wholes = ss
    if len(wholes) < 2:
        ss = '0' + ss
    return '{0}:{1}:{2}'.format(hh, mm, ss)


@classmethod
def transform(cls, pts):
    """Override in sub-classes to transform points."""
    raise NotImplementedError


@classmethod
def name(cls):
    """
    Subclasses (Classifier, NearestNeighbor, ... etc.) must override this
    method and return its service name (classifier, nearest_neighbor, ... etc.)
    """
    raise NotImplementedError()


@classmethod
def _get_pepmass(cls, string, key='PEPMASS'):
    """ Strips key from mass and returns an Ion object. """
    pepmass = cls._split_kvline(key, string)
    return cls._get_ion(pepmass)


def align(positionner_list, alignement):
    """
        Function to align all given elements defined by their positionner.

        alignement:

        'left': align left
        'right': align right
        'xcenter': align center (verticaly)
        'ycenter': align center (horizontaly)
        'baseline': if all elements are text align their baseline
        'top': align top
        'bottom': align bottom

    """
    print('TODO')


def filter2query(filter):
    """
    http://docs.mongodb.org/manual/reference/operator/query/
    """
    query = {}
    filter = filter or {}
    for k, v in filter.items():
        if isinstance(v, tuple):
            operator, v = v
            mop = '$%s' % operator
            value = {mop: v}
        elif isinstance(v, list):
            value = {'$in': v}
        else:
            value = v
        query[k] = value
    """
    if keyword:
        #filter = {'description':{"$regex": keyword}}
        mongokeywordfilter = {"$or": [
            {"description": {"$regex": keyword,'$options':'i'}},
            {"title": {"$regex": keyword,'$options':'i'}}
        ]}
        query = {
            "$and": [ query, mongokeywordfilter ]
        }
    """
    return query


def size_in_bytes(data):
    """
    Gets the size in bytes of a str.
    @return: long
    """
    return len(data)


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

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


def many_point_hist_update(hist, diff_hist, inplace=True):
    """
  many_point_hist_update(hist, diff_hist)

  Update the complete_history structure after a many calls to f.

  WARNING! The complete_history structure uses your bounds, and is
  not scaled to make 0 <= x(i) <= 1."""
    if not inplace:
        hist = hist.copy()
    if type(diff_hist.good_points) == list:
        hist.good_points.extend(diff_hist.good_points)
    else:
        for i in range(diff_hist.good_points.shape[1]):
            hist.good_points.append(diff_hist.good_points[:, (i)])
    hist.good_values.extend(diff_hist.good_values)
    hist.failed_points.extend(diff_hist.failed_points)
    return hist


def starts(epsilon=0):
    """Returns a function that computes whether a temporal interval has the
    same start time as another interval (+/- epsilon), and ends before it.

    The output function expects two temporal intervals (dicts with keys 't1'
    and 't2' for the start and end times, respectively). It returns ``True`` if
    the first interval starts at the same time as the second interval (+/-
    ``epsilon``), and the first interval ends before the second interval.

    Args:
        epsilon: The maximum difference between the start time of the first
            interval and the start time of the second interval.

    Returns:
        An output function that takes two temporal intervals and returns
        ``True`` if the first interval starts at the same time as the second
        interval, and ends before the second interval ends.
    """
    return lambda intrvl1, intrvl2: abs(intrvl1['t1'] - intrvl2['t1']
        ) <= epsilon and intrvl1['t2'] < intrvl2['t2']


def gainFromId(allMedia, hashtag, id):
    """
    Print XP Gain from one post
    :param allMedia: All your Instagram posts
    :param hashtag: Specific hashtag for Yum4FIT
    :param id: ID of the media
    :return: XP Gain
    """
    summary = 0
    for post in allMedia:
        if post['caption'] != None and post['id'] == id:
            if hashtag in post['caption']['text']:
                likes_count = post['like_count']
                summary += int(likes_count)
    return summary


def swap_inputs():
    """Swap the first two inputs for the effect strip

    """
    pass


def markLocation(stream):
    """Creates text file showing current location in context."""
    RADIUS = 5000
    stream.seek(-RADIUS, 1)
    outputDoc = open('PyPDF4_pdfLocation.txt', 'w')
    outputDoc.write(stream.read(RADIUS))
    outputDoc.write('HERE')
    outputDoc.write(stream.read(RADIUS))
    outputDoc.close()
    stream.seek(-RADIUS, 1)


def argmax_channel(data=None, out=None, name=None, **kwargs):
    """Returns argmax indices of each channel from the input array.

    The result will be an NDArray of shape (num_channel,).

    In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence
    are returned.

    Examples::

      x = [[ 0.,  1.,  2.],
           [ 3.,  4.,  5.]]

      argmax_channel(x) = [ 2.,  2.]

    Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L97

    Parameters
    ----------
    data : NDArray
        The input array

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

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


def quantity_to_hdf5(f, key, q):
    """
    Turn an Astropy Quantity object into something we can write out to
    an HDF5 file.

    Parameters
    ----------
    f : :class:`h5py.File`, :class:`h5py.Group`, :class:`h5py.DataSet`
    key : str
        The name.
    q : float, `astropy.units.Quantity`
        The quantity.

    """
    if hasattr(q, 'unit'):
        f[key] = q.value
        f[key].attrs['unit'] = str(q.unit)
    else:
        f[key] = q
        f[key].attrs['unit'] = ''


def project_opened(project):
    """This function is called after opening the project"""


def obliquity2000(jd):
    """
----------------------------------------------------------------------
Purpose:   What is the obliquity of the ecliptic at this Julian date?
           IAU2000
Input:     Julian date
Returns:   Mean obliquity in degrees
Reference: Fukushima, T. 2003, AJ, 126,1
           Kaplan, H., 2005, , The IAU Resolutions
           on Astronomical Reference Systems,
           Time Scales, and Earth Rotation Models,
           United States Naval Observatory circular no. 179,
           http://aa.usno.navy.mil/publications/docs/Circular_179.pdf
           (page 44)
notes:     The epoch is entered in Julian date and the time is calculated
           w.r.t. J2000
           The obliquity is the angle between the mean equator and
           ecliptic, or, between the ecliptic pole and mean celestial
           pole of date.
----------------------------------------------------------------------
   """
    T = (jd - 2451545.0) / 36525.0
    eps = (84381.406 + (-46.836769 + (-0.0001831 + (0.0020034 + (-5.76e-07 +
        -4.34e-08 * T) * T) * T) * T) * T) / 3600.0
    return eps


def postpone():
    """Do nothing. The message will stay in claim an eventually revert
        back to new.
        """


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 reduce_dirs(dirs: list) ->list:
    """Given a sequence of directories, remove duplicates and any directories nested in one of the other paths. (Useful for recursive path searching).

    :param dirs: Sequence of directory paths.
    :type dirs: list
    :return:  A unique list of paths.
    """
    pass


def get_root_storage_index_string():
    """Return the storage index (abbreviated human-readable string) of
        the first object checked."""


def get_grid_capacity(grid, plus, minus):
    """Read the grid capacity from a given region pair from the renpass db."""
    tmp_grid = grid.query('plus_region_id == {:0d} & '.format(plus) +
        'minus_region_id == {:1d} & '.format(minus) +
        "scenario_name == 'status_quo_2012_distance'")
    if len(tmp_grid) > 0:
        capacity = tmp_grid.capacity_calc.sum()
        distance = tmp_grid.distance.iloc[0]
    else:
        capacity = 0
        distance = 0
    return capacity, distance


@classmethod
def close_all_sessions(cls):
    """Close and remove all sessions in cls.session_instances."""
    for session in cls.session_instances:
        session.close()
    cls.session_instances = []


@classmethod
def find_by_url(cls, url):
    """Returns all tracks with the specified download URL."""
    return cls.where('`download` = ?', [url])


def close():
    """
        Release the resources held by this instance and all child instances.
        """


def matchCalendars(calendars):
    """
    Matches calendars against each other

    :param calendars: array containing all calendars to match
    :type calendars: array
    :return: Matched calendarpattern
    :rtype: dict
    """
    calendarPattern = []
    for i in range(24):
        calendarPattern.append(i)
        calendarPattern[i] = []
        for j in range(4):
            calendarPattern[i].append(j)
            calendarPattern[i][j] = 0
    for calendar in calendars:
        if calendar is not None:
            for i in range(24):
                for j in range(4):
                    if calendar[i][j] == 1:
                        calendarPattern[i][j] = 1
    return calendarPattern


def wl_lockTokens(killinvalids=0):
    """ Returns a sequence of lock tokens.  if 'killinvalids' is true,
        invalid locks will be deleted"""


def add_marker_at_click():
    """Place new marker at the desired (clicked) position

    """
    pass


def activation_energy(molecule):
    """
    Extracts the final energy of a reactant from an Orca output file.

    **Parameters**

        molecule: *str*
            A string for the name of the simulation containing
            the optimized reactant.

    **Returns**

        E_tmp: *float*
            The energy of the optimized reactant.
    """
    lines = []
    E_tmp = 0
    f = open('orca/%s/%s.out' % (molecule, molecule), 'r')
    for line in f:
        lines.append(line.strip().split())
    f.close()
    for j in range(len(lines)):
        if len(lines[j]) > 4:
            if lines[j][0] == 'FINAL' and lines[j][1] == 'SINGLE' and lines[j][
                2] == 'POINT' and lines[j][3] == 'ENERGY':
                E_tmp = float(lines[j][4])
                break
    return E_tmp


def shape_key_remove(all: bool=False):
    """Remove shape key from the object

    :param all: All, Remove all shape keys
    :type all: bool
    """
    pass


def arcsinh(data=None, out=None, name=None, **kwargs):
    """Returns the element-wise inverse hyperbolic sine of the input array, \\
    computed element-wise.

    The storage type of ``arcsinh`` output depends upon the input storage type:

       - arcsinh(default) = default
       - arcsinh(row_sparse) = row_sparse
       - arcsinh(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L436

    Parameters
    ----------
    data : NDArray
        The input array.

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

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


def insert_offset():
    """Automatically offset nodes on insertion

    """
    pass


def _inversion_simple(a3, a0):
    """Solve for degree 5 polynomial with coefficients a5=1, a3=0., a0."""
    return (-a0) ** (1.0 / 5.0)


def read_fasta(inputfile):
    """Method for loading sequences from a FASTA formatted file into :py:attr:`sequences` & :py:attr:`names`.
    This method is used by the base class :class:`modlamp.descriptors.PeptideDescriptor` if the input is a FASTA file.

    :param inputfile: .fasta file with sequences and headers to read
    :return: list of sequences in the attribute :py:attr:`sequences` with corresponding sequence names in
        :py:attr:`names`.
    """
    names = list()
    sequences = list()
    seq = str()
    with open(inputfile) as f:
        all = f.readlines()
        last = all[-1]
        for line in all:
            if line.startswith('>'):
                names.append(line.split(' ')[0][1:].strip())
                sequences.append(seq.strip())
                seq = str()
            elif line == last:
                seq += line.strip()
                sequences.append(seq.strip())
            else:
                seq += line.strip()
    return sequences[1:], names


@classmethod
def make_category_tag(cls, category, value=None, tag_prefix=None, value_sep
    =None):
    """Build category tag (mostly for testing purposes).
        :return: Category tag as string (without leading AT char).
        """
    if tag_prefix is None:
        tag_prefix = cls.tag_prefixes[0]
    if value_sep is None:
        value_sep = cls.value_separator
    value = value or ''
    return '%s.with_%s%s%s' % (tag_prefix, category, value_sep, value)


def _write_log(*msg, end='\n'):
    """Write message to log output, ignoring the verbosity level.
    This is the most basic function.
    Parameters
    ----------
    *msg :
        One or more arguments to be formatted as string. Same behavior as print
        function.
    """
    from pypairs.settings import logfile
    if logfile == '':
        print(*msg, end=end)
    else:
        out = ''
        for s in msg:
            out += str(s) + ' '
        with open(logfile, 'a') as f:
            f.write(out + end)


def _check_for_invalid_keys(fname, kwargs, compat_args):
    """
    Checks whether 'kwargs' contains any keys that are not
    in 'compat_args' and raises a TypeError if there is one.
    """
    diff = set(kwargs) - set(compat_args)
    if diff:
        bad_arg = list(diff)[0]
        raise TypeError(
            f"{fname}() got an unexpected keyword argument '{bad_arg}'")


def _get_options_group(group=None):
    """Get a specific group of options which are allowed."""
    hex_options = frozenset(['--check-sigs', '--default-key',
        '--default-recipient', '--delete-keys', '--delete-secret-keys',
        '--delete-secret-and-public-keys', '--desig-revoke', '--export',
        '--export-secret-keys', '--export-secret-subkeys', '--fingerprint',
        '--gen-revoke', '--hidden-encrypt-to', '--hidden-recipient',
        '--list-key', '--list-keys', '--list-public-keys',
        '--list-secret-keys', '--list-sigs', '--recipient', '--recv-keys',
        '--send-keys', '--edit-key', '--sign-key'])
    unchecked_options = frozenset(['--list-options', '--passphrase-fd',
        '--status-fd', '--verify-options', '--command-fd'])
    other_options = frozenset(['--debug-level', '--keyserver'])
    dir_options = frozenset(['--homedir'])
    keyring_options = frozenset(['--keyring', '--primary-keyring',
        '--secret-keyring', '--trustdb-name'])
    file_or_none_options = frozenset(['--decrypt', '--decrypt-files',
        '--encrypt', '--encrypt-files', '--import', '--verify',
        '--verify-files', '--output'])
    pref_options = frozenset(['--digest-algo', '--cipher-algo',
        '--compress-algo', '--compression-algo', '--cert-digest-algo',
        '--personal-digest-prefs', '--personal-digest-preferences',
        '--personal-cipher-prefs', '--personal-cipher-preferences',
        '--personal-compress-prefs', '--personal-compress-preferences',
        '--pinentry-mode', '--print-md', '--trust-model'])
    none_options = frozenset(['--allow-loopback-pinentry', '--always-trust',
        '--armor', '--armour', '--batch', '--check-sigs', '--check-trustdb',
        '--clearsign', '--debug-all', '--default-recipient-self',
        '--detach-sign', '--export', '--export-ownertrust',
        '--export-secret-keys', '--export-secret-subkeys', '--fingerprint',
        '--fixed-list-mode', '--gen-key', '--import-ownertrust',
        '--list-config', '--list-key', '--list-keys', '--list-packets',
        '--list-public-keys', '--list-secret-keys', '--list-sigs',
        '--lock-multiple', '--lock-never', '--lock-once',
        '--no-default-keyring', '--no-default-recipient',
        '--no-emit-version', '--no-options', '--no-tty', '--no-use-agent',
        '--no-verbose', '--print-mds', '--quiet', '--sign', '--symmetric',
        '--throw-keyids', '--use-agent', '--verbose', '--version',
        '--with-colons', '--yes'])
    hex_or_none_options = hex_options.intersection(none_options)
    allowed = hex_options.union(unchecked_options, other_options,
        dir_options, keyring_options, file_or_none_options, pref_options,
        none_options)
    if group and group in locals().keys():
        return locals()[group]


def parse_ipv6_literal_host(entity, default_port):
    """Validates an IPv6 literal host:port string.

    Returns a 2-tuple of IPv6 literal followed by port where
    port is default_port if it wasn't specified in entity.

    :Parameters:
        - `entity`: A string that represents an IPv6 literal enclosed
                    in braces (e.g. '[::1]' or '[::1]:27017').
        - `default_port`: The port number to use when one wasn't
                          specified in entity.
    """
    if entity.find(']') == -1:
        raise ValueError(
            "an IPv6 address literal must be enclosed in '[' and ']' according to RFC 2732."
            )
    i = entity.find(']:')
    if i == -1:
        return entity[1:-1], default_port
    return entity[1:i], entity[i + 2:]


def square(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise squared value of the input.

    .. math::
       square(x) = x^2

    Example::

       square([2, 3, 4]) = [4, 9, 16]

    The storage type of ``square`` output depends upon the input storage type:

       - square(default) = default
       - square(row_sparse) = row_sparse
       - square(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L118

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

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

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


def timestring(input):
    """print with time prepended"""
    from time import localtime, strftime
    thetime = strftime('%H:%M:%S', localtime())
    print('%s: %s' % (thetime, input.lstrip()))


def with_y(p1, a2):
    """Returns the first argument (a coordinate pair) with the x value replaced with
    the second argument."""
    try:
        return p1[0], a2[1]
    except TypeError:
        return p1[0], a2


def _unplug_container(widget, container):
    """ The handler for a QDockContainer widget.

    If the widget matches the container, this handler will hide and
    unparent the container.

    """
    if widget is container:
        widget.hide()
        widget.showTitleBar()
        widget.setParent(None)
        return True, None
    return False, None


def update_columns(idx, single_session):
    """ Update name of columns according to the set Dataclass

    Parameters
    ----------
    idx             : int
        Dataclass index
    single_session  : boolean
        True if the project is single session

    Returns
    -------
    column          : dict
        New list of columns
    """
    if idx == 0:
        if single_session:
            subject, session, dtype = 1, 3, 2
        else:
            subject, session, dtype = 1, 2, 3
        columns = {(0): 'DataClass', subject: 'Subject', session: 'Session',
            dtype: 'DataType'}
    elif idx == 1:
        columns = {(0): 'DataClass', (1): 'Pipeline', (2): 'Step', (3):
            'Subject', (4): 'Session'}
    elif idx == 2:
        columns = {(0): 'DataClass', (1): 'Pipeline', (2): 'Result', (3):
            'Subject', (4): 'Session'}
    else:
        columns = {(0): 'DataClass'}
    return columns


def robust_add(a, b):
    """Add numbers a and b, treating None as 0"""
    if a is None:
        a = 0
    if b is None:
        b = 0
    return a + b


def get_main_package_directory(distribution):
    """
    Given a Distribution object, return the main package directory.
    """
    return min(distribution.packages, key=len)


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

        :param PaperExternalViewDefaultTeamDetails val:
        :rtype: EventDetails
        """
    return cls('paper_external_view_default_team_details', val)


def theta_Ba_H_PK74(T, P):
    """c-c': barium hydrogen [PK74]."""
    theta = -0.036
    valid = T == 298.15
    return theta, valid


@property
def all(cls):
    """List of `Option` objects"""
    return list(cls.__get_name_options_mapping().values())


def fill_pattern(var_list, pattern):
    """
    Replace values in pattern
    var_list has to have 'pattern' and 'value' keys
    pattern is a string with some keys inside
    """
    code = pattern
    for lista in var_list:
        keys = lista.keys()
        assert 'pattern' in keys and 'value' in keys, 'Lista incorrecta en ' + str(
            lista)
        code = code.replace(lista['pattern'], lista['value'])
    return code


def evict():
    """Remove all pended items whose lifetime has expired."""


def is_set(val):
    """
  Returns True iff this is a "set-like" type
  """
    return isinstance(val, (frozenset, set))


def make_fits_image(imagedata, wcsobj, beam, freq, equinox, telescope, xmin
    =0, ymin=0, is_mask=False, shape=None):
    """Makes a simple FITS hdulist appropriate for single-channel images"""
    from distutils.version import StrictVersion
    try:
        from astropy.io import fits as pyfits
        use_header_update = False
    except ImportError as err:
        import pyfits
        if StrictVersion(pyfits.__version__) < StrictVersion('3.1'):
            use_header_update = True
        else:
            use_header_update = False
    import numpy as np
    if is_mask and shape is not None:
        shape_out = shape
    else:
        shape_out = [1, 1, imagedata.shape[0], imagedata.shape[1]]
    hdu = pyfits.PrimaryHDU(np.resize(imagedata, shape_out))
    hdulist = pyfits.HDUList([hdu])
    header = hdulist[0].header
    if use_header_update:
        header.update('CRVAL1', wcsobj.wcs.crval[0])
        header.update('CDELT1', wcsobj.wcs.cdelt[0])
        header.update('CRPIX1', wcsobj.wcs.crpix[0] + xmin)
        header.update('CUNIT1', str(wcsobj.wcs.cunit[0]).strip().lower())
        header.update('CTYPE1', wcsobj.wcs.ctype[0])
        header.update('CRVAL2', wcsobj.wcs.crval[1])
        header.update('CDELT2', wcsobj.wcs.cdelt[1])
        header.update('CRPIX2', wcsobj.wcs.crpix[1] + ymin)
        header.update('CUNIT2', str(wcsobj.wcs.cunit[1]).strip().lower())
        header.update('CTYPE2', wcsobj.wcs.ctype[1])
    else:
        header['CRVAL1'] = wcsobj.wcs.crval[0]
        header['CDELT1'] = wcsobj.wcs.cdelt[0]
        header['CRPIX1'] = wcsobj.wcs.crpix[0] + xmin
        header['CUNIT1'] = str(wcsobj.wcs.cunit[0]).strip().lower()
        header['CTYPE1'] = wcsobj.wcs.ctype[0]
        header['CRVAL2'] = wcsobj.wcs.crval[1]
        header['CDELT2'] = wcsobj.wcs.cdelt[1]
        header['CRPIX2'] = wcsobj.wcs.crpix[1] + ymin
        header['CUNIT2'] = str(wcsobj.wcs.cunit[1]).strip().lower()
        header['CTYPE2'] = wcsobj.wcs.ctype[1]
    if use_header_update:
        header.update('CRVAL3', 1.0)
        header.update('CDELT3', 1.0)
        header.update('CRPIX3', 1.0)
        header.update('CUNIT3', ' ')
        header.update('CTYPE3', 'STOKES')
    else:
        header['CRVAL3'] = 1.0
        header['CDELT3'] = 1.0
        header['CRPIX3'] = 1.0
        header['CUNIT3'] = ''
        header['CTYPE3'] = 'STOKES'
    if use_header_update:
        header.update('RESTFRQ', freq)
        header.update('CRVAL4', freq)
        header.update('CDELT4', 300000000.0)
        header.update('CRPIX4', 1.0)
        header.update('CUNIT4', 'HZ')
        header.update('CTYPE4', 'FREQ')
        header.update('SPECSYS', 'TOPOCENT')
    else:
        header['RESTFRQ'] = freq
        header['CRVAL4'] = freq
        header['CDELT4'] = 300000000.0
        header['CRPIX4'] = 1.0
        header['CUNIT4'] = 'HZ'
        header['CTYPE4'] = 'FREQ'
        header['SPECSYS'] = 'TOPOCENT'
    if not is_mask:
        if use_header_update:
            header.update('BMAJ', beam[0])
            header.update('BMIN', beam[1])
            header.update('BPA', beam[2])
        else:
            header['BMAJ'] = beam[0]
            header['BMIN'] = beam[1]
            header['BPA'] = beam[2]
    if use_header_update:
        header.update('EQUINOX', equinox)
    else:
        header['EQUINOX'] = equinox
    if telescope is not None:
        if use_header_update:
            header.update('TELESCOP', telescope)
        else:
            header['TELESCOP'] = telescope
    hdulist[0].header = header
    return hdulist


@staticmethod
def _convert_indirect_jump_targets_to_states(job, indirect_jump_targets):
    """
        Convert each concrete indirect jump target into a SimState. If there are non-zero successors and the original
        jumpkind is a call, we also generate a fake-ret successor.

        :param job:                     The CFGJob instance.
        :param indirect_jump_targets:   A collection of concrete jump targets resolved from a indirect jump.
        :return:                        A list of SimStates.
        :rtype:                         list
        """
    first_successor = job.sim_successors.all_successors[0]
    successors = []
    for t in indirect_jump_targets:
        a = first_successor.copy()
        a.ip = t
        successors.append(a)
    if successors and first_successor.history.jumpkind == 'Ijk_Call':
        a = first_successor.copy()
        a.ip = job.cfg_node.addr + job.cfg_node.size
        a.history.jumpkind = 'Ijk_FakeRet'
        successors.append(a)
    return successors


def detach_typed_link(DirectoryArn=None, TypedLinkSpecifier=None):
    """
    Detaches a typed link from a specified source and target object. For more information, see Typed link .
    See also: AWS API Documentation

    :example: response = client.detach_typed_link(
        DirectoryArn='string',
        TypedLinkSpecifier={
            'TypedLinkFacet': {
                'SchemaArn': 'string',
                'TypedLinkName': 'string'
            },
            'SourceObjectReference': {
                'Selector': 'string'
            },
            'TargetObjectReference': {
                'Selector': 'string'
            },
            'IdentityAttributeValues': [
                {
                    'AttributeName': 'string',
                    'Value': {
                        'StringValue': 'string',
                        'BinaryValue': b'bytes',
                        'BooleanValue': True|False,
                        'NumberValue': 'string',
                        'DatetimeValue': datetime(2015, 1, 1)
                    }
                },
            ]
        }
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the directory where you want to detach the typed link.

    :type TypedLinkSpecifier: dict
    :param TypedLinkSpecifier: [REQUIRED]
            Used to accept a typed link specifier as input.
            TypedLinkFacet (dict) -- [REQUIRED]Identifies the typed link facet that is associated with the typed link.
            SchemaArn (string) -- [REQUIRED]The Amazon Resource Name (ARN) that is associated with the schema. For more information, see arns .
            TypedLinkName (string) -- [REQUIRED]The unique name of the typed link facet.
            SourceObjectReference (dict) -- [REQUIRED]Identifies the source object that the typed link will attach to.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

            TargetObjectReference (dict) -- [REQUIRED]Identifies the target object that the typed link will attach to.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

            IdentityAttributeValues (list) -- [REQUIRED]Identifies the attribute value to update.
            (dict) --Identifies the attribute name and value for a typed link.
            AttributeName (string) -- [REQUIRED]The attribute name of the typed link.
            Value (dict) -- [REQUIRED]The value for the typed link.
            StringValue (string) --A string data value.
            BinaryValue (bytes) --A binary data value.
            BooleanValue (boolean) --A Boolean data value.
            NumberValue (string) --A number data value.
            DatetimeValue (datetime) --A date and time value.

    """
    pass


@classmethod
def get_taxid(cls, entry):
    """
        get NCBI taxonomy identifier from XML node entry

        :param entry:X ML node entry
        :return: int
        """
    query = "./organism/dbReference[@type='NCBI Taxonomy']"
    return int(entry.find(query).get('id'))


def str_to_list(value):
    """
    Convert a newline terminated string into a list.  Any empty lines
    will be removed from the result list.

    Parameters
    ----------
    value : str
        The string object to convert to a list

    Returns
    -------
    list
        List based on the string
    """
    result_list = []
    for item in value.strip().split('\n'):
        item = item.strip()
        if item:
            result_list.append(item)
    return result_list


def cc_flags():
    """Get the compiler flags necessary for including the interface
    library in a C or C++ program.

    Returns:
        list: The necessary compiler flags and preprocessor definitions.

    """
    from yggdrasil.drivers import CModelDriver
    print(' '.join(CModelDriver.CModelDriver.get_compiler_flags(for_model=
        True)))


def PUSH(expression):
    """
    Returns an array of all values that result from applying an expression
    to each document in a group of documents that share the same group by key.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/push/
    for more details
    :param expression: expression
    :return: Aggregation operator
    """
    return {'$push': expression}


def build_condition(bcstr):
    """decode build condition"""
    if bcstr == 'BC':
        bcstr += ' (as-built)'
    elif bcstr == 'CC':
        bcstr += ' (as-current)'
    elif bcstr == 'RC':
        bcstr += ' (as-repaired)'
    elif bcstr == 'OT':
        bcstr += ' (other)'
    else:
        bcstr += ' (unknown)'
    return bcstr


def context(input):
    """Return the context/device of the input tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    Context object
        A framework-specific context object.
    """
    pass


def set_debug_console(value):
    """Set debug console enable."""
    global DEBUG_CONSOLE
    DEBUG_CONSOLE = bool(value)


def get_reference(condition_ref_string, stats_df):
    """
    If condition_ref_string matches a column in stats_df, return that
    column. If it doesn't match a column, try to convert it to a float.

    :param str condition_ref_string: left or right part of a condition             from a QC conditions file
    :param stats_df: QC statistics table
    :type stats_df: :class:`~pandas.DataFrame`
    :returns: Either a column of stats_df, a float or a string.
    """
    if condition_ref_string in stats_df.columns:
        return stats_df.loc[:, (condition_ref_string)]
    try:
        return float(condition_ref_string)
    except ValueError:
        return condition_ref_string