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

        :param ShowcaseFileViewType val:
        :rtype: EventType
        """
    return cls('showcase_file_view', val)


def init_value(value, default_value):
    """Returns the value if it is not None. Otherwise, returns the default
    value.

    Parameters
    ----------
    value: any
    default_value: any

    Returns
    -------
    any
    """
    return value if not value is None else default_value


def resolve_path_parts(path_parts):
    """Normalize the URL path by resolving segments of '.' and '..',
    resulting in a dot-free path.  See RFC 3986 section 5.2.4, Remove
    Dot Segments.
    """
    ret = []
    for part in path_parts:
        if part == u'.':
            pass
        elif part == u'..':
            if ret and (len(ret) > 1 or ret[0]):
                ret.pop()
        else:
            ret.append(part)
    if list(path_parts[-1:]) in ([u'.'], [u'..']):
        ret.append(u'')
    return ret


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 prepare_search(search_term):
    """Return a search term that the api can use to query the db
    :param search_term: string
    :return: search dict
    """
    if search_term:
        return {'match': [{'_all': search_term}]}
    return {}


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables. The same goes for tuples, since they are immutable and therefore
    valid entries.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str
        ) and not isinstance(obj, tuple)


def reslice_img(img, new_zooms=None, order=3):
    """ Performs regridding of an image to set isotropic voxel sizes using dipy.
    If the file has already isotropic voxels, will return a copy of the same image.

    Parameters
    ----------
    img: nibabel.Nifti1Image
        The diffusion image.

    new_zooms : tuple, shape (3,)
        new voxel size for (i,j,k) after resampling

    order : int, from 0 to 5
       order of interpolation for resampling/reslicing, 0 nearest interpolation, 1 trilinear etc..
       if you don’t want any smoothing 0 is the option you need.

    Returns
    -------
    nu_img: nibabel.Nifti1Image
        A isotropic voxel version from `img`.
    """
    import numpy as np
    import nibabel as nib
    from dipy.align.reslice import reslice
    data = img.get_data()
    img_zooms = img.header.get_zooms()[:3]
    all_equal = len(np.unique(img_zooms)) == 1
    if all_equal:
        return nib.Nifti1Image(img.get_data(), affine=img.affine, header=
            img.header)
    if new_zooms is None:
        minzoom = np.array(img_zooms).min()
        new_zooms = tuple(np.ones((3,)) * minzoom)
    nu_data, nu_affine = reslice(data=data, affine=img.affine, zooms=
        img_zooms, new_zooms=new_zooms, order=order)
    header = img.header.copy()
    tmp_zooms = np.array(header.get_zooms())
    tmp_zooms[:3] = new_zooms[0]
    header.set_zooms(tuple(tmp_zooms))
    header.set_data_shape(nu_data.shape)
    header.set_xyzt_units('mm')
    nu_img = nib.Nifti1Image(nu_data.astype(header.get_data_dtype()),
        nu_affine, header)
    return nu_img


def _write_pred_sum(path_res, ipred, ndone, ntot, t_pred):
    """ `_write_pred_sum` writes a text file that summarized the overall
    progress of the predictions at 'popex.path_res'.

    The file structure is as followes:
        | <popex.path_res>$
        |    └- pred_progress.txt

    Parameters
    ----------
    path_res : str
        Path to where the results should be saved
    ipred : int
        Index of last predictions
    ndone : int
        Number of computed predictions
    ntot : int
        Number of total predictions
    t_pred : float
        Total time elapsed

    Returns
    -------
    None
    """
    bar_width = 40
    progress = ndone / ntot
    t_mod = t_pred / ndone
    m_pred, s_pred = divmod(t_pred, 60)
    h_pred, m_pred = divmod(m_pred, 60)
    m_mod, s_mod = divmod(t_mod, 60)
    h_mod, m_mod = divmod(m_mod, 60)
    t_est = t_pred / progress
    m_est, s_est = divmod(t_est, 60)
    h_est, m_est = divmod(m_est, 60)
    with open('{}pred_progress.txt'.format(path_res), 'w+') as file:
        file.write('PREDICTION PROGRESS SUMMARY\n')
        file.write('---------------------------\n')
        file.write('\n')
        nfull = int(bar_width * progress)
        nempty = bar_width - nfull
        file.write('  Status\n')
        file.write('    n_mod    = {:6d} / {:6d}    (last: {:6d})\n'.format
            (ndone, ntot, ipred))
        file.write('    [{:s}{:s}]'.format('-' * nfull, ' ' * nempty))
        file.write(' {:3.0f}%\n'.format(progress * 100))
        file.write('\n')
        file.write('  Time\n')
        file.write('    T_el     = {:4.0f}[h] {:2.0f}[m] {:5.2f}[s]\n'.
            format(h_pred, m_pred, s_pred))
        file.write('    T / mod  = {:4.0f}[h] {:2.0f}[m] {:5.2f}[s]\n'.
            format(h_mod, m_mod, s_mod))
        file.write('    T_tot    = {:4.0f}[h] {:2.0f}[m] {:5.2f}[s]\n'.
            format(h_est, m_est, s_est))


def smtlib_eq(left, right):
    """Bit-wise equality"""
    assert left.compatible(right)
    return left.isNaN() and right.isNaN() or left.bv == right.bv


def get_root_date_offset(tree):
    """
    years from most recent tip of the root
    """
    greatest_dist2root = 0
    for leaf in tree.get_terminals():
        if leaf.dist2root > greatest_dist2root:
            greatest_dist2root = leaf.dist2root
    return greatest_dist2root


def _has_context(value):
    """A *value* is a *(data, context)* pair, if it is a tuple of length 2,
    where the second element is derived from a *dictionary*.
    """
    if isinstance(value, tuple):
        if len(value) == 2:
            if isinstance(value[1], dict):
                return True
    return False


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Technology` from a :code:`technology` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Technology`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def quoted_identifier(identifier):
    """One-liner to add double-quote marks around an SQL identifier
    (table name, view name, etc), and to escape double-quote marks.

    Args:
        identifier(str): the unquoted identifier
    """
    return '"{}"'.format(identifier.replace('"', '""'))


@staticmethod
def _specify_input(recs, idx, ivar, emulate_taxsim_2441_logic):
    """
        Specifies recs values for index idx using ivar input variables.

        Parameters
        ----------
        recs: Records
            Records object containing a row for each tax filing unit.

        idx: integer
            recs index of the tax filing unit whose input is in ivar.

        ivar: dictionary
            input variables for a single tax filing unit.

        emulate_taxsim_2441_logic: boolean

        Returns
        -------
        nothing: void
        """
    recs.RECID[idx] = ivar[1]
    recs.FLPDYR[idx] = ivar[2]
    if ivar[4] == 3:
        mars_value = 4
        num_taxpayers = 1
    else:
        mars_value = ivar[4]
        num_taxpayers = ivar[4]
    recs.MARS[idx] = mars_value
    num_dependents = ivar[5]
    num_eitc_qualified_kids = num_dependents
    recs.EIC[idx] = min(num_eitc_qualified_kids, 3)
    total_num_exemptions = num_taxpayers + num_dependents
    recs.XTOT[idx] = total_num_exemptions
    if ivar[6] < 3:
        recs.age_head[idx] = 50
        recs.age_spouse[idx] = 50
        if ivar[6] >= 1:
            recs.age_head[idx] = 70
            if ivar[6] >= 2:
                recs.age_spouse[idx] = 70
    else:
        recs.age_head[idx] = ivar[6] // 100
        recs.age_spouse[idx] = ivar[6] % 100
    recs.e00200p[idx] = ivar[7]
    recs.e00200s[idx] = ivar[8]
    recs.e00200[idx] = ivar[7] + ivar[8]
    recs.e00650[idx] = ivar[9]
    recs.e00600[idx] = ivar[9]
    recs.e00300[idx] = ivar[10]
    recs.e01700[idx] = ivar[11]
    recs.e02400[idx] = ivar[12]
    recs.e00400[idx] = ivar[13]
    recs.e18500[idx] = ivar[15]
    recs.e18400[idx] = ivar[16]
    recs.e32800[idx] = ivar[17]
    if emulate_taxsim_2441_logic:
        recs.f2441[idx] = num_dependents
    else:
        recs.f2441[idx] = ivar[19]
    recs.e02300[idx] = ivar[18]
    recs.n24[idx] = ivar[19]
    recs.e19200[idx] = ivar[20]
    recs.p22250[idx] = ivar[21]
    recs.p23250[idx] = ivar[22]


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

        :param DomainInvitesSetInviteNewUserPrefToNoDetails val:
        :rtype: EventDetails
        """
    return cls('domain_invites_set_invite_new_user_pref_to_no_details', val)


def psi_Na_HCO3_SO4_HMW84(T, P):
    """c-a-a': sodium bicarbonate sulfate [HMW84]."""
    psi = -0.005
    valid = T == 298.15
    return psi, valid


def enum(nstr, schema, *symbols):
    """
    !~~enum(symb1[,symb2[,...]])
        corresponding strings in documents must be in the set of
        given symbols.
    """
    return nstr in symbols


@classmethod
def _default(cls, cfg):
    """
    Initializes the given config (dict-like) with the default configuration.
    """
    raise NotImplementedError()


def bisect(plane_co: float=(0.0, 0.0, 0.0), plane_no: float=(0.0, 0.0, 0.0),
    use_fill: bool=False, clear_inner: bool=False, clear_outer: bool=False,
    threshold: float=0.0001, xstart: int=0, xend: int=0, ystart: int=0,
    yend: int=0, cursor: int=1002):
    """Cut geometry along a plane (click-drag to define plane)

    :param plane_co: Plane Point, A point on the plane
    :type plane_co: float
    :param plane_no: Plane Normal, The direction the plane points
    :type plane_no: float
    :param use_fill: Fill, Fill in the cut
    :type use_fill: bool
    :param clear_inner: Clear Inner, Remove geometry behind the plane
    :type clear_inner: bool
    :param clear_outer: Clear Outer, Remove geometry in front of the plane
    :type clear_outer: bool
    :param threshold: Axis Threshold
    :type threshold: float
    :param xstart: X Start
    :type xstart: int
    :param xend: X End
    :type xend: int
    :param ystart: Y Start
    :type ystart: int
    :param yend: Y End
    :type yend: int
    :param cursor: Cursor, Mouse cursor style to use during the modal operator
    :type cursor: int
    """
    pass


def format_string(string, *args, **kwargs):
    """
    Format text inserting parameters in the wildcard positions.

    There are two different syntax for string formatting. The first is based
    on C and uses symbols such as %s, %f, %d to delimit insertion points.

    >>> format_string('%i != %.2f', 42, 43)
    '42 != 43.00'

    The second uses curly braces.

    >>> format_string('{0} != {1}', 42, 43)
    '42 != 43'
    """
    try:
        return string % args
    except TypeError:
        return string.format(*args, **kwargs)


@staticmethod
def get_connection():
    """Get the SQLA database connection

        :return: the SQLA database connection
        """
    from aiida.backends import sqlalchemy as sa
    return sa.ENGINE.raw_connection()


def human_readable_time(delta, terms=1):
    """Convert hours to human readable string

    Arguments:
        delta: time in hours
        terms: how many word terms to use, to describe the timestep
    Returns
        str: Human readable string
    """
    from dateutil.relativedelta import relativedelta
    intervals = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
    if delta > 31:
        pass
    rd = relativedelta(hours=delta)
    out = ''
    for k in intervals[:terms]:
        if getattr(rd, k):
            out += '{} {} '.format(getattr(rd, k), k)
    return out.strip()


def _hascode(object):
    """True if object has an attribute that stores it's __code__"""
    return getattr(object, '__code__', None) or getattr(object, 'func_code',
        None)


def data_extend(data, key, values):
    """Appends all values in a list under ``key`` in the dictionary ``data``."""
    assert isinstance(data, dict)
    assert isinstance(key, str)
    assert isinstance(values, (list, tuple))
    lst = data.get(key, [])
    lst.extend(values)
    if lst:
        data[key] = lst


def get_content_disposition(mimeobj):
    """Return the message's content-disposition if it exists, or None.

    Backport of py3.5 :func:`~email.message.Message.get_content_disposition`
    """
    value = mimeobj.get('content-disposition')
    if value is None:
        return None
    return str(value).partition(';')[0].strip().lower()


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

    The ".dev0" means dirty.

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


def adapt_diff(diff):
    """
    Formats diff to human-readable format
    :param diff: dictionary
    :type diff: dict
    :return: result of the formatted text
    :rtype: str
    """
    a = ''
    for key, value in diff.items():
        a += '[{}] nou:{} antic:{} '.format(key, *value)
    return a


def nguass(calc, val):
    """https://www.quantum-espresso.org/Doc/INPUT_PROJWFC.html#ngauss
    """
    assert isinstance(val, int)


def addEvent(event, fd, action):
    """
        Add a new win32 event to the event loop.

        @param event: a Win32 event object created using win32event.CreateEvent()

        @param fd: an instance of L{twisted.internet.abstract.FileDescriptor}

        @param action: a string that is a method name of the fd instance.
                       This method is called in response to the event.

        @return: None
        """


def get_positionangle(source_id1, source_id2):
    """Use Gaia DR2 source ids to return the position angle between two sources in degrees"""
    import warnings
    warnings.filterwarnings('ignore')
    import numpy as np
    from astroquery.gaia import Gaia
    from myastrotools.gaia_tools import to_polar
    deg_to_mas = 3600000.0
    mas_to_deg = 1.0 / 3600000.0
    job = Gaia.launch_job(
        'SELECT * FROM gaiadr2.gaia_source WHERE source_id = ' + str(
        source_id1))
    j = job.get_results()
    job = Gaia.launch_job(
        'SELECT * FROM gaiadr2.gaia_source WHERE source_id = ' + str(
        source_id2))
    k = job.get_results()
    RAa, RAaerr = j[0]['ra'], j[0]['ra_error'] * mas_to_deg
    RAb, RAberr = k[0]['ra'], k[0]['ra_error'] * mas_to_deg
    Deca, Decaerr = j[0]['dec'], j[0]['dec_error'] * mas_to_deg
    Decb, Decberr = k[0]['dec'], k[0]['dec_error'] * mas_to_deg
    raa_array = np.random.normal(RAa, RAaerr, 10000)
    rab_array = np.random.normal(RAb, RAberr, 10000)
    deca_array = np.random.normal(Deca, Decaerr, 10000)
    decb_array = np.random.normal(Decb, Decberr, 10000)
    rho_array, pa_array = to_polar(raa_array, rab_array, deca_array, decb_array
        )
    pa, paerr = np.mean(pa_array).value, np.std(pa_array).value
    return pa, paerr


def fig(fig):
    """
    Check if fig is an instance of *Figure*.

    :raises TypeError: fig must be an instance of *Figure*.
    """
    if not fig.__class__.__name__ == 'Figure':
        raise TypeError('\n\nfig must be an instance of *Figure*.\n')


def vpack(boxes, padding=0, strength='strong'):
    """
    Stack LayoutBox instances from top to bottom
    """
    for i in range(1, len(boxes)):
        c = boxes[i - 1].bottom - padding >= boxes[i].top
        boxes[i].solver.addConstraint(c | strength)


def print_info(message):
    """ Prints an informative message. """
    print('INFO: {}'.format(message))


def setNoneAttributes(obj, name, value, listNone):
    """
    Set attribute contained in dictionary dictList into the attr-list.
    A list is a native list or a numpy.ndarray. It also checks the type.
    if values is a singular item of the proper type it will be inserted as [value].

    Parameters
    ----------
    obj : object
        to place the attribute in
    name : str
        of the attribute
    value : any
        of the attribute
    listNone : list of names
        that could have a None value

    Returns
    -------
        True on succesful insertion. False otherwise.

    Raises
    ------
        TypeError   if the type is not as in the dictionary
     """
    if name in listNone and value is None:
        object.__setattr__(obj, name, value)
        return True
    return False


def _paginate(seq, page_size):
    """Consume an iterable and return it in chunks.

    Every chunk is at most `page_size`. Never return an empty chunk.
    """
    page = []
    it = iter(seq)
    while True:
        try:
            for i in range(page_size):
                page.append(next(it))
            yield page
            page = []
        except StopIteration:
            if page:
                yield page
            return


def _synchronous_switch_listener(dbapi_conn, connection_rec):
    """Switch sqlite connections to non-synchronous mode."""
    dbapi_conn.execute('PRAGMA synchronous = OFF')


@classmethod
def map(cls, *args, **kwargs):
    """
        Map using the `.map()` implementation in the multiprocessing engine
        """
    if not cls.is_initialized:
        raise RuntimeError('Connect before calling map()')
    return cls.client.map(*args, **kwargs)


def to_bio2(tags):
    """
    Convert the original tag sequence to BIO2 format. If the input is already in BIO2 format,
    the original input is returned.

    Args:
        tags: a list of tags in either BIO or BIO2 format

    Returns:
        new_tags: a list of tags in BIO2 format
    """
    new_tags = []
    for i, tag in enumerate(tags):
        if tag == 'O':
            new_tags.append(tag)
        elif tag[0] == 'I':
            if i == 0 or tags[i - 1] == 'O' or tags[i - 1][1:] != tag[1:]:
                new_tags.append('B' + tag[1:])
            else:
                new_tags.append(tag)
        else:
            new_tags.append(tag)
    return new_tags


def clipboard_copy():
    """Copies selected nodes to the clipboard

    """
    pass


def join_infile_path(*paths):
    """
    Join path components using '/' as separator.
    This method is defined as an alternative to os.path.join, which uses '\\'
    as separator in Windows environments and is therefore not valid to navigate
    within data files.

    Parameters
    ----------
    *paths: all strings with path components to join

    Returns
    -------
    A string with the complete path using '/' as separator.
    """
    path = '/'.join(paths)
    path = path.replace('//', '/')
    return path


@staticmethod
def mandatory_attrs():
    """Retruns a list of mandatory attributes.

        Mandatory attributes can't be removed from the document. This
        method should be overwritten by derived class.

        """
    return []


@classmethod
def on_write_connection(cls):
    """
        Begin querying the model on the write connection.

        :return: A Builder instance
        :rtype: QueryBuilder
        """
    instance = cls()
    return instance.new_query().use_write_connection()


def describe():
    """
    Describe Part-Of-Speech supported.
    """
    print('ADJ - Adjective, kata sifat')
    print('ADP - Adposition')
    print('ADV - Adverb, kata keterangan')
    print('ADX - Auxiliary verb, kata kerja tambahan')
    print('CCONJ - Coordinating conjuction, kata hubung')
    print('DET - Determiner, kata penentu')
    print('NOUN - Noun, kata nama')
    print('NUM - Number, nombor')
    print('PART - Particle')
    print('PRON - Pronoun, kata ganti')
    print('PROPN - Proper noun, kata ganti nama khas')
    print('SCONJ - Subordinating conjunction')
    print('SYM - Symbol')
    print('VERB - Verb, kata kerja')
    print('X - Other')


def delete_receipt_rule(RuleSetName=None, RuleName=None):
    """
    Deletes the specified receipt rule.
    For information about managing receipt rules, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example deletes a receipt rule:
    Expected Output:

    :example: response = client.delete_receipt_rule(
        RuleSetName='string',
        RuleName='string'
    )

    :type RuleSetName: string
    :param RuleSetName: [REQUIRED]
            The name of the receipt rule set that contains the receipt rule to delete.

    :type RuleName: string
    :param RuleName: [REQUIRED]
            The name of the receipt rule to delete.

    :rtype: dict
    :return: {}

    """
    pass


def clear_history(current_scene_db):
    """empties the history table"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    clear_history = 'DELETE FROM "History"'
    cur.execute(clear_history)
    conn.commit()
    conn.close()


@staticmethod
def push_notification(name, updates, original):
    """
        Ignore this request, as we want to handle the notification separately in update
        """
    pass


def make_exact(h):
    """Make sure h is an exact representable number

    This is important when calculating numerical derivatives and is
    accomplished by adding 1.0 and then subtracting 1.0.
    """
    return h + 1.0 - 1.0


def get_installed_distributions():
    """
    Returns a list of all the packages that are installed in this current
    environment.
    """
    from gae.link_libs import pip
    return pip.get_installed_distributions()


def unary_undefined(prev_u, m):
    """given u_{i - 1} and m_{i},
    returns True if u_{i} is undefined,
    False if defined"""
    if m is None:
        return True
    if m == 0 and prev_u is not None and prev_u % 2 == 0:
        return True
    else:
        return False


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

        :returns: this backend does not supports entries resuming
        """
    return False


def __get__(row):
    """
        @param row: an item that has this column.
        @type row: L{axiom.item.Item}

        @return: The value of the column described by this object, for the given
        row.

        @rtype: depends on the underlying type of the column.
        """


@classmethod
def from_dict(cls, source, data):
    """
        Create SourceLine from given OrderSource and dict.

        :type source: OrderSource
        :type data: dict
        :rtype: cls
        """
    return cls(source, **cls._deserialize_data(source, data))


def describe_user_pool_client(UserPoolId=None, ClientId=None):
    """
    Client method for returning the configuration information and metadata of the specified user pool client.
    See also: AWS API Documentation

    :example: response = client.describe_user_pool_client(
        UserPoolId='string',
        ClientId='string'
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool you want to describe.

    :type ClientId: string
    :param ClientId: [REQUIRED]
            The ID of the client associated with the user pool.

    :rtype: dict
    :return: {
        'UserPoolClient': {
            'UserPoolId': 'string',
            'ClientName': 'string',
            'ClientId': 'string',
            'ClientSecret': 'string',
            'LastModifiedDate': datetime(2015, 1, 1),
            'CreationDate': datetime(2015, 1, 1),
            'RefreshTokenValidity': 123,
            'ReadAttributes': [
                'string',
            ],
            'WriteAttributes': [
                'string',
            ],
            'ExplicitAuthFlows': [
                'ADMIN_NO_SRP_AUTH'|'CUSTOM_AUTH_FLOW_ONLY',
            ],
            'SupportedIdentityProviders': [
                'string',
            ],
            'CallbackURLs': [
                'string',
            ],
            'LogoutURLs': [
                'string',
            ],
            'DefaultRedirectURI': 'string',
            'AllowedOAuthFlows': [
                'code'|'implicit'|'client_credentials',
            ],
            'AllowedOAuthScopes': [
                'string',
            ],
            'AllowedOAuthFlowsUserPoolClient': True|False
        }
    }

    :returns:
    (string) --

    """
    pass


def __version__():
    """This will print the number of the pylj version currently in use."""
    major = 1
    minor = 3
    micro = 4
    print('pylj-{:d}.{:d}.{:d}'.format(major, minor, micro))


def create_qualification_type(Name=None, Keywords=None, Description=None,
    QualificationTypeStatus=None, RetryDelayInSeconds=None, Test=None,
    AnswerKey=None, TestDurationInSeconds=None, AutoGranted=None,
    AutoGrantedValue=None):
    """
    The CreateQualificationType operation creates a new Qualification type, which is represented by a QualificationType data structure.
    See also: AWS API Documentation

    :example: response = client.create_qualification_type(
        Name='string',
        Keywords='string',
        Description='string',
        QualificationTypeStatus='Active'|'Inactive',
        RetryDelayInSeconds=123,
        Test='string',
        AnswerKey='string',
        TestDurationInSeconds=123,
        AutoGranted=True|False,
        AutoGrantedValue=123
    )

    :type Name: string
    :param Name: [REQUIRED]
            The name you give to the Qualification type. The type name is used to represent the Qualification to Workers, and to find the type using a Qualification type search. It must be unique across all of your Qualification types.

    :type Keywords: string
    :param Keywords: One or more words or phrases that describe the Qualification type, separated by commas. The keywords of a type make the type easier to find during a search.

    :type Description: string
    :param Description: [REQUIRED]
            A long description for the Qualification type. On the Amazon Mechanical Turk website, the long description is displayed when a Worker examines a Qualification type.

    :type QualificationTypeStatus: string
    :param QualificationTypeStatus: [REQUIRED]
            The initial status of the Qualification type.
            Constraints: Valid values are: Active | Inactive

    :type RetryDelayInSeconds: integer
    :param RetryDelayInSeconds: The number of seconds that a Worker must wait after requesting a Qualification of the Qualification type before the worker can retry the Qualification request.
            Constraints: None. If not specified, retries are disabled and Workers can request a Qualification of this type only once, even if the Worker has not been granted the Qualification. It is not possible to disable retries for a Qualification type after it has been created with retries enabled. If you want to disable retries, you must delete existing retry-enabled Qualification type and then create a new Qualification type with retries disabled.

    :type Test: string
    :param Test: The questions for the Qualification test a Worker must answer correctly to obtain a Qualification of this type. If this parameter is specified, TestDurationInSeconds must also be specified.
            Constraints: Must not be longer than 65535 bytes. Must be a QuestionForm data structure. This parameter cannot be specified if AutoGranted is true.
            Constraints: None. If not specified, the Worker may request the Qualification without answering any questions.

    :type AnswerKey: string
    :param AnswerKey: The answers to the Qualification test specified in the Test parameter, in the form of an AnswerKey data structure.
            Constraints: Must not be longer than 65535 bytes.
            Constraints: None. If not specified, you must process Qualification requests manually.

    :type TestDurationInSeconds: integer
    :param TestDurationInSeconds: The number of seconds the Worker has to complete the Qualification test, starting from the time the Worker requests the Qualification.

    :type AutoGranted: boolean
    :param AutoGranted: Specifies whether requests for the Qualification type are granted immediately, without prompting the Worker with a Qualification test.
            Constraints: If the Test parameter is specified, this parameter cannot be true.

    :type AutoGrantedValue: integer
    :param AutoGrantedValue: The Qualification value to use for automatically granted Qualifications. This parameter is used only if the AutoGranted parameter is true.

    :rtype: dict
    :return: {
        'QualificationType': {
            'QualificationTypeId': 'string',
            'CreationTime': datetime(2015, 1, 1),
            'Name': 'string',
            'Description': 'string',
            'Keywords': 'string',
            'QualificationTypeStatus': 'Active'|'Inactive',
            'Test': 'string',
            'TestDurationInSeconds': 123,
            'AnswerKey': 'string',
            'RetryDelayInSeconds': 123,
            'IsRequestable': True|False,
            'AutoGranted': True|False,
            'AutoGrantedValue': 123
        }
    }

    """
    pass


@classmethod
def gcd(cls, a, b):
    """Greatest common divisor of polynomials a and b."""
    a = cls._intern(a)
    b = cls._intern(b)
    return cls(cls._gcd(a, b))


@staticmethod
def dump_key(key):
    """The result of the export is a JSON string
        """
    return key.export()


def block_num_from_hash(block_hash: str) ->int:
    """
    return the first 4 bytes (8 hex digits) of the block ID (the block_num)
    Args:
        block_hash (str):

    Returns:
        int:
    """
    return int(str(block_hash)[:8], base=16)


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

        :param str val:
        :rtype: MemberAddResult
        """
    return cls('persistent_id_disabled', val)


@classmethod
def deserialize(cls, dict_model):
    """Returns an unsaved class object based on the valid properties passed in."""
    kwargs = {}
    for f in cls._meta.concrete_fields:
        if f.attname in dict_model:
            kwargs[f.attname] = dict_model[f.attname]
    return cls(**kwargs)


def compare_eval(a, b):
    """
    >>> compare_eval(1, "x%2==1")
    True
    >>> compare_eval(1, "0<x/3 and x/3 <=1.0")
    True
    >>> compare_eval("xyz", "len(x)==3")
    True
    >>> compare_eval("xyz", 'hash(x)!=hash("xyz")')
    False
    >>> compare_eval("xyz", 'x[2]=="z"')
    True
    >>> compare_eval("xyzxyz", 'x[:int(len(x)/2)]==x[int(len(x)/2):]')
    True
    >>> compare_eval("xyzxyz123123", 'x[:int(len(x)/2)]==x[int(len(x)/2):]')
    False
    """
    return eval(b, {}, {'x': a})


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

    The ".dev0" means dirty.

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


def unindexObject():
    """ Unindex the object from the portal catalog.
        """


@classmethod
def subscription_remove(cls, options=None):
    """Remove a subscription from host

        Usage::

            hammer host subscription remove [OPTIONS]

        Options::

            --host HOST_NAME                    Name to search by
            --host-id HOST_ID
            --quantity Quantity                 Remove the first instance of a
                                                subscription with matching id
                                                and quantity
            --subscription-id SUBSCRIPTION_ID   ID of subscription
        """
    cls.command_sub = 'subscription remove'
    return cls.execute(cls._construct_command(options))


def MP98_eqTableA3(T, abc):
    """MP98 equation for Table A3."""
    Tr = 298.15
    return abc[0] + abc[1] * (T - Tr) + abc[2] * (T - Tr) ** 2


def toggle_actions(actions, enable):
    """Enable/disable actions"""
    if actions is not None:
        for action in actions:
            if action is not None:
                action.setEnabled(enable)


@classmethod
def templates_changed(cls, action, instance, **kwargs):
    """
        this method is called from a django signal (m2m_changed)
        see django_netjsonconfig.apps.DjangoNetjsonconfigApp.connect_signals
        """
    if action not in ['post_add', 'post_remove', 'post_clear']:
        return
    if instance.status != 'modified':
        instance.set_status_modified()
    else:
        instance._send_config_modified_signal()


def apply_ants_transform(transform, data, data_type='point', reference=None,
    **kwargs):
    """
    Apply ANTsTransform to data

    ANTsR function: `applyAntsrTransform`

    Arguments
    ---------
    transform : ANTsTransform
        transform to apply to image

    data : ndarray/list/tuple
        data to which transform will be applied

    data_type : string
        type of data
        Options :
            'point'
            'vector'
            'image'

    reference : ANTsImage
        target space for transforming image

    kwargs : kwargs
        additional options passed to `apply_ants_transform_to_image`

    Returns
    -------
    ANTsImage if data_type == 'point'
    OR
    tuple if data_type == 'point' or data_type == 'vector'
    """
    return transform.apply(data, data_type, reference, **kwargs)


def getMegamanicEditableFields():
    """Returns an ordered list of editable fields (as strings)."""


def event(ev):
    """ Widget that immediately returns `ev`. """
    return ev
    yield


def getCookie(key):
    """
        Get a cookie that was sent from the network.
        """


def _new_object(cls):
    """Helper function for pickle"""
    return cls.__new__(cls)


def shared_directory(files, verbose=False):
    """
    Find the shared base directory amongst a list of files.

    Parameters
    ----------

    files : list
            A list of filenames.

    Returns
    -------

    shared : str
            A filepath that is the shared across all the files.
    """
    for i in range(len(files[0])):
        shared = files[0][:i + 1]
        if verbose:
            print('"{}"'.format(shared))
        for f in files:
            if f[:i + 1] != shared:
                if verbose:
                    print('Huzzah! "{}" is shared across {} files.'.format(
                        shared[:-1], len(files)))
                return shared[:-1]


def _convert_type(data_type):
    """
        Converts CDF data types into python types
        """
    if data_type in (1, 41):
        dt_string = 'b'
    elif data_type == 2:
        dt_string = 'h'
    elif data_type == 4:
        dt_string = 'i'
    elif data_type in (8, 33):
        dt_string = 'q'
    elif data_type == 11:
        dt_string = 'B'
    elif data_type == 12:
        dt_string = 'H'
    elif data_type == 14:
        dt_string = 'I'
    elif data_type in (21, 44):
        dt_string = 'f'
    elif data_type in (22, 45, 31):
        dt_string = 'd'
    elif data_type == 32:
        dt_string = 'd'
    elif data_type in (51, 52):
        dt_string = 's'
    else:
        dt_string = ''
    return dt_string


def import_backend(path):
    """Import a backend class by dotted path."""
    module_name, class_name = path.rsplit('.', 1)
    module = __import__(module_name, fromlist=[class_name])
    return getattr(module, class_name)


def fill_region(regions, note, rect, cutoff):
    """Fill the region defined by rect with a (note, velocity, 0) color

    The velocity varies from a small value at the top of the region to
    127 at the bottom. The vertical region 0 to cutoff is split into
    three parts, with velocities 42, 84 and 127. Everything below cutoff
    has velocity 127.

    """
    x, y, width, height = rect
    if cutoff is None:
        cutoff = height
    delta_height = cutoff // 3
    regions.fill((note, 42, 0), (x, y, width, delta_height))
    regions.fill((note, 84, 0), (x, y + delta_height, width, delta_height))
    regions.fill((note, 127, 0), (x, y + 2 * delta_height, width, height -
        2 * delta_height))


def restore_base(model, first_solution, copy_of_dmu_codes, max_slack_solution):
    """ Helper function used for restoring DMU codes and first solution.

        Args:
            model (ModelBase): model used in the peel the onion.
            first_solution (Solution): first solution of the peel the
                onion.
            copy_of_dmu_codes (list of str): list of original DMU codes.
            max_slack_solution (Solution): solution obtained by two phase
                model if any.
    """
    model.input_data.DMU_codes = copy_of_dmu_codes
    if max_slack_solution:
        model.second_solution = max_slack_solution
    assert first_solution


def write_output_to_file(pathway_table, currenttarmet, cutoff,
    cyclic_pathways, folder_to_create, namemap, source_metabolites, G):
    """
    This function writes the pathways of sizes less than or equal to the
    cutoff from source to the target and seed metabolites to target.
    This function also writes cyclic pathways of sizes less than or equal to
    cutoff from the source to target.

    Parameters
    ----------
    pathway_table : dict
        Dictionary of dictionary containing the pathways of different sizes
        identified for every metabolite. This will have only the acyclic/
        branched pathways.
    currenttarmet : str
        Current target metabolite
    cutoff : int
        Maximum pathway length cutoff
    cyclic_pathways : dict
        Dictionary of dictionary containing cyclic pathways of different sizes
        identified for every metabolite.
    folder_to_create : str
        Name of the folder where results have to be written
    namemap : dict
        Dictionary mapping the adhoc reaction names to reaction names in
        the model
    source_metabolites : list
        List of source metabolites
    G : NetworkX DiGraph Object
        Bipartite graph of the metabolic network

    Returns
    -------
    None
    """
    pred = G.predecessors
    succ = G.successors
    all_pathways_count = []
    path_count = []
    cyclic_pathway_count = []
    if currenttarmet in pathway_table:
        for plen in pathway_table[currenttarmet]:
            all_pathways_count.append(len(pathway_table[currenttarmet][plen]))
            if plen <= int(cutoff):
                path_count.append(len(pathway_table[currenttarmet][plen]))
        if currenttarmet in cyclic_pathways:
            for plen in cyclic_pathways[currenttarmet]:
                if plen <= int(cutoff):
                    cyclic_pathway_count.append(len(cyclic_pathways[
                        currenttarmet][plen]))
            cycfname = (folder_to_create + 'cyclic_pathways_' +
                currenttarmet.replace(' ', '') + '_' + 'leq_plen_' + str(
                cutoff) + '.txt')
            pathnumcount = 0
            with open(cycfname, 'w') as filetowrite:
                print('\nWriting cyclic pathways to a file')
                for idx in cyclic_pathways[currenttarmet]:
                    if idx <= int(cutoff):
                        filetowrite.write('Path length ' + str(idx) + '\n')
                    for items in cyclic_pathways[currenttarmet][idx]:
                        pathnumcount += 1
                        filetowrite.write(str(pathnumcount) + '\n')
                        for entities in list(items):
                            filetowrite.write(namemap[entities] + '\t' +
                                ' + '.join(pred(entities)) + '->' + ' + '.
                                join(succ(entities)))
                            filetowrite.write('\n')
                        filetowrite.write('--------------------\n')
        if int(cutoff) in pathway_table[currenttarmet]:
            for sourcemets in source_metabolites:
                seedfname = (folder_to_create +
                    'branched_pathways_from_seed_' + currenttarmet.replace(
                    ' ', '') + '_' + 'leq_plen_' + str(cutoff) + '.txt')
                pathnumcount = 0
                with open(seedfname, 'w') as filetowrite:
                    print('Writing branched pathways (from seed) to a file')
                    for idx in pathway_table[currenttarmet]:
                        if idx <= int(cutoff):
                            filetowrite.write('Path length ' + str(idx) + '\n')
                            for items in pathway_table[currenttarmet][idx]:
                                pathnumcount += 1
                                filetowrite.write(str(pathnumcount) + '\n')
                                for entities in list(items):
                                    filetowrite.write(namemap[entities] +
                                        '\t' + ' + '.join(pred(entities)) +
                                        '->' + ' + '.join(succ(entities)))
                                    filetowrite.write('\n')
                                filetowrite.write('--------------------\n')
                            filetowrite.write('--------------------\n')
                only_source_to_target = []
                for sourcemets in source_metabolites:
                    for idx in pathway_table[currenttarmet]:
                        if idx <= int(cutoff):
                            for items in pathway_table[currenttarmet][idx]:
                                if set(succ(sourcemets)).intersection(items):
                                    only_source_to_target.append(list(items))
                    if only_source_to_target:
                        sourcefname = (folder_to_create +
                            'branched_pathways_from_source_' +
                            currenttarmet.replace(' ', '') + '_' +
                            'leq_plen_' + str(cutoff) + '.txt')
                        with open(sourcefname, 'w') as filetowrite:
                            print(
                                'Writing branched pathways (from source) to a file \n'
                                )
                            for currentidx, listentries in enumerate(
                                only_source_to_target):
                                filetowrite.write(str(currentidx + 1) + '\n')
                                filetowrite.write('Path length ' + str(len(
                                    listentries)) + '\n')
                                for entities in listentries:
                                    filetowrite.write(namemap[entities] +
                                        '\t' + ' + '.join(pred(entities)) +
                                        '->' + ' + '.join(succ(entities)))
                                    filetowrite.write('\n')
                                filetowrite.write('--------------------\n')
    else:
        print(currenttarmet, ': Target could not be found.')
        print('Consider changing the cut-off or the seed metabolite set')


def filter_dataframe(data, frm, to):
    """
    A function to filter the dataset, which is the first
    argument to the function using 'frm' and 'to' as the
    second and third arguments.
    Please note that both 'frm' and 'to' are included in
    the returned filtered Pandas Data frame.

    Returns a filtered Pandas Data frame according to 'frm'
    and 'to' arguments
    """
    return data.loc[((data['time'] >= frm) & (data['time'] < to)), :]


def _get_namespace(obj, globalns, localns):
    """Retrieve the global and local namespaces for an object.

    Args:
        obj: An object.
        globalns: The currently known global namespace.
        localns: The currently known local namespace.

    Returns:
        A tuple containing two dictionaries for the global and local namespaces
        to be used by eval.
    """
    if globalns is None:
        globalns = getattr(obj, '__globals__', {})
        if localns is None:
            localns = globalns
    elif localns is None:
        localns = globalns
    return globalns, localns


def disable_color():
    """Disable colours by setting colour code constants to empty strings."""
    global LIGHT_GREEN
    LIGHT_GREEN = ''
    global LIGHT_RED
    LIGHT_RED = ''
    global LIGHT_BLUE
    LIGHT_BLUE = ''
    global DARK_RED
    DARK_RED = ''
    global END_COLOR
    END_COLOR = ''


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 numeric_logg_to_string(logg):
    """
    Convert numeric form of cgs logg to string used in castelli-kurucz 04,
    kurucz 93 and van-hamme limb darkening table names.

    :param logg: float;
    :return: str;
    """
    return 'g%02d' % (logg * 10)


@classmethod
def compose(cls, *args):
    """Return the product of a collection of matrices."""
    return cls.mul(*args)


def textbox_remove(index: int=0):
    """Remove the textbox

    :param index: Index, The current text box
    :type index: int
    """
    pass


def undo_push(message: str='Addanundostep*functionmaybemoved*'):
    """Add an undo state (internal use only)

    :param message: Undo Message
    :type message: str
    """
    pass


def generate_date(field, factory):
    """Generate a date.

    :returns: a unique datetime.date.
    :return_type: datetime.date
    """
    return factory.getUniqueDate()


@staticmethod
def load(filename: str):
    """Load and return an instance from the file `filename`

Parameters
----------
filename : str
    a path for the file to be loaded
        """
    import pickle
    with open(filename, 'rb') as f:
        obj = pickle.load(f)
    obj._stopwords = lambda x: False
    return obj


def _entity_isa(given, mapper):
    """determine if 'given' "is a" mapper, in terms of the given
    would load rows of type 'mapper'.

    """
    if given.is_aliased_class:
        return mapper in given.with_polymorphic_mappers or given.mapper.isa(
            mapper)
    elif given.with_polymorphic_mappers:
        return mapper in given.with_polymorphic_mappers
    else:
        return given.isa(mapper)


@staticmethod
def p_bridge(symbols):
    """bridge : SOB maybespace ENDOFLINE bridge_content EOB maybespace
        """
    symbols[0] = symbols[4]


def set_constant(name, value, export=vars()):
    """ sets constants and returns resolved options dict """
    export[name] = value


def save():
    """Save active text data block

    """
    pass


def boss_distance(histo1, histo2):
    """
    BOSS distance between two histograms

    Not really a distance because it is not symmetric

    :param histo1:
    :param histo2:
    :return:
    """
    val = 0
    for w in histo1:
        if w in histo2:
            val += (histo1[w] - histo2[w]) ** 2
        else:
            val += histo1[w] * histo1[w]
    return val


def normalize_sizes(sizes, dx, dy):
    """Normalize list of values.

    Normalizes a list of numeric values so that `sum(sizes) == dx * dy`.

    Parameters
    ----------
    sizes : list-like of numeric values
        Input list of numeric values to normalize.
    dx, dy : numeric
        The dimensions of the full rectangle to normalize total values to.

    Returns
    -------
    list[numeric]
        The normalized values.
    """
    total_size = sum(sizes)
    total_area = dx * dy
    sizes = map(float, sizes)
    sizes = map(lambda size: size * total_area / total_size, sizes)
    return list(sizes)


@classmethod
def format_z(cls, offset):
    """ Format `timedelta` into %z """
    sec = offset.total_seconds()
    return '{s}{h:02d}{m:02d}'.format(s='-' if sec < 0 else '+', h=abs(int(
        sec / 3600)), m=int(sec % 3600 / 60))


def xml_to_standard_dict(ordered_data, reduce_orderedDicts=False,
    reduce_lists=False, manual_selection_for_list_reduction=False):
    """
    Convert a xml/orderedDict to normal dictionary

    Parameters
    ----------
    ordered_data : orderedDict
        input xml data to convert to standard dict
    reduce_orderedDicts : bool, optional
        if collections.orderedDicts shall be converted to normal dicts
    reduce_lists : bool, list, set, optional
        if lists in the dictionary shall be converted to dictionaries with transformed keys
        (list_key + unique key from dictionary from list_element)
        if list or set is provided, only these values will be reduced
    manual_selection_for_list_reduction : bool, optional
        if manually decision on list reduction shall be used
        all keys in ``reduce_lists`` will be automatically reduced

    Returns
    -------
    dict
        the normalized dictionary

    """
    from collections import OrderedDict
    from ._helper import _reduce_lists, _dictionize
    data = dict()
    if reduce_orderedDicts:
        for key in ordered_data:
            if isinstance(ordered_data[key], OrderedDict):
                data[key] = _dictionize(ordered_data[key])
            else:
                data[key] = ordered_data[key]
    if manual_selection_for_list_reduction:
        raise NotImplemented
    elif reduce_lists:
        data = _reduce_lists(data, reduce_lists,
            manual_selection_for_list_reduction)
    return data


def listify(maybe_list):
    """Return list version of whatever value is passed in.

    This is used to provide a consistent way of interacting with the JSON
    results from the API. There are several attributes that will either missing
    if there are no values, a single dictionary if there is only one value, and
    a list if there are multiple.
    """
    if maybe_list is None:
        return []
    if isinstance(maybe_list, list):
        return maybe_list
    return [maybe_list]


@classmethod
def create_event(cls, form, creator):
    """Creates a Mongoengine and Google Calendar event from form data.

        Calls either :func:`create_series` or :func:`create_single_event`
        depending on whether or not the event should be recurring.

        :param form: The WTForms form.
        :type form: :class:`CreateEventForm` or a subclass.
        :param creator: The user that is currently logged in.
        :type creator: :class:`~app.models.User`

        :raises: :class:`GoogleCalendarAPIError` and it's subclasses

        :returns: Response from the Google Calendar API.
        :rtype: dict
        """
    if form.is_recurring.data:
        return cls.create_series(form, creator)
    return cls.create_single_event(form, creator)


def parseline(line):
    """ Extract the spec and command from a line.  If the line is any kind
    of no-op we return None. """
    if not line:
        return
    if line[0] == '#':
        return
    if line[0] == '@':
        return tuple(line.split(' ', 1))
    else:
        parts = line.split(' ', 5)
        return ' '.join(parts[:5]), parts[-1]


def get_kbd_values_by_def(confdict, searchwith=''):
    """Return a list of values by searching a dynamic kb.

    :param confdict: dictionary with keys "field", "expression"
        and "collection" name
    :param searchwith: a term to search with
    :return: list of values
    """
    from invenio_search.api import Query
    if not confdict:
        return []
    if 'field' not in confdict:
        return []
    field = confdict['field']
    expression = confdict['expression']
    collection = ''
    if 'collection' in confdict:
        collection = confdict['collection']
    if searchwith and expression:
        if expression.count('%') > 0:
            expression = expression.replace('%', searchwith)
            response = Query(expression).search(collection=collection)
        else:
            expression = expression + ' and ' + searchwith
            response = Query(expression).search(collection=collection)
    elif expression:
        response = Query(expression).search(collection=collection)
    else:
        fake_exp = '/.*/'
        if searchwith:
            fake_exp = searchwith
        response = Query('{0}:{1}'.format(field, fake_exp)).search(collection
            =collection)
    response.body['size'] = 9999999
    values = []
    for record in response.records():
        value = record.get(field)
        if value:
            values.append(value)
    return values


def get_file_extension(driver='shapefile'):
    """Return file extension for given driver"""
    drivers = {'shapefile': '.shp', 'geodatabase': '.gdb', 'geojson':
        '.geojson', 'csv': '.csv', 'tsv': '.tsv'}
    return drivers.get(driver)


@classmethod
def from_id(cls, provider, id, default=None):
    """
        Special case of _query that doesn't require an instantiated object
        and to fetch by a specific column name.
        """
    id_field = cls.__field_map__['id']
    result = provider._query(cls, **{id_field: id}).fetchone()
    if result is None:
        return default
    else:
        return cls(provider, **dict(result))


def BlockGrad(data=None, name=None, attr=None, out=None, **kwargs):
    """Stops gradient computation.

    Stops the accumulated gradient of the inputs from flowing through this operator
    in the backward direction. In other words, this operator prevents the contribution
    of its inputs to be taken into account for computing gradients.

    Example::

      v1 = [1, 2]
      v2 = [0, 1]
      a = Variable('a')
      b = Variable('b')
      b_stop_grad = stop_gradient(3 * b)
      loss = MakeLoss(b_stop_grad + a)

      executor = loss.simple_bind(ctx=cpu(), a=(1,2), b=(1,2))
      executor.forward(is_train=True, a=v1, b=v2)
      executor.outputs
      [ 1.  5.]

      executor.backward()
      executor.grad_arrays
      [ 0.  0.]
      [ 1.  1.]

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L327

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

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

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


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

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

       - arctanh(default) = default
       - arctanh(row_sparse) = row_sparse
       - arctanh(csr) = csr

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

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

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

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


def get_key_by_value(dict_, value):
    """Return key by value."""
    for key, val in dict_.items():
        if value == val:
            return key
    return None


@classmethod
def from_commit(cls, commit):
    """Create an instance from a Git commit."""
    return cls(name=commit.author.name, email=commit.author.email)


def setScriptname(name):
    """
    Module function to set the scriptname to be reported back to the IDE.

    @param name absolute pathname of the script (string)
    """
    global __scriptname
    __scriptname = name


def save_dirty():
    """Save all modified textures

    """
    pass


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def insert(text: str=''):
    """Insert text at cursor position

    :param text: Text, Text to insert at the cursor position
    :type text: str
    """
    pass


def mbar2inhg(press_mbar):
    """Convert pressure value from mbar to inHg"""
    return press_mbar / 33.8639


def fix_name(player):
    """
    Get rid of (A) or (C) when a player has it attached to their name

    :param player: list of player info -> [number, position, name]

    :return: fixed list
    """
    if player[2].find('(A)') != -1:
        player[2] = player[2][:player[2].find('(A)')].strip()
    elif player[2].find('(C)') != -1:
        player[2] = player[2][:player[2].find('(C)')].strip()
    return player


def fn_upper_case(context, text):
    """
    http://www.w3.org/TR/xpath-functions/#func-upper-case
    :param context: Parent DOM context
        :type context: EtreeElement
    :param text: matches xpath results
        :type text: str

    :rtype: str
    # TODO add in documentation
    """
    del context
    return text.upper()


def partialSums(labels, data, partials, partial_labels='', datarow_labels=''):
    """Returns a latex table with sums of data.

    Data is though to be unidimensional. Each row
    is transposed to a column to which partial sum
    are added.
    """
    lines = []
    for label in labels:
        lines.append('{} '.format(label))
    for datarow in data:
        for partial in partials:
            for line_num in range(len(datarow)):
                if line_num % partial == 0:
                    lines[line_num
                        ] += '& \\multirow{{{:d}}}{{*}}{{ {:.2f} }}  '.format(
                        partial, sum(datarow[line_num:line_num + partial]))
                else:
                    lines[line_num] += '& '
    for line_num in range(len(lines)):
        cuts = [(0 == (line_num + 1) % partial) for partial in partials]
        i = 0
        suffix = ''
        for cut in cuts:
            if cut:
                for datarownum in range(len(data)):
                    num = i + datarownum * len(partials)
                    suffix += '\\cline{{{}-{}}}'.format(num + 2, num + 2)
            i += 1
        lines[line_num] += '\\\\{}\n'.format(suffix)
    ltable = ''.join(lines)
    if partial_labels:
        header = (' & {}' * len(partial_labels)).format(*partial_labels) * len(
            data) + ' \\\\\\hline\n'
        ltable = header + ltable
    if datarow_labels:
        header = (' & \\multicolumn{{%i}}{{c|}}{{{}}}' % (len(partials),) *
            len(datarow_labels)).format(*datarow_labels) + ' \\\\\\hline\n'
        ltable = header + ltable
    header = '\\begin{center}\n\\begin{tabular}{| l ||' + ' c |' * len(data
        ) * len(partials) + '}\\hline\n'
    footer = '\\hline\\end{tabular}\n\\end{center}'
    ltable = header + ltable + footer
    return ltable


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Pin` from a :code:`pin` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Pin`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def round_channels(channels, divisor=8):
    """
    Round weighted channel number (make divisible operation).

    Parameters:
    ----------
    channels : int or float
        Original number of channels.
    divisor : int, default 8
        Alignment value.

    Returns
    -------
    int
        Weighted number of channels.
    """
    rounded_channels = max(int(channels + divisor / 2.0) // divisor *
        divisor, divisor)
    if float(rounded_channels) < 0.9 * channels:
        rounded_channels += divisor
    return rounded_channels


def split_msg(msgs, max_len):
    """Splits as close to the end as possible."""
    msg = ''
    while len(msg.encode()) < max_len:
        if len(msg.encode()) + len(msgs[0]) > max_len:
            return msg, msgs
        char = msgs.pop(0).decode()
        if char == ' ' and len(msg.encode()) > max_len - 15:
            return msg, msgs
        msg += char
    return msg, msgs


@classmethod
def from_dataframe(cls, df):
    """create metadata from dataframe"""
    d = df.to_dict(orient='index')
    metadata = cls.from_dict(d)
    return metadata


def _sign(num):
    """Return the sign of the number provided.

    Returns:
        1 if number is greater than 0, -1 otherwise

    """
    return -1 if num < 0 else 1


def _configSpecial_OrthoOpts_xcentre(target, parser, shortArg, longArg,
    helpText):
    """Configures the ``xcentre`` option for the ``OrthoOpts`` class. """
    parser.add_argument(shortArg, longArg, metavar=('Y', 'Z'), type=float,
        nargs=2, help=helpText)


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


@classmethod
def roots(cls, degree, domain, kind):
    """Return optimal collocation nodes for some orthogonal polynomial."""
    basis_coefs = cls._basis_monomial_coefs(degree)
    basis_poly = cls.functions_factory(basis_coefs, domain, kind)
    return basis_poly.roots()


def branchmap():
    """Return a mapping of branch to heads in that branch."""


def simple_ccw(a, b, c):
    """Simple Counterclockwise test.

    Return true if the points A, B, C are strictly counterclockwise.  Return
    false if the points are clockwise or collinear (i.e. if they are all
    contained on some great circle).

    Due to numerical errors, situations may arise that are mathematically
    impossible, e.g. ABC may be considered strictly CCW while BCA is not.
    However, the implementation guarantees the following:

      If simple_ccw(a,b,c), then !simple_ccw(c,b,a) for all a,b,c.

    see :cpp:func:`S2::SimpleCCW`
    """
    return c.cross_prod(a).dot_prod(b) > 0


def build_command_list(command, param_list, include_keys=True):
    """
    build_command_list builds a list to be used by subprocess.Popen with the
    ParamList providing key/value pairs for command-line parameters.
    ParamList is a dictionary of key:value pairs to be put into the command
    list as such

    Args:
        command (list): A list containing the base command (e.g. ['ls']) with
            parameters that are always used.

        param_list (dict): An dictionary (usually ordered) of key/value pairs
            representing command-line parameters/switches for the command in
            question. Results in ("-k value" or "--key=value")

        include_keys (bool, optional): A flag to indicate whether or not to
            include the keys in the command list. Defaults to True.

    Returns:
        list: returns the completed command-list expected by subprocess.Popen

    Example:
        .. code-block:: python

            command = ['du']
            params = {'a': '', 'human-readable': True, 'max-depth': 3}
            command = build_command_list(command, params)

        results in

        ``['du', '-a', '--human-readable', '--max-depth=3']``
    """
    for key in param_list.keys():
        if len(key) == 1:
            if isinstance(param_list[key], bool) and param_list[key]:
                command.append('-' + key)
            else:
                if include_keys:
                    command.append('-' + key)
                if str(param_list[key]):
                    command.append(str(param_list[key]))
        elif isinstance(param_list[key], bool):
            if param_list[key] and include_keys:
                command.append('--' + key)
        else:
            item = ''
            if include_keys:
                item = '--' + key
            if str(param_list[key]):
                if include_keys:
                    item = item + '='
                item = item + str(param_list[key])
            command.append(item)
    return command


@classmethod
def from_name(cls, endpoint_name):
    """
        Return an Endpoint subclass instance based on the name of the endpoint.
        """
    return cls._endpoints.get(endpoint_name)


def read_detector_pars(filename):
    """Read detector parameters from ASCII file.

    Table must contain 4 columns without header.
    Comment lines are allowed and will be ignored.
    Columns are automatically named:

    #. ``OBSMODE`` - Observation mode.
    #. ``SCALE`` - Pixel scale in arcseconds.
    #. ``NX`` - X dimension in pixels.
    #. ``NY`` - Y dimension in pixels.

    Example::

        # DETECTORS.DAT -- Comments.
        # More comments.
        acs,hrc     0.027   1024  1024
        acs,sbc     0.032   1024  1024
        stis,g140l  0.0244  1024  1024
        stis,g140m  0.0290  1024  1024

    Parameters
    ----------
    filename : str
        Detector parameters filename. Must be ASCII format.

    Returns
    -------
    data : `~astropy.table.Table`
        Data table.

    """
    return ascii.read(filename, guess=False, format='no_header', delimiter=
        '\\s', names=('OBSMODE', 'SCALE', 'NX', 'NY'), converters={
        'OBSMODE': [ascii.convert_numpy(str)], 'SCALE': [ascii.
        convert_numpy(float)], 'NX': [ascii.convert_numpy(int)], 'NY': [
        ascii.convert_numpy(int)]})


def milliseconds(datetime) ->float:
    """
    Returns the milliseconds component for the given datetime value,
    in local time.
    """
    return datetime.millisecond()


@classmethod
def pa(cls, ab, bb, hbp, sf, sh):
    """
        Plate appearance
        :param ab: at bat
        :param bb: base on ball
        :param hbp: hit by pitch
        :param sf: sacrifice fly
        :param sh: sacrifice hit
        :return: (int)Plate appearance
        """
    return ab + bb + hbp + sf + sh


def precision_system_output(entity, partitioned_entity):
    """ Compute a spanning tree from antecedent information.

    All edges in the spanning tree correspond to anaphor-antecedent pairs. In
    order to access this antecedent information, the attribute "antecedent" of
    the mentions in the entity must be set.

    Args:
        entity (EntityGraph): The EntityGraph for the entity for which the
            spanning tree should be computed.
        partitioned_entity (EntityGraph): A partition of the entity -- not
            used for this algorithm.

    Returns:
        list(Mention, Mention): A list of mention pairs, which constitute the
        edges of the spanning tree. For a pair (m, n), n appears later in
        the text than m.
    """
    edges = []
    for mention in entity.edges:
        if 'antecedent' in mention.attributes and mention.attributes[
            'antecedent'] in entity.edges[mention]:
            edges.append((mention, mention.attributes['antecedent']))
    return sorted(edges)


def bezier_tangent(p0: float, p1: float, p2: float, p3: float, t: float):
    """
    Calculate the tangent of the point with parameter t on the cubic bezier curve.

    Note that the parameter t must >=0 and <=1 .

    :param p0: position of the first control point
    :param p1: position of the second control point
    :param p2: position of the third control point
    :param p3: position of the forth control point
    :param t: the parameter t
    :return: tangent of the point
    """
    if t < 0 or t > 1:
        raise ValueError('t must in [0..1]')
    return 3 * (1 - t) ** 2 * (p1 - p0) + 6 * (1 - t) * t * (p2 - p1
        ) + 3 * t ** 2 * (p3 - p2)


def get_svg_viewbox(dom):
    """Get margin and size from svg node"""
    svg_node = dom.getElementsByTagName('svg')[0]
    view_box = svg_node.getAttribute('viewBox')
    sizes = view_box.split(' ')
    return {'margin_x': float(sizes[0]), 'margin_y': float(sizes[1]),
        'width': float(sizes[2]), 'height': float(sizes[3])}


def _overload_dummy(*args, **kwds):
    """Helper for @overload to raise when called."""
    raise NotImplementedError(
        'You should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed.'
        )


def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub):
    """Helper function used by Constraint and Model"""
    if lb is None and ub is None:
        raise Exception('Free constraint ...')
    elif lb is None:
        sense = '<'
        rhs = float(ub)
        range_value = 0.0
    elif ub is None:
        sense = '>'
        rhs = float(lb)
        range_value = 0.0
    elif lb == ub:
        sense = '='
        rhs = float(lb)
        range_value = 0.0
    elif lb > ub:
        raise ValueError('Lower bound is larger than upper bound.')
    else:
        sense = '='
        rhs = float(lb)
        range_value = float(ub - lb)
    return sense, rhs, range_value


def getSwaggerPaginationDef(resultsPerPage):
    """Build swagger spec section for pagination"""
    return {'name': 'page', 'type': 'int', 'in': 'query', 'description':
        'The page number for this paginated query ({} results per page)'.
        format(resultsPerPage)}


def get_default_shaders():
    """
    Returns a list of default Maya shaders
    :return: list(str)
    """
    return ['particleCloud1', 'shaderGlow1', 'defaultColorMgtGlobals',
        'lambert1']


@classmethod
def create(cls, cli, src_resource_id, dst_resource_id, max_time_out_of_sync,
    name=None, members=None, auto_initiate=None,
    hourly_snap_replication_policy=None, daily_snap_replication_policy=None,
    replicate_existing_snaps=None, remote_system=None, src_spa_interface=
    None, src_spb_interface=None, dst_spa_interface=None, dst_spb_interface
    =None):
    """
        Creates a replication session.

        :param cli: the rest cli.
        :param src_resource_id: id of the replication source, could be
            lun/fs/cg.
        :param dst_resource_id: id of the replication destination.
        :param max_time_out_of_sync: maximum time to wait before syncing the
            source and destination. Value `-1` means the automatic sync is not
            performed. `0` means it is a sync replication.
        :param name: name of the replication.
        :param members: list of `UnityLunMemberReplication` object. If
            `src_resource` is cg, `lunMemberReplication` list need to pass in
            to this parameter as member lun pairing between source and
            destination cg.
        :param auto_initiate: indicates whether to perform the first
            replication sync automatically.
            True - perform the first replication sync automatically.
            False - perform the first replication sync manually.
        :param hourly_snap_replication_policy: `UnitySnapReplicationPolicy`
            object. The policy for replicating hourly scheduled snaps of the
            source resource.
        :param daily_snap_replication_policy: `UnitySnapReplicationPolicy`
            object. The policy for replicating daily scheduled snaps of the
            source resource.
        :param replicate_existing_snaps: indicates whether or not to replicate
            snapshots already existing on the resource.
        :param remote_system: `UnityRemoteSystem` object. The remote system of
            remote replication.
        :param src_spa_interface: `UnityRemoteInterface` object. The
            replication interface for source SPA.
        :param src_spb_interface: `UnityRemoteInterface` object. The
            replication interface for source SPB.
        :param dst_spa_interface: `UnityRemoteInterface` object. The
            replication interface for destination SPA.
        :param dst_spb_interface: `UnityRemoteInterface` object. The
            replication interface for destination SPB.
        :return: the newly created replication session.
        """
    req_body = cli.make_body(srcResourceId=src_resource_id, dstResourceId=
        dst_resource_id, maxTimeOutOfSync=max_time_out_of_sync, members=
        members, autoInitiate=auto_initiate, name=name,
        hourlySnapReplicationPolicy=hourly_snap_replication_policy,
        dailySnapReplicationPolicy=daily_snap_replication_policy,
        replicateExistingSnaps=replicate_existing_snaps, remoteSystem=
        remote_system, srcSPAInterface=src_spa_interface, srcSPBInterface=
        src_spb_interface, dstSPAInterface=dst_spa_interface,
        dstSPBInterface=dst_spb_interface)
    resp = cli.post(cls().resource_class, **req_body)
    resp.raise_if_err()
    return cls.get(cli, resp.resource_id)


def attachment_deleted(attachment):
    """Called when an attachment is deleted."""


def average(array):
    """Returns the average for all the values in the given :attr:`array`.

    Args:
        array (list): List of values.

    Returns:
        int/float: Average of all the values in the given list.

    Example:

        >>> float(average([1, 2, 3]))
        2.0

    .. versionadded:: 0.1.0
    """
    return sum(array) / len(array)


def lookup_portion(twitter, user_ids):
    """Resolve a limited list of user ids to screen names."""
    users = {}
    kwargs = dict(user_id=','.join(map(str, user_ids)), skip_status=1)
    for u in twitter.users.lookup(**kwargs):
        users[int(u['id'])] = u['screen_name']
    return users


def add_tag_filter_names(cls):
    """Add tag filter names to the said class.

    :param cls: The class to add tag filter names to.
    :returns: None.
    """
    cls.add_extra_filter_name('tags')
    cls.add_extra_filter_name('not-tags')
    cls.add_extra_filter_name('tags-any')
    cls.add_extra_filter_name('not-tags-any')


def divide(data, params=None):
    """
    Divide function aggregation.

    Example config:

    .. code-block:: python

        config = {
            ...
            'fields': ['timestamp', 'energy'],
            'aggregations': [
                {
                    'func': 'divide',
                    'field': 'energy',
                    'params': {
                        'by': 10
                    }
                }
            ],
            ...
        }
    """
    kwargs = params or {}
    factor = kwargs.get('by', 1.0)
    return data / factor


def get_resource_stream(manager, resource_name):
    """Return a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``"""


def get_length(crf2subtype2bitmask):
    """
    Calculates the alignment length for the breakpoint bitmask mapping.

    :param crf2subtype2bitmask: mapping between CRF ids and a mapping of subtypes to breakpoint interval list (aligned):
        {id: {subtype: [(start, stop), ...], ...}, ..}
    :type crf2subtype2bitmask: dict
    :return: alignment length
    :rtype: int
    """
    return len(next(iter(next(iter(crf2subtype2bitmask.values())).values())))


def find_allnot(ol, test_func, *args):
    """
        from elist.elist import *
        from elist.jprint import pobj
        def test_func(ele,x):
            cond = (ele > x)
            return(cond)

        ol = [1,2,3,4,5,6,7]
        rslt = find_allnot(ol,test_func,3)
        pobj(rslt)
    """
    rslt = []
    length = ol.__len__()
    for i in range(0, length):
        cond = test_func(ol[i], *args)
        if cond:
            pass
        else:
            rslt.append({'index': i, 'value': ol[i]})
    return rslt


def mandatory(value):
    """
    An external constraint that prohibits a value of C{None}.
    """
    if value is None:
        return u'Value is mandatory'


def types():
    """ Returns a list of available property types
        """


def __flatten_index(pos, shape):
    """
    Takes a three dimensional index (x,y,z) and computes the index required to access the
    same element in the flattened version of the array.
    """
    res = 0
    acc = 1
    for pi, si in zip(reversed(pos), reversed(shape)):
        res += pi * acc
        acc *= si
    return res


def get_values_from_global_info_file(global_info_file):
    """Read all values from global_info file"""
    global_values = {}
    with open(global_info_file, 'r') as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            split_line = line.strip().split(' ')
            cur_last_val = line.strip().split('\t')[-1]
            if i < len(lines) - 1:
                next_last_val = lines[i + 1].strip().split('\t')[-1]
            if split_line[0] == 'Vertices':
                global_values['Vertices'] = cur_last_val
            elif split_line[0] == 'Edges':
                global_values['Edges'] = cur_last_val
            elif split_line[0] == 'Total':
                if split_line[1] == 'degree':
                    global_values['Total_degree'] = cur_last_val
                elif split_line[1] == 'strength':
                    global_values['Total_strength'] = cur_last_val
            elif split_line[0] == 'Average':
                if split_line[1] == 'degree':
                    global_values['Average_degree'] = cur_last_val
                elif split_line[1] == 'strength':
                    global_values['Average_strength'] = cur_last_val
                elif split_line[1] == 'clustering':
                    if split_line[2] == 'coefficient':
                        global_values['Clustering_coeff'] = cur_last_val
                        a = 'Clustering_coeff_weighted'
                        global_values[a] = next_last_val
            elif split_line[0] == 'Minimum':
                if split_line[1] == 'degree':
                    global_values['Minimum_degree'] = cur_last_val
                elif split_line[1] == 'strength':
                    global_values['Minimum_strength'] = cur_last_val
            elif split_line[0] == 'Maximum':
                if split_line[1] == 'degree':
                    global_values['Maximum_degree'] = cur_last_val
                elif split_line[1] == 'strength':
                    global_values['Maximum_strength'] = cur_last_val
            elif split_line[0] == 'Assortativity':
                global_values['Assortativity'] = cur_last_val
                global_values['Assortativity_weighted'] = next_last_val
        return global_values


@staticmethod
def metadata_updated_on(item):
    """Extracts and coverts the update time from a Phabricator item.

        The timestamp is extracted from 'dateModified' field. This date is
        in UNIX timestamp format but needs to be converted to a float
        number.

        :param item: item generated by the backend

        :returns: a UNIX timestamp
        """
    return float(item['fields']['dateModified'])


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

        :param SsoRemoveLogoutUrlType val:
        :rtype: EventType
        """
    return cls('sso_remove_logout_url', val)


@classmethod
def unit_attname(cls, unit_str):
    """
        Retrieve the unit attribute name for the given unit string.
        For example, if the given unit string is 'metre', return 'm'.
        Raise an exception if an attribute cannot be found.
        """
    lower = unit_str.lower()
    if unit_str in cls.UNITS:
        return unit_str
    elif lower in cls.UNITS:
        return lower
    elif lower in cls.LALIAS:
        return cls.LALIAS[lower]
    else:
        raise Exception(
            'Could not find a unit keyword associated with "%s"' % unit_str)


def parse_featured_channels(item):
    """
    Parses and processes raw output and returns a dictionary where the key is the channel_id and the key is a list of channel URLs.

    :params item: json document
    :type item: dict

    :returns: parsed dictionary
    :rtype: dict
    """
    if not isinstance(item, dict):
        return dict()
    d = {}
    d[item['id']] = item['brandingSettings']['channel'].get(
        'featuredChannelsUrls', [])
    return d


def security_group_rule_type(neutron_type):
    """Translate neutron rule type.

    Translate to/from openstack - occi

    :param neutron_type: neutron status
    """
    if neutron_type == 'ingress':
        return 'inbound'
    elif neutron_type == 'egress':
        return 'outbound'
    elif neutron_type == 'inbound':
        return 'ingress'
    elif neutron_type == 'outbound':
        return 'egress'
    else:
        return None


def p_fancy_drel_assignment_stmt(p):
    """fancy_drel_assignment_stmt : ID OPEN_PAREN dotlist CLOSE_PAREN """
    p[0] = ['FANCY_ASSIGN', p[1], p[3]]


def allowedMimeTypes():
    """Get allowed MIME types
        """


@classmethod
def from_empty_sync(cls) ->'Universe':
    """Create an empty universe ready to be populated."""
    return cls()


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 '+'


@classmethod
def supported(cls, typ):
    """Return True if the type is supported by the field type."""
    return cls.check_type(typ) or cls.check_obj(typ)


@classmethod
def to_ordinal(cls, d):
    """Return month ordinal for date `d`."""
    return d.year * 12 + d.month


def invert_permutation_indices(indices):
    """Invert the permutation giver by indices.
    """
    inverted = [0] * len(indices)
    for i, index in enumerate(indices):
        inverted[index] = i
    return inverted


def trace2index_flat(shape, ntrace):
    """
    Calculate the index of a trace assuming a flat structure
    """
    q = ntrace
    index = []
    for s in shape[:0:-1]:
        q, r = divmod(q, s)
        index.insert(0, r)
    index.insert(0, q)
    return tuple(index)


def to_unicode(obj: object, encoding: str) ->str:
    """Return unicode representation of an object.

    Returns:

        str: unicoce string object representation

    """
    if isinstance(obj, str):
        return obj
    return bytes(obj).decode(encoding)


def check_server_url(srvurl):
    """Check given url for correctness"""
    good_name = srvurl.startswith('http://') or srvurl.startswith('https://')
    if not good_name:
        msg = 'You must include '
        msg += "http(s):// in your server's address, %s doesn't" % srvurl
        raise ValueError(msg)


def optimize_db(cursor):
    """Set options to make sqlite more efficient on a high memory machine"""
    cursor.execute('PRAGMA cache_size = -%i' % (0.1 * 10 ** 7))
    cursor.execute('PRAGMA temp_store = 2')


def client_method_template_f(method_name: str='', http_verb: str='',
    api_path: str='', doc_string: str='', path_params: str='') ->str:
    """
     one size fits *most* method template

    Args:
        http_verb (str): `GET`, `POST`, `PUT`, `DELETE` and `PATCH`
        method_name (str): a valid python function name as a string
        api_path (str): a valid URL part which is joined with the `BASE_PATH`.
                  Can contain path parameters. Will be evaluated to a string.
        doc_string (str): some description of the method and or endpoint
        path_params (str): e.g. pagination is frequently used in the path

    Returns:
        str: a method code string ready to be appended to python-client-module
    """
    py_code = f"""
    def {method_name}(self{path_params}, headers=None, body=None, fields_data=None, **kwargs):
        ""\" {doc_string} ""\"
        r = self._do_call(
                method='{http_verb.upper()}',
                url=f'{{self.API_BASE_URL}}{api_path}',
                headers=headers,
                body=body,
                fields=fields_data,
                **kwargs
        )
        return r
    """
    return py_code


def quantify():
    """how many times call is `True` for incoming things"""


def join_rows(rows, joiner=' '):
    """
    Given a series of rows, return them as a single row where the inner edge cells are merged. By default joins with a single space character, but you can specify new-line, empty string, or anything else with the 'joiner' kwarg.
    """
    rows = list(rows)
    fixed_row = rows[0][:]
    for row in rows[1:]:
        if len(row) == 0:
            row = ['']
        fixed_row[-1] += '%s%s' % (joiner, row[0])
        fixed_row.extend(row[1:])
    return fixed_row


def hasElement(node, element):
    """Check if exlement existing in a tag."""
    if node.getElementsByTagName(element).length > 0:
        return True
    else:
        return False


def getPortalRoles():
    """ Return a sequence of role names defined by the portal itself.

        o Returned role names are those understood by the portal object.

        o Permission:  Manage portal
        """


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

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

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


def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The logic is described in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    """
    return value.tzinfo is not None and value.tzinfo.utcoffset(value
        ) is not None


def world_remove():
    """Remove Rigid Body simulation world from the current scene

    """
    pass


def rows(addressed_data):
    """    iterate over dual-address and data sequence and make rows of up to
    16 data bytes, also restart rows if addresses jump.
    """
    stream = iter(addressed_data)
    while True:
        row = []
        a1, a2, data = next(stream)
        try:
            row.extend(bytearray(data))
            for i in range(len(data), 16, len(data)):
                an1, an2, data = next(stream)
                row.extend(bytearray(data))
                if a1 is not None and an1 != a1 + i:
                    break
                if a2 is not None and an2 != a2 + i:
                    break
        finally:
            yield a1, a2, row


def get_mtfe_derived_W_solv_max(FOS_offset, original_fos,
    solvation_group_count, PRO_PEP):
    """
    FOSS_offset is the off

    """
    original_fos = 0.0
    solvation_groups = list(original_fos.keys())
    BB_count = 0
    BB_PRO_count = 0


@staticmethod
def _reduce_index(t, idx, shift_text):
    """Reduces index of a text object if it lies within a spanning
        cell.

        Parameters
        ----------
        table : camelot.core.Table
        idx : list
            List of tuples of the form (r_idx, c_idx, text).
        shift_text : list
            {'l', 'r', 't', 'b'}
            Select one or more strings from above and pass them as a
            list to specify where the text in a spanning cell should
            flow.

        Returns
        -------
        indices : list
            List of tuples of the form (r_idx, c_idx, text) where
            r_idx and c_idx are new row and column indices for text.

        """
    indices = []
    for r_idx, c_idx, text in idx:
        for d in shift_text:
            if d == 'l':
                if t.cells[r_idx][c_idx].hspan:
                    while not t.cells[r_idx][c_idx].left:
                        c_idx -= 1
            if d == 'r':
                if t.cells[r_idx][c_idx].hspan:
                    while not t.cells[r_idx][c_idx].right:
                        c_idx += 1
            if d == 't':
                if t.cells[r_idx][c_idx].vspan:
                    while not t.cells[r_idx][c_idx].top:
                        r_idx -= 1
            if d == 'b':
                if t.cells[r_idx][c_idx].vspan:
                    while not t.cells[r_idx][c_idx].bottom:
                        r_idx += 1
        indices.append((r_idx, c_idx, text))
    return indices


def skipping_window(sequence, target, n=3):
    """
    Return a sliding window with a constraint to check that
    target is inside the window.
    From http://stackoverflow.com/q/43626525/610569

        >>> list(skipping_window([1,2,3,4,5], 2, 3))
        [(1, 2, 3), (2, 3, 4)]
    """
    start, stop = 0, n
    seq = list(sequence)
    while stop <= len(seq):
        subseq = seq[start:stop]
        if target in subseq:
            yield tuple(seq[start:stop])
        start += 1
        stop += 1
        try:
            start = max(seq.index(target, start) - (n - 1), start)
            stop = start + n
        except ValueError:
            break


@staticmethod
def _layers_opts():
    """Returns command options in a form that can be handled by the
        command parser."""
    opts = {'-h': {'type': bool, 'default': False}, '-c': {'type': bool,
        'default': False}}
    return opts


def getProducts():
    """ returns list of products currently in the cart
        """


@classmethod
def _strip_protocol(cls, path):
    """ For HTTP, we always want to keep the full URL
        """
    return path


def load_glib(finder, module):
    """Ignore globals that are imported."""
    module.AddGlobalName('GError')
    module.AddGlobalName('IOChannel')
    module.AddGlobalName('IO_ERR')
    module.AddGlobalName('IO_FLAG_APPEND')
    module.AddGlobalName('IO_FLAG_GET_MASK')
    module.AddGlobalName('IO_FLAG_IS_READABLE')
    module.AddGlobalName('IO_FLAG_IS_SEEKABLE')
    module.AddGlobalName('IO_FLAG_IS_WRITEABLE')
    module.AddGlobalName('IO_FLAG_MASK')
    module.AddGlobalName('IO_FLAG_NONBLOCK')
    module.AddGlobalName('IO_FLAG_SET_MASK')
    module.AddGlobalName('IO_HUP')
    module.AddGlobalName('IO_IN')
    module.AddGlobalName('IO_NVAL')
    module.AddGlobalName('IO_OUT')
    module.AddGlobalName('IO_PRI')
    module.AddGlobalName('IO_STATUS_AGAIN')
    module.AddGlobalName('IO_STATUS_EOF')
    module.AddGlobalName('IO_STATUS_ERROR')
    module.AddGlobalName('IO_STATUS_NORMAL')
    module.AddGlobalName('Idle')
    module.AddGlobalName('MainContext')
    module.AddGlobalName('MainLoop')
    module.AddGlobalName('OPTION_ERROR')
    module.AddGlobalName('OPTION_ERROR_BAD_VALUE')
    module.AddGlobalName('OPTION_ERROR_FAILED')
    module.AddGlobalName('OPTION_ERROR_UNKNOWN_OPTION')
    module.AddGlobalName('OPTION_FLAG_FILENAME')
    module.AddGlobalName('OPTION_FLAG_HIDDEN')
    module.AddGlobalName('OPTION_FLAG_IN_MAIN')
    module.AddGlobalName('OPTION_FLAG_NOALIAS')
    module.AddGlobalName('OPTION_FLAG_NO_ARG')
    module.AddGlobalName('OPTION_FLAG_OPTIONAL_ARG')
    module.AddGlobalName('OPTION_FLAG_REVERSE')
    module.AddGlobalName('OPTION_REMAINING')
    module.AddGlobalName('OptionContext')
    module.AddGlobalName('OptionGroup')
    module.AddGlobalName('PRIORITY_DEFAULT')
    module.AddGlobalName('PRIORITY_DEFAULT_IDLE')
    module.AddGlobalName('PRIORITY_HIGH')
    module.AddGlobalName('PRIORITY_HIGH_IDLE')
    module.AddGlobalName('PRIORITY_LOW')
    module.AddGlobalName('Pid')
    module.AddGlobalName('PollFD')
    module.AddGlobalName('SPAWN_CHILD_INHERITS_STDIN')
    module.AddGlobalName('SPAWN_DO_NOT_REAP_CHILD')
    module.AddGlobalName('SPAWN_FILE_AND_ARGV_ZERO')
    module.AddGlobalName('SPAWN_LEAVE_DESCRIPTORS_OPEN')
    module.AddGlobalName('SPAWN_SEARCH_PATH')
    module.AddGlobalName('SPAWN_STDERR_TO_DEV_NULL')
    module.AddGlobalName('SPAWN_STDOUT_TO_DEV_NULL')
    module.AddGlobalName('Source')
    module.AddGlobalName('Timeout')
    module.AddGlobalName('child_watch_add')
    module.AddGlobalName('filename_display_basename')
    module.AddGlobalName('filename_display_name')
    module.AddGlobalName('filename_from_utf8')
    module.AddGlobalName('get_application_name')
    module.AddGlobalName('get_current_time')
    module.AddGlobalName('get_prgname')
    module.AddGlobalName('glib_version')
    module.AddGlobalName('idle_add')
    module.AddGlobalName('io_add_watch')
    module.AddGlobalName('main_context_default')
    module.AddGlobalName('main_depth')
    module.AddGlobalName('markup_escape_text')
    module.AddGlobalName('set_application_name')
    module.AddGlobalName('set_prgname')
    module.AddGlobalName('source_remove')
    module.AddGlobalName('spawn_async')
    module.AddGlobalName('timeout_add')
    module.AddGlobalName('timeout_add_seconds')


def constant_to_callable(eps):
    """
	Takes in a constant eps (int, float, or complex) and returns a function
	eps(kpar,omega).

	Useful for writing code that assumes callables for generality.
	"""
    epsval = eps
    del eps
    eps = lambda kp, w: epsval
    return eps


def decrementAny(tup):
    """ the closest tuples to tup: decrementing by 1 along any dimension.
    Never go into negatives though. """
    res = []
    for i, x in enumerate(tup):
        if x > 0:
            res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:])))
    return res


@classmethod
def must_ignore(cls, url):
    """Check if url must be ignored by check links based on ignore list."""
    for ignore_pattern in cls.regex_urls_to_ignore:
        if ignore_pattern in url:
            return True
    return False


def exc_to_str(e):
    """
    Exception as string.
    """
    return getattr(e, 'message', None) or str(e)


def preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Render Preset

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


def supported_activation_methods(res):
    """
    Given an activation_requirements document
    returns a list of activation methods supported by this endpoint.
    """
    supported = ['web']
    if res['oauth_server']:
        supported.append('oauth')
    for req in res['DATA']:
        if req['type'] == 'myproxy' and req['name'] == 'hostname' and req[
            'value'] != 'myproxy.globusonline.org':
            supported.append('myproxy')
        if req['type'] == 'delegate_proxy' and req['name'] == 'public_key':
            supported.append('delegate_proxy')
    return supported


@classmethod
def get_ca_configuration(cls, ca_name):
    """ Get list of CAs from configuration

        :rtype: list: Returns list of CAs loaded from configuration file

        """
    for cert_authority in cls.cas:
        if ca_name == cert_authority['name']:
            return cert_authority
    return []


def Fields(*args, **kw):
    """Return a list of formlib fields based on interfaces and/or schema
        fields."""


def immediate_read(f):
    """A PinBank read mode: read() is called automatically whenever a pin value is read.

    Note: this mode is not compatible with interrupts. A warning will
    be issued if interrupts are enabled on a PinBank that is in
    immediate_read mode.
    """
    f()


def find_cell(nb, cell_name):
    """
    find a named cell within a notebook
    """
    for cell in nb.cells:
        if 'name' in cell.metadata and cell.metadata['name'] == cell_name:
            return nb.cells.index(cell), cell
    return None, None


def linear_gradient(temperature, temperature_height, hub_height):
    """
    Calculates the temperature at hub height using a linear gradient.

    A linear temperature gradient of -6.5 K/km is assumed. This function is
    carried out when the parameter `temperature_model` of an instance of
    the :class:`~.modelchain.ModelChain` class is
    'temperature_gradient'.

    Parameters
    ----------
    temperature : :pandas:`pandas.Series<series>` or numpy.array
        Air temperature in K.
    temperature_height : float
        Height in m for which the parameter `temperature` applies.
    hub_height : float
        Hub height of wind turbine in m.

    Returns
    -------
    :pandas:`pandas.Series<series>` or numpy.array
        Temperature at hub height in K.

    Notes
    -----

    The following equation is used [1]_:

    .. math:: T_{hub}=T_{air}-0.0065\\cdot\\left(h_{hub}-h_{T,data}\\right)

    with:
        T: temperature [K], h: height [m]

    :math:`h_{T,data}` is the height in which the temperature :math:`T_{air}`
    is measured and :math:`T_{hub}` is the temperature at hub height
    :math:`h_{hub}` of the wind turbine.

    Assumptions:

    * Temperature gradient of -6.5 K/km (-0.0065 K/m)

    References
    ----------
    .. [1] ICAO-Standardatmosphäre (ISA).
        http://www.dwd.de/DE/service/lexikon/begriffe/S/Standardatmosphaere_pdf.pdf?__blob=publicationFile&v=3

    """
    return temperature - 0.0065 * (hub_height - temperature_height)


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

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


def _lower_neighbours(G, u):
    """ Given a graph `G` and a vertex `u` in `G`, we return a list with the
    vertices in `G` that are lower than `u` and are connected to `u` by an
    edge in `G`.

    Parameters
    ----------
    G : :obj:`Numpy Array(no. of edges, 2)`
        Matrix storing the edges of the graph.
    u : int
        Vertex of the graph.

    Returns
    -------
    lower_neighbours : :obj:`list`
        List of lower neighbours of `u` in `G`.
    """
    lower_neighbours = []
    for e in G:
        if e[1] == u:
            lower_neighbours.append(e[0])
    lower_neighbours.sort()
    return lower_neighbours