@staticmethod
def filter_entry_by_matching_url(har_page, url_matcher):
    """
        Static method to match request url, an absolute string match is made
        e.g. bproxy.filter_entry_by_matching_url(har_page, "gstatic.com")
        :param HarParser.page har_page: HarParser page instance
        :param str url_matcher: matching url
        :return: list of matching page entry
        """
    matching_list = []
    for entry in har_page.entries:
        if url_matcher in entry['request']['url']:
            matching_list.append(entry)
    return matching_list


def tris_convert_to_quads(face_threshold: float=0.698132, shape_threshold:
    float=0.698132, uvs: bool=False, vcols: bool=False, seam: bool=False,
    sharp: bool=False, materials: bool=False):
    """Join triangles into quads

    :param face_threshold: Max Face Angle, Face angle limit
    :type face_threshold: float
    :param shape_threshold: Max Shape Angle, Shape angle limit
    :type shape_threshold: float
    :param uvs: Compare UVs
    :type uvs: bool
    :param vcols: Compare VCols
    :type vcols: bool
    :param seam: Compare Seam
    :type seam: bool
    :param sharp: Compare Sharp
    :type sharp: bool
    :param materials: Compare Materials
    :type materials: bool
    """
    pass


def api_client_user_agent():
    """
    Returns the string of User-Agent to use in api calls.
    """
    from . import __version__
    return 'Telemetron-client-python/%s' % (__version__,)


def decode_bitmask(mask, value, strict=True):
    """Decode a integer value into its symbolic bit names.

    Use this function to convert a bitmask value into a list of symbolic bit names,
    for example::

        >>> COLORS = define_bitmask('COLORS','Primary colors',RED=0,BLUE=1,GREEN=4)
        >>> decode_bitmask(COLORS,COLORS.RED|COLORS.BLUE)
        ('RED', 'BLUE')

    For pretty printing, try::

        >>> print('|'.join(decode_bitmask(COLORS,COLORS.RED|COLORS.BLUE)))
        RED|BLUE

    Args:
        mask: A bitmask type, normally created with :func:`create_bitmask`, that defines
            the symbolic bit names to use for the decoding.
        value(int): The integral value to decode.
        strict(bool): If set, then all bits set in value must be defined in the bitmask
            type definition.

    Returns:
        tuple: A tuple of symbolic bit names in order of increasing bit offset. If strict
            is False, then any bits without corresponding symbolic names will appear as
            '1<<n' for offset n.

    Raises:
        AttributeError: mask does not have the attributes necessary to define a bitmask.
        ValueError: value has a bit set that has no symbolic name defined and strict is True.
    """
    names = []
    shifted = int(value)
    offset = 0
    while shifted:
        if shifted & 1:
            name = mask._reverse_map.get(offset)
            if name is None:
                if strict:
                    raise ValueError(
                        'Bit {0:d} is set but has no symbolic name defined.'
                        .format(offset))
                name = '1<<{0:d}'.format(offset)
            names.append(name)
        offset += 1
        shifted = shifted >> 1
    return tuple(names)


def check_dekad_startdate(dt):
    """
    Check if a date is a dekad startdate
    """
    if dt.day in [1, 11, 21]:
        return True
    else:
        return False


@classmethod
def enable(cls):
    """Enables page domain notifications.
        """
    return cls.build_send_payload('enable', {}), None


def inc_value(value, name, node):
    """Increment global value with node attribute values"""
    ival = 0
    try:
        sval = node.attributes[name].value
        ival = int(sval)
    finally:
        return value + ival


def json_response_schema(expected_object_schema):
    """
    Make a schema for a "standard" server response.
    Standard server responses have 'status': True
    and possibly 'indexing': True set.
    """
    schema = {'type': 'object', 'properties': {'status': {'type': 'boolean'
        }, 'indexing': {'type': 'boolean'}, 'lastblock': {'anyOf': [{'type':
        'integer', 'minimum': 0}, {'type': 'null'}]}}, 'required': [
        'status', 'indexing', 'lastblock']}
    schema['properties'].update(expected_object_schema['properties'])
    schema['required'] = list(set(schema['required'] +
        expected_object_schema['required']))
    return schema


def sum(input, dim, keepdims=False):
    """Reduce sum the input tensor along the given dim.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    dim : int
        The reduce dim.
    keepdims : bool
        Whether to keep the summed dimension.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


def get_invoice_filename(metadata_file_xml_root,
    metadata_file_invoice_filename_xml_tag: str,
    metadata_file_xml_namespace: str) ->str:
    """Return the file name of the invoice file.

    :param metadata_file_xml_root: the root of the metadata XML tree.
    :param metadata_file_invoice_filename_xml_tag: the tag name corresponding
        to the invoice filename.
    :param metadata_file_xml_namespace: the XML namespace of the metadata file.
    :type metadata_file_xml_root: lxml.etree._Element
    :type metadata_file_invoice_filename_xml_tag: str
    :type metadata_file_xml_namespace: str
    :returns: the element or ``None``, if no match is found.
    :rtype: str
    :raises: an lxml or a built-in exception.
    """
    return metadata_file_xml_root.find(metadata_file_invoice_filename_xml_tag,
        metadata_file_xml_namespace).text


def categories():
    """ Return a sorted sequence of category names known by
         this introspector """


def clog2(num: int) ->int:
    """Return the ceiling log base two of an integer :math:`\\ge 1`.

    This function tells you the minimum dimension of a Boolean space with at
    least N points.

    For example, here are the values of ``clog2(N)`` for :math:`1 \\le N < 18`:

    >>> [clog2(n) for n in range(1, 18)]
    [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5]

    This function is undefined for non-positive integers:

    >>> clog2(0)
    Traceback (most recent call last):
        ...
    ValueError: expected num >= 1
    """
    if num < 1:
        raise ValueError('expected num >= 1')
    accum, shifter = 0, 1
    while num > shifter:
        shifter <<= 1
        accum += 1
    return accum


def clipboard_paste():
    """Pastes nodes from the clipboard to the active node tree

    """
    pass


@staticmethod
def defaultServerModError():
    """The default function that gives an error when a Discord Member is trying to run a Server Moderator command
        without having the proper permissions.
        """
    return 'You do not have the proper permissions to run this command.'


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 is_classifier(estimator):
    """
    Returns True if the given estimator is (probably) a classifier.

    Parameters
    ----------
    estimator : class or instance
        The object to test if it is a Scikit-Learn clusterer, especially a
        Scikit-Learn estimator or Yellowbrick visualizer

    See also
    --------
    is_classifier
        `sklearn.is_classifier() <https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py#L518>`_
    """
    return getattr(estimator, '_estimator_type', None) == 'classifier'


def check_bool(**params):
    """Check that parameters are bools as expected

    Raises
    ------
    ValueError : unacceptable choice of parameters
    """
    for p in params:
        if params[p] is not True and params[p] is not False:
            raise ValueError('Expected {} boolean, got {}'.format(p, params[p])
                )


def generic_find_uq_constraint_name(table, columns, insp):
    """Utility to find a unique constraint name in alembic migrations"""
    for uq in insp.get_unique_constraints(table):
        if columns == set(uq['column_names']):
            return uq['name']


def _color(string, ansi, bold=False):
    """Colors the given string with the given ANSI color index."""
    return '\x1b[1;{}m{}\x1b[0m'.format(ansi, string)


def fileobj_closed(f):
    """
    Returns True if the given file-like object is closed or if f is a string
    (and assumed to be a pathname).

    Returns False for all other types of objects, under the assumption that
    they are file-like objects with no sense of a 'closed' state.
    """
    if isinstance(f, str):
        return True
    if hasattr(f, 'closed'):
        return f.closed
    elif hasattr(f, 'fileobj') and hasattr(f.fileobj, 'closed'):
        return f.fileobj.closed
    elif hasattr(f, 'fp') and hasattr(f.fp, 'closed'):
        return f.fp.closed
    else:
        return False


@staticmethod
def request_output_status(output_id):
    """Generate an output-port status request.

        :param    int    output_id:    Output id 0..3
        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    if output_id < 0 or output_id > 3:
        raise ValueError('Invalid output_id.')
    return 'SMA{:d}'.format(output_id + 1)


@staticmethod
def format_packet(command, num_serial):
    """Format packet to be sent."""
    frame_header = b'!' + num_serial.encode()
    return frame_header + command.encode()


def shuffle(iterable):
    """
    Returns a shuffled copy of the list.
    Caution: DOes not work with unordered collections and generators

    params: iterable
        iterable -> list, sequenece,

    Examples:
    >>> _.shuffle([1, 2, 3, 4, 5, 6]);
    >>> [4, 1, 6, 3, 5, 2]
    """
    from random import random
    return sorted(iterable, key=lambda x: random())


def calculate_widths(parts, num=12):
    """
    Generates a list of length parts containing integers, the sum of which is num.
    """
    first = num // parts
    last = num - (parts - 1) * first
    return (parts - 1) * [first] + [last]


def KK_RC3(w, Rs, R_values, t_values):
    """
    Kramers-Kronig Function: -RC-

    Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
    """
    return Rs + R_values[0] / (1 + w * 1.0j * t_values[0]) + R_values[1] / (
        1 + w * 1.0j * t_values[1]) + R_values[2] / (1 + w * 1.0j * t_values[2]
        )


def affine_weights(dim):
    """Compute coefficents for mapping from reference to physical element"""
    if dim == 1:
        return lambda x: (1.0 - x[0], x[0])
    elif dim == 2:
        return lambda x: (1.0 - x[0] - x[1], x[0], x[1])
    elif dim == 3:
        return lambda x: (1.0 - x[0] - x[1] - x[2], x[0], x[1], x[2])


def thiels_U(ys_true=None, ys_pred=None, display_equation=True,
    display_table=True):
    """Calculate's Thiel's U metric for forecasting accuracy.
    Accepts true values and predicted values.
    Returns Thiel's U"""
    from IPython.display import Markdown, Latex, display
    import numpy as np
    display(Markdown(''))
    eqn = (
        ' $$U = \\sqrt{\\frac{ \\sum_{t=1 }^{n-1}\\left(\\frac{\\bar{Y}_{t+1} - Y_{t+1}}{Y_t}\\right)^2}{\\sum_{t=1 }^{n-1}\\left(\\frac{Y_{t+1} - Y_{t}}{Y_t}\\right)^2}}$$'
        )
    markdown_explanation = """|Thiel's U Value | Interpretation |
    | --- | --- |
    | <1 | Forecasting is better than guessing|
    | 1 | Forecasting is about as good as guessing|
    |>1 | Forecasting is worse than guessing|
"""
    if display_equation and display_table:
        display(Latex(eqn), Markdown(markdown_explanation))
    elif display_equation:
        display(Latex(eqn))
    elif display_table:
        display(Markdown(markdown_explanation))
    if ys_true is None and ys_pred is None:
        return
    num_list = []
    denom_list = []
    for t in range(len(ys_true) - 1):
        num_exp = (ys_pred[t + 1] - ys_true[t + 1]) / ys_true[t]
        num_list.append([num_exp ** 2])
        denom_exp = (ys_true[t + 1] - ys_true[t]) / ys_true[t]
        denom_list.append([denom_exp ** 2])
    U = np.sqrt(np.sum(num_list) / np.sum(denom_list))
    return U


def add_body(ax, rad=2.0, rotate=0.0, add_night=True, **extra_kwargs):
    """
    Creates a circle of radius kwarg rad (default 2.0 RE) at the center of
    axis ax.  Then, a planet of radius 1.0 RE is added to the center to
    represent the Earth.  Extra kwargs are passed to the patch generators.

    Three patches are created by this function: the inner boundary (a light
    grey Circle patch), the planet (a white Circle patch) and the night side
    of the planet (a black wedge.)  All three are returned to the caller.

    The kwarge "rotate", which defaults to 0.0, can be set to any angle
    (in degrees) to rotate the location of local noon/midnight on the
    planet patches.  The default is local noon points towards +X.  A
    rotate value of 90 will cause local noon to point towards +Y.

    Example

    >>>ax=pylab.subplot(111)
    >>>inner, planet, night = rampy.add_body(ax)

    If you are using a polar axis, try using add_body_polar.
    """
    from matplotlib.patches import Circle, Wedge
    inner = Circle((0, 0), rad, fc='lightgrey', ec='k', zorder=1000, **
        extra_kwargs)
    planet = Circle((0, 0), 1.0, fc='w', zorder=1001, **extra_kwargs)
    night = Wedge((0, 0), 1.0, 90 + rotate, -90 + rotate, fc='k', zorder=
        1002, **extra_kwargs)
    ax.add_artist(inner)
    ax.add_artist(planet)
    if add_night:
        ax.add_artist(night)
    return inner, planet, night


@classmethod
def get_table_names(cls, schema, inspector):
    """Need to disregard the schema for Sqlite"""
    return sorted(inspector.get_table_names())


def find_value(dic, key):
    """return the value of dictionary dic given the key"""
    return dic[key]


@classmethod
def input_labelled(cls, label):
    """Returns an XPath to find an HTML <input> referred to by a <label> that contains the text in `label`."""
    for_based_xpath = (
        '//input[@id=//label[normalize-space(node())=normalize-space("%s")]/@for]'
         % label)
    nested_xpath = (
        '//label[normalize-space()=normalize-space("%s")]//input' % label)
    return cls('%s|%s' % (for_based_xpath, nested_xpath))


def model_key(model):
    """For a given model, return 'appname.modelname'."""
    return '%s.%s' % (model._meta.app_label, model._meta.object_name.lower())


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

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


def p_compound_stmt_5(p):
    """compound_stmt : with_stmt"""
    p[0] = [p[1]]


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

        :param AccountCaptureNotificationEmailsSentDetails val:
        :rtype: EventDetails
        """
    return cls('account_capture_notification_emails_sent_details', val)


@staticmethod
def _flag_what_changed(note, what_changed):
    """Flag a note field as changed"""
    if 'what_changed' not in note:
        note['what_changed'] = []
    if what_changed not in note['what_changed']:
        note['what_changed'].append(what_changed)


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

        :param LegalHoldsActivateAHoldDetails val:
        :rtype: EventDetails
        """
    return cls('legal_holds_activate_a_hold_details', val)


@classmethod
def _chunk_end_indexes_from_vcf_record_list(cls, record_list, start_index,
    flank_length, total_sites=None, total_alleles=None):
    """Returns tuple of:
           1. last index of VCF record that we want to use for variant calling
           2. index of last variant in the chunk, which can't be used for variant calling
              but should end up in the gramtools graph"""
    assert total_sites != total_alleles and (total_sites is not None or
        total_alleles is not None)
    file_start_index = start_index
    while file_start_index > 0:
        distance_to_previous_variant = record_list[start_index
            ].POS - record_list[file_start_index - 1].ref_end_pos()
        if distance_to_previous_variant > flank_length:
            break
        file_start_index -= 1
    if total_sites is not None:
        use_vcf_end_index = min(start_index + total_sites - 1, len(
            record_list) - 1)
    else:
        use_vcf_end_index = start_index
        alleles = 1 + len(record_list[start_index].ALT)
        while use_vcf_end_index < len(record_list
            ) - 1 and alleles <= total_alleles:
            use_vcf_end_index += 1
            alleles += 1 + len(record_list[use_vcf_end_index].ALT)
        use_vcf_end_index = max(start_index, use_vcf_end_index - 1)
    if use_vcf_end_index == len(record_list) - 1:
        return file_start_index, use_vcf_end_index, use_vcf_end_index
    file_end_index = use_vcf_end_index
    while file_end_index < len(record_list) - 1:
        distance_to_next_variant = record_list[file_end_index + 1
            ].POS - record_list[use_vcf_end_index].ref_end_pos()
        if distance_to_next_variant > flank_length:
            break
        file_end_index += 1
    return file_start_index, use_vcf_end_index, min(file_end_index, len(
        record_list) - 1)


def return_vars(var_list):
    """Generate RETURN query with the input variables."""
    return 'RETURN {}\n'.format(', '.join(var_list))


def only_numbers(char):
    """  Validation entry widgets: only digits """
    return char.isdigit()


def get_args(require=0):
    """
    >> get_args [<require>]

    Load the command line arguments after the last '--' into $arg1...$argN,
    optionally requiring at least 'require' such arguments.
    """
    from twill3 import commands, namespaces, shell, errors
    global_dict, local_dict = namespaces.get_twill_glocals()
    require = int(require)
    if len(shell.twillargs) < require:
        from twill3.errors import TwillAssertionError
        raise TwillAssertionError('too few arguments; %d rather than %d' %
            (len(shell.twillargs), require))
    if shell.twillargs:
        for i, arg in enumerate(shell.twillargs):
            global_dict['arg%d' % (i + 1,)] = arg
        print('get_args: loaded %d args as $arg1..$arg%d.' % (i + 1, i + 1),
            file=commands.OUT)
    else:
        print('no arguments to parse!', file=commands.OUT)


def get_corner_coordinates(gdal_ds=None, gt=None, cols=None, rows=None):
    """Returns (ULxy, LLxy, LRxy, URxy) in the same coordinate units like the given geotransform."""
    assert gdal_ds or gt and cols and rows, "GEOP.get_corner_coordinates: Missing argument! Please provide either 'gdal_ds' or 'gt', 'cols' AND 'rows'."
    gdal_ds_GT = gdal_ds.GetGeoTransform() if gdal_ds else gt
    ext = []
    xarr = [0, gdal_ds.RasterXSize if gdal_ds else cols]
    yarr = [0, gdal_ds.RasterYSize if gdal_ds else rows]
    for px in xarr:
        for py in yarr:
            x = gdal_ds_GT[0] + px * gdal_ds_GT[1] + py * gdal_ds_GT[2]
            y = gdal_ds_GT[3] + px * gdal_ds_GT[4] + py * gdal_ds_GT[5]
            ext.append([x, y])
        yarr.reverse()
    del gdal_ds_GT
    return ext


def percent_error(prediction, target):
    """
    Return the percent error of a predicted value compared
    to a target value
    """
    if prediction == target:
        return 0
    else:
        return abs(prediction - target) / max(prediction, target) * 100


def bind(handler):
    """Simple binding function"""
    return lambda scanner, token: handler(scanner, token)


def vertex_group_add():
    """Add a new vertex group to the active object

    """
    pass


def del_invalid_routes(engine, nicids):
    """
    Helper method to run through and delete any routes that are tagged
    as invalid or to_delete by a list of nicids. Since we could have a
    list of routes, iterate from top level engine routing node to avoid
    fetch exceptions. Route list should be a list of nicids as str.

    :param list nicids: list of nicids
    :raises DeleteElementFailed: delete element failed with reason
    """
    nicids = map(str, nicids)
    for interface in engine.routing:
        if interface.nicid in nicids:
            if getattr(interface, 'to_delete', False):
                interface.delete()
                continue
        for network in interface:
            if getattr(network, 'invalid', False) or getattr(network,
                'to_delete', False):
                network.delete()


def device_info(jaide):
    """ Retrieve basic device information.

    @param jaide: The jaide connection to the device.
    @type jaide: jaide.Jaide object

    @returns: The output from the device.
    @rtype str
    """
    return jaide.device_info()


@classmethod
def get(klass, name):
    """
        Return a specific subclass by slug
        """
    for sub in klass.list():
        if sub.get_slug() == name:
            return sub


@staticmethod
def _get_parent_dn(dn):
    """
        Gets the dn of the parent object
        Meant to be overridden by inheriting classes.
        Raises exception if not overridden.

        :returns: string containing dn
        """
    return dn.split('/psu-')[0]


def describe_selection(selection):
    """Create a human-readable description of the given selection

    Parameters
    ----------
    selection: FileSelectionFile

    Returns
    -------
    str

    """
    return f"""Selection containing {len(selection.selected_paths)} files:
Description: {selection.description}"""


def parse_dimensions(tag, tag_json, dimension_keys=('width', 'height')):
    """
    Adds dimensions to converted JSON. Images and iframes will generally
    have width/height properties; this is just a convenience method for
    adding those properties.
    """
    for dimension_key in dimension_keys:
        try:
            tag_json[dimension_key] = int(tag.attrs.get(dimension_key))
        except Exception:
            pass


def get_password_option(version):
    """Gets the password option template string to use for the SET PASSWORD sql query

    This helper function takes in the mysql version and returns the appropriate password option template string that can
    be used in the SET PASSWORD query for that mysql version.

    Args:
        version (string): The mysql database version

    Returns:
        PasswordOption: The password option string

    """
    if version.startswith('8'):
        return '%s'
    else:
        return 'PASSWORD(%s)'


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 _constant_time_compare(val1, val2):
    """
    Returns True if the two strings are equal, False otherwise.

    The time taken is independent of the number of characters that match.
    """
    if len(val1) != len(val2):
        return False
    result = 0
    if isinstance(val1, bytes) and isinstance(val2, bytes):
        for x, y in zip(val1, val2):
            result |= x ^ y
    else:
        for x, y in zip(val1, val2):
            result |= ord(x) ^ ord(y)
    return result == 0


def normalize_dictionary(data_dict):
    """
    Converts all the keys in "data_dict" to strings. The keys must be
    convertible using str().
    """
    for key, value in data_dict.items():
        if not isinstance(key, str):
            del data_dict[key]
            data_dict[str(key)] = value
    return data_dict


def decode_payload(encoding, payload):
    """Decode the payload according to the given encoding

    Supported encodings: base64, quoted-printable.

    :param encoding: the encoding's name
    :param payload: the value to decode
    :return: a string
    """
    encoding = encoding.lower()
    if encoding == 'base64':
        import base64
        return base64.b64decode(payload)
    elif encoding == 'quoted-printable':
        import quopri
        return quopri.decodestring(payload)
    return payload


def insert_commands() ->dict:
    """Lists the available sub-commands of the 'chado insert' command with corresponding descriptions"""
    return {'organism': 'insert an organism into the CHADO database'}


def _prefix_paths(tree, nodes):
    """ Generate all paths of tree leading to all item nodes """
    for node in nodes:
        path = []
        support = node.count
        node = node.parent
        while node.item is not None:
            path.append(node.item)
            node = node.parent
        if path:
            yield support, path


def p_scalar_value(p):
    """SCALAR_VALUE : BOOLEAN
                    | INTEGER
                    | INTEGER64
                    | HEX
                    | HEX64
                    | FLOAT
                    | STRING"""
    p[0] = p[1]


def filesizeformat(bytes, sep=' '):
    """
    Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
    102 B, 2.3 GB etc).

    Grabbed from Django (http://www.djangoproject.com), slightly modified.

    :param bytes: size in bytes (as integer)
    :param sep: string separator between number and abbreviation
    """
    try:
        bytes = float(bytes)
    except (TypeError, ValueError, UnicodeDecodeError):
        return '0%sB' % sep
    if bytes < 1024:
        size = bytes
        template = '%.0f%sB'
    elif bytes < 1024 * 1024:
        size = bytes / 1024
        template = '%.0f%sKB'
    elif bytes < 1024 * 1024 * 1024:
        size = bytes / 1024 / 1024
        template = '%.1f%sMB'
    else:
        size = bytes / 1024 / 1024 / 1024
        template = '%.2f%sGB'
    return template % (size, sep)


def elemwise_div(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Divides arguments element-wise.

    The storage type of ``elemwise_div`` output is always dense

    Parameters
    ----------
    lhs : Symbol
        first input
    rhs : Symbol
        second input

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

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


def create_replication_subnet_group(ReplicationSubnetGroupIdentifier=None,
    ReplicationSubnetGroupDescription=None, SubnetIds=None, Tags=None):
    """
    Creates a replication subnet group given a list of the subnet IDs in a VPC.
    See also: AWS API Documentation

    :example: response = client.create_replication_subnet_group(
        ReplicationSubnetGroupIdentifier='string',
        ReplicationSubnetGroupDescription='string',
        SubnetIds=[
            'string',
        ],
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ReplicationSubnetGroupIdentifier: string
    :param ReplicationSubnetGroupIdentifier: [REQUIRED]
            The name for the replication subnet group. This value is stored as a lowercase string.
            Constraints: Must contain no more than 255 alphanumeric characters, periods, spaces, underscores, or hyphens. Must not be 'default'.
            Example: mySubnetgroup

    :type ReplicationSubnetGroupDescription: string
    :param ReplicationSubnetGroupDescription: [REQUIRED]
            The description for the subnet group.

    :type SubnetIds: list
    :param SubnetIds: [REQUIRED]
            The EC2 subnet IDs for the subnet group.
            (string) --

    :type Tags: list
    :param Tags: The tag to be assigned to the subnet group.
            (dict) --
            Key (string) --A key is the required name of the tag. The string value can be from 1 to 128 Unicode characters in length and cannot be prefixed with 'aws:' or 'dms:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').
            Value (string) --A value is the optional value of the tag. The string value can be from 1 to 256 Unicode characters in length and cannot be prefixed with 'aws:' or 'dms:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').

    :rtype: dict
    :return: {
        'ReplicationSubnetGroup': {
            'ReplicationSubnetGroupIdentifier': 'string',
            'ReplicationSubnetGroupDescription': 'string',
            'VpcId': 'string',
            'SubnetGroupStatus': 'string',
            'Subnets': [
                {
                    'SubnetIdentifier': 'string',
                    'SubnetAvailabilityZone': {
                        'Name': 'string'
                    },
                    'SubnetStatus': 'string'
                },
            ]
        }
    }

    """
    pass


def get_class_property_from_TEMPLATE(texts_TEMPLATE, template):
    """찾은 문형과 일치하는 템플릿 문형에서 클래스와 프러퍼티 요소를 추출합니다"""
    class_property = []
    for t_template in texts_TEMPLATE:
        if t_template[0] == template:
            class_property.append(t_template[1])
            class_property.append(t_template[2])
            class_property.append(t_template[3])
            class_property.append(t_template[4])
    return class_property


def update_dictionary(current_dict, update_dict, constructor):
    """Update current_dict to update_dict without reconstructing existing

    update_dictionary updates the dict current_dict to resemble update_dict
    by
        1. removing values from current_dict that are missing in update_dict.
           (via del current_dict('missing'))
        2. adding values to current_dict that are only found in update_dict.
           (via constructor(update_dict['new'])
        3. update values (via current_dict[i].update(update_dict['changed']))

    Args:
        current_dict: The dict to update with entities
        update_dict: The latest dict with update payloads
        constructor: Constructor funtion to generate entity with payload

    """
    existing_keys = set(current_dict.keys())
    update_keys = set(update_dict.keys())
    for i in existing_keys.intersection(update_keys):
        current_dict[i].update(update_dict[i])
    for i in update_keys.difference(existing_keys):
        current_dict[i] = constructor(update_dict[i])
    for i in existing_keys.difference(update_keys):
        del current_dict[i]


def fwrite(filename: str, content, mode: str='w', coding: str='utf8'):
    """ Write the file that has the filename with content.
        Default mode: "w"
        Default coding: utf8."""
    with open(filename, mode, encoding=coding) as file:
        if type(content) != str:
            content = repr(content)
        file.write(content)


@classmethod
def is_datasource_for(cls, **kwargs):
    """
        Determines if header corresponds to an EVE image.
        """
    if kwargs.get('source', ''):
        return kwargs.get('source', '').lower().startswith(cls._source)


def imports_on_separate_lines(logical_line):
    """Imports should usually be on separate lines.

    Okay: import os\\nimport sys
    E401: import sys, os

    Okay: from subprocess import Popen, PIPE
    Okay: from myclas import MyClass
    Okay: from foo.bar.yourclass import YourClass
    Okay: import myclass
    Okay: import foo.bar.yourclass
    """
    line = logical_line
    if line.startswith('import '):
        found = line.find(',')
        if -1 < found and ';' not in line[:found]:
            yield found, 'E401 multiple imports on one line'


@classmethod
def adapt_emulated_to_native(cls, impl, **kw):
    """Produce a MySQL native :class:`.mysql.ENUM` from plain
        :class:`.Enum`.

        """
    kw.setdefault('validate_strings', impl.validate_strings)
    kw.setdefault('values_callable', impl.values_callable)
    return cls(**kw)


def __new__(meta_class, class_name, bases, class_dict, **kw_arguments):
    """
        Create a new type object, for example through a 'class' statement.

        Behaves like a class method and is called before __init__().
        """
    if kw_arguments:
        specialized_meta_class = meta_class.__specialize(kw_arguments)
        specialized_bases = []
        for base in bases:
            if base.__class__ is meta_class:
                specialized_bases.append(specialized_meta_class.__new__(
                    specialized_meta_class, base.__plain_name__, base.
                    __bases__, base.__dict__))
            else:
                specialized_bases.append(base)
        return specialized_meta_class.__new__(specialized_meta_class,
            class_name, tuple(specialized_bases), class_dict)
    else:
        extended_name = meta_class.__template_name(class_name, meta_class.
            __parameters__, meta_class.__parameter_map__)
        extended_dict = meta_class.__parameter_map__.copy()
        extended_dict.update(class_dict)
        extended_dict['__plain_name__'] = class_name
        return type.__new__(meta_class, extended_name, bases, extended_dict)


def meta_headers(text_minutes):
    """Extract the metadata section of a meeting.

    - simple format of Key: Value.
    - Ends with a blank line.
    - Returns a dictionary.
    """
    meta = {}
    lines = text_minutes.split('\n')
    if lines[0] == '---':
        lines.pop(0)
    for line in lines:
        if line.strip() in ['', '---']:
            break
        meta_key, meta_value = line.split(':', 1)
        meta[meta_key.strip().lower()] = meta_value.strip()
    return meta


def RelsRiskAdj(t):
    """Release of Risk Adjustment to Revenue

    Warning:
        To be implemented.
    """
    return 0


def envmap_clear_all():
    """Discard all environment maps in the .blend file and free them from memory

    """
    pass


def __sub_class_rename__(tab):
    """
    Changes the sub-class identification of SDSS DR12 in such a way, that for stars only the main identification
    (Kx, Fy, ...) is left. WD's are also only one sub-class and it won't be distingushed between
    hot and cool ones.
    The identification of galaxies and QSO's is untouched.

    :param tab: The input table with the data from the SDSS DR12
    :type tab: numpy.ndarray, astropy.table.Table
    :return: The input data with the changed sub-class identification
    :rtype: numpy.ndarray, astropy.table.Table
    """
    for i, t in enumerate(tab):
        sub_cl = t['subCl'].split(' ')
        if len(sub_cl) > 1:
            tab['subCl'][i] = sub_cl[0]
        sub_cl = sub_cl[0]
        if (len(sub_cl) == 3 or len(sub_cl) == 4) and sub_cl[-1] != 'N':
            if 'sd' in sub_cl:
                sub_cl = sub_cl[2:]
            else:
                sub_cl = sub_cl[:2]
            tab['subCl'][i] = sub_cl
        elif '/' in sub_cl:
            if 'Ib' in sub_cl:
                sub_cl = sub_cl.split('Ib')[0]
            else:
                sub_cl = sub_cl.split('/')[0]
            tab['subCl'][i] = sub_cl
        elif 'WD' in sub_cl:
            tab['subCl'][i] = 'WD'
        elif 'III' in sub_cl:
            sub_cl = sub_cl[:2]
            tab['subCl'][i] = sub_cl
        elif ':' in sub_cl:
            sub_cl = sub_cl.split(':')[-1]
            tab['subCl'][i] = sub_cl
        elif '.' in sub_cl:
            if 'Ib' in sub_cl:
                sub_cl = sub_cl.split('Ib')[0]
            elif 'V.' in sub_cl:
                sub_cl = sub_cl.split('V.')[0]
            sub_cl = sub_cl.split('.')[0]
            tab['subCl'][i] = sub_cl
        elif 'lb' in sub_cl:
            sub_cl = sub_cl.split('lb')[0]
            tab['subCl'][i] = sub_cl
        elif 'Ib' in sub_cl:
            sub_cl = sub_cl.split('Ib')[0]
            tab['subCl'][i] = sub_cl
        elif 'IV' in sub_cl:
            sub_cl = sub_cl.split('IV')[0]
            tab['subCl'][i] = sub_cl
        elif 'Ia' in sub_cl:
            sub_cl = sub_cl.split('Ia')[0]
            tab['subCl'][i] = sub_cl
        elif 'Vn' in sub_cl:
            sub_cl = sub_cl.split('Vn')[0]
            tab['subCl'][i] = sub_cl
    tab = tab[tab['subCl'] != '']
    return tab


def lint_citations(tool_xml, lint_ctx):
    """Ensure tool contains at least one valid citation."""
    root = tool_xml.getroot()
    citations = root.findall('citations')
    if len(citations) > 1:
        lint_ctx.error(
            'More than one citation section found, behavior undefined.')
        return
    if len(citations) == 0:
        lint_ctx.warn(
            'No citations found, consider adding citations to your tool.')
        return
    valid_citations = 0
    for citation in citations[0]:
        if citation.tag != 'citation':
            lint_ctx.warn(
                'Unknown tag discovered in citations block [%s], will be ignored.'
                 % citation.tag)
            continue
        citation_type = citation.attrib.get('type')
        if citation_type not in ('bibtex', 'doi'):
            lint_ctx.warn(
                'Unknown citation type discovered [%s], will be ignored.',
                citation_type)
            continue
        if citation.text is None or not citation.text.strip():
            lint_ctx.error('Empty %s citation.' % citation_type)
            continue
        valid_citations += 1
    if valid_citations > 0:
        lint_ctx.valid('Found %d likely valid citations.', valid_citations)


@classmethod
def has_fitbit_authorization(cls, request, ppm_id):
    """
        Make a request to P2MD to determine if a participant has authorized Fitbit.
        """
    response = cls.head(request, f'/sources/api/fitbit/{ppm_id}', raw=True)
    return response.ok


def get_exception_message(ex):
    """Build exception message with details.
    """
    template = '{0}: {1!r}'
    return template.format(type(ex).__name__, ex.args)


def retransmit_timeout(group_state: 'GroupState'):
    """
    retransmit timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'Querier MembersPresent: retransmit_timeout')
    return


def print_text(tasks):
    """Print the __repr__ of all tasks in the list."""
    for task in tasks:
        print(task)


def sort_domains(domains):
    """Sort domains in a canonical ordering."""
    return tuple(sorted(domains, key=lambda domain: domain._ufl_sort_key_()))


@staticmethod
def should(vm):
    """
        Return True if branching should occur, based on the virtual machine's state.
        """
    raise NotImplementedError


def get_fiber_markers(mesh_type='lv'):
    """
    Get the markers for the mesh.
    This is the default markers for fiberrules.

    :param str mesh_type: type of mesh, 'lv' or 'biv'
    :returns: The markers
    :rtype: dict

    """
    if mesh_type == 'lv':
        return {'BASE': 10, 'ENDO': 30, 'EPI': 40, 'WALL': 50, 'ENDORING':
            300, 'EPIRING': 400, 'WALL': 50}
    elif mesh_type == 'biv':
        return {'BASE': 10, 'ENDO_RV': 20, 'ENDO_LV': 30, 'EPI': 40,
            'ENDORING_RV': 200, 'ENDORING_LV': 300, 'EPIRING': 400, 'WALL': 50}


def escape_filename_sh_ansic(name):
    """Return an ansi-c shell-escaped version of a filename."""
    out = []
    for ch in name:
        if ord(ch) < 32:
            out.append('\\x%02x' % ord(ch))
        elif ch == '\\':
            out.append('\\\\')
        else:
            out.append(ch)
    return "$'" + ''.join(out) + "'"


def scan_deployed_policies(org_client):
    """
    Return list of Service Control Policies deployed in Organization
    """
    return org_client.list_policies(Filter='SERVICE_CONTROL_POLICY')['Policies'
        ]


@classmethod
def get_capabilities(cls):
    """Return an dictionary with the capabilities of each driver."""
    return cls.CAPABILITIES


def max_dist_sqrd(center, size):
    """
    Calculate the squared distnace to the furthest corner of a rectangle.

    Assumes that the origin is ``(0, 0)``.

    Does not take the square of the distance for the sake of speed.

    If the rectangle's center is in the Q1, then the upper-right corner is
    the farthest away from the origin. If in Q2, then the upper-left corner
    is farthest away. Etc.

    Returns the magnitude of the largest distance.

    Used primarily for calculating if a die has any part outside of wafer's
    edge exclusion.

    Parameters
    ----------
    center : tuple of length 2, numerics
        (x, y) tuple defining the rectangle's center coordinates

    size : tuple of length 2
        (x, y) tuple that defines the size of the rectangle.

    Returns
    -------
    dist : numeric
        The distance from the origin (0, 0) to the farthest corner of the
        rectangle.

    See Also
    --------
    max_dist :
        Calculates the distance from the orgin (0, 0) to the
        farthest corner of a rectangle.
    """
    half_x = size[0] / 2.0
    half_y = size[1] / 2.0
    if center[0] < 0:
        half_x = -half_x
    if center[1] < 0:
        half_y = -half_y
    dist = (center[0] + half_x) ** 2 + (center[1] + half_y) ** 2
    return dist


def plot_confusion_matrix(cm, classes, normalize=False, title=
    'Confusion matrix', cmap=None, save_as=None):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    import itertools
    import matplotlib.pyplot as plt
    import numpy as np
    plt.figure()
    if cmap is None:
        cmap = plt.cm.Blues
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, (np.newaxis)]
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.0
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt), horizontalalignment='center',
            color='white' if cm[i, j] > thresh else 'black')
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
    if save_as is not None:
        plt.savefig(save_as, bbox_inches='tight')
    plt.show()
    plt.clf()


@classmethod
def from_pygments_lexer_cls(cls, lexer_cls):
    """
        Create a :class:`.RegexSync` instance for this Pygments lexer class.
        """
    patterns = {'Python': '^\\s*(class|def)\\s+', 'Python 3':
        '^\\s*(class|def)\\s+', 'HTML': '<[/a-zA-Z]', 'JavaScript':
        '\\bfunction\\b'}
    p = patterns.get(lexer_cls.name, '^')
    return cls(p)


def bytes_to_text(s, encoding):
    """
    Convert bytes objects to strings, using the given encoding. Illegally
    encoded input characters are replaced with Unicode "unknown" codepoint
    (�).

    Return any non-bytes objects without change.
    """
    if isinstance(s, bytes):
        return str(s, encoding, 'replace')
    else:
        return s


@classmethod
def get_context_data(cls, obj, request=None):
    """
        Returns additional information to be used in the template

        To fetch this data in the template, you must first add it to your request's context

        e.g. `context[admin_order_section.identifier] =
                admin_order_section.get_context_data(self.object)`

        :type object: e.g. shuup.core.models.Order
        :type request: HttpRequest
        :return additional context data
        :rtype: object|None
        """
    return None


def process_edited_message(bot, chains, update):
    """Process an edited message"""
    for hook in chains['messages_edited']:
        bot.logger.debug(
            'Processing edited message in update #%s with the hook %s...' %
            (update.update_id, hook.name))
        result = hook.call(bot, update)
        if result is True:
            bot.logger.debug('Update %s was just processed by the %s hook.' %
                (update.update_id, hook.name))
            return
    bot.logger.debug('No hook actually processed the #%s update.' % update.
        update_id)


def timestamp_init(monitor_params):
    """
    Initializes the psana Detector interface for timestamp data at LCLS.

    Arguments:

        monitor_params (:class:`~onda.utils.parameters.MonitorParams`): an object
            storing the OnDA monitor parameters from the configuration file.
    """
    del monitor_params
    return None


def keplermag_to_keplerflux(keplermag, f12=174000.0):
    """This converts the Kepler mag back to Kepler flux.

    Parameters
    ----------

    keplermag : float or array-like
        The Kepler magnitude value(s) to convert to fluxes.

    f12 : float
        The flux value in the Kepler band corresponding to Kepler mag = 12.0.

    Returns
    -------

    np.array
        Fluxes in the Kepler band corresponding to the input `keplermag`
        magnitude value(s).

    """
    kepflux = 10.0 ** (-0.4 * (keplermag - 12.0)) * f12
    return kepflux


@classmethod
def string_list_file(cls, filename, values):
    """
        Write a list of strings to a file.
        If a file of the same name exists, it's contents are replaced.

        See L{HexInput.string_list_file} for a description of the file format.

        @type  filename: str
        @param filename: Name of the file to write.

        @type  values: list( int )
        @param values: List of strings to write to the file.
        """
    fd = open(filename, 'w')
    for string in values:
        print >> fd, string
    fd.close()


@classmethod
def by_range(cls, *args, **kws):
    """
        Constructor given a interval
        """
    return cls(*args, **kws)


@staticmethod
def _cache_eject_callback(key, entity):
    """A callback for when entities are ejected from a cache.

        When an entity is dumped from all of it's caches, there's a chance
        it could fall out of scope before every being saved, so we save it
        on ejection to be sure.

        :param key: The ejected entity's cache key
        :param Entity entity: The ejected entity
        :return None:

        """
    entity.save()


@classmethod
def __getDataSources(cls, node, direct=False):
    """ provides datasources and its records from xml string

        :param xmlc: xml string
        :type xmlc: :obj:`str`
        :returns: list of datasource descriptions
        :rtype: :obj:`list` <:obj:`dict` <:obj:`str`, :obj:`str`>>
        """
    dss = []
    if direct:
        dss.extend(node.findall('datasource'))
    else:
        if node.tag == 'datasource':
            dss.append(node)
        dss.extend(node.findall('.//datasource'))
    dslist = []
    for ds in dss:
        if ds.tag == 'datasource':
            dstype = ds.attrib['type']
            dsname = ds.attrib['name']
            record = cls.getRecord(ds)
            dslist.append({'source_type': dstype, 'source_name': dsname,
                'source': record})
    return dslist


def _convert_state(key: str, data: dict) ->dict:
    """Make state data more usable"""
    mod, id, name, fun = key.split('_|-')
    state = {'module': mod, 'id': id, 'function': fun, 'name': name,
        'success': data['result'], 'changed': bool(data['changes']), 'sls':
        data.get('__sls__'), 'changes': data['changes'], 'duration': data.
        get('duration', 0), 'start_time': data.get('start_time'), 'comment':
        data.get('comment', ''), 'order': data['__run_num__'], 'jid': data.
        get('__jid__')}
    if not state['success']:
        if state['comment'].startswith('One or more requisite failed:'):
            state['status'] = 'requisite-failed'
        else:
            state['status'] = 'failed'
    elif state['changed']:
        state['status'] = 'changed'
    else:
        state['status'] = 'unchanged'
    return state


def build_key_hierarchy(key):
    """Build a list with key in it and all of it's parent keys.

    :param key: (str) A dotted path.
    :returns [str]: A list of keys.
    """
    all_keys = [key]
    try:
        while True:
            key = key[:key.rindex('.')]
            all_keys.append(key)
    except ValueError:
        pass
    return all_keys


def end_group(xml):
    """End of a fieldgroup
        """


def is_twotuple(L, type1, type2):
    """
    Checks whether the object L is a 2-element tuple throughout.
    """
    if isinstance(L, (list, tuple)):
        for i, x in enumerate(L):
            if isinstance(x, tuple):
                if len(x) != 2:
                    raise ValueError(
                        "'L' element at index [{}] is not of size 2".format(i))
                if not isinstance(x[0], type1):
                    raise TypeError(
                        "x[0] element at index [{}] is not of type '{}'".
                        format(i, type1))
                if not isinstance(x[1], type2):
                    raise TypeError(
                        "x[1] element at index [{}] is not of type '{}'".
                        format(i, type2))
            else:
                raise TypeError("'x' is not of type 'tuple'")
        return True
    else:
        raise TypeError("'L' must be of type 'list, tuple'")


def Mach(V, c):
    """Calculates Mach number or `Ma` for a fluid of velocity `V` with speed
    of sound `c`.

    .. math::
        Ma = \\frac{V}{c}

    Parameters
    ----------
    V : float
        Velocity of fluid, [m/s]
    c : float
        Speed of sound in fluid, [m/s]

    Returns
    -------
    Ma : float
        Mach number []

    Notes
    -----
    Used in compressible flow calculations.

    .. math::
        Ma = \\frac{\\text{fluid velocity}}{\\text{sonic velocity}}

    Examples
    --------
    >>> Mach(33., 330)
    0.1

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    return V / c


def removemount(absolutepath):
    """ Remove the '/' on unix and (TODO) 'C:' on Windows """
    return absolutepath[1:]


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 formatUnits(units):
    """
    Format a unit specification ([numerators,...], [denominators,...])
    into a string (this is the inverse of evalUnits)
    """
    pass


def _return_interrogation_script_json(package, filename=None):
    """Return script to interrogate deps for package inside env.
    Uses json.dump instead of pickle due to cryptic pickle/requests bug."""
    head = (
        '\nimport pip\nimport json\npkgs  = pip.get_installed_distributions()\n'
        )
    mid = "package = '{0}'".format(package.lower())
    if not filename:
        out = (
            'fn = "{0}_{1}_req.dat".format(p.key, p.version.replace(".","_"))')
    else:
        out = 'fn = "{0}"'.format(filename)
    conv = """
p = [x for x in pkgs if x.key == package][0]

req_dic = {'project_name': p.project_name,
               'version': p.version, 'requires': {}}

for r in p.requires():
    req_dic['requires'][r.key] = {}
    req_dic['requires'][r.key]['project_name'] = r.project_name
    req_dic['requires'][r.key]['key'] = r.key
    req_dic['requires'][r.key]['specs'] = r.specs

"""
    end = "json.dump(req_dic, open(fn, 'wb'))"
    nl = '\n'
    return head + nl + mid + nl + conv + nl + out + nl + end + nl


def _get_decorator_names(fun):
    """Get decorator names from the function.

    Args:
        fun: The function whose decorators we are getting.

    Returns:
        The names of the decorators. Does not include setters and
        getters.

    """
    ret = list()
    for decorator in fun.decorator_list:
        if hasattr(decorator, 'id'):
            ret.append(getattr(decorator, 'id'))
    return ret


def badtype_error(attribute, allowedtypes):
    """ Wrong type of argument passed. Provide attribute and allowed types"""
    return TypeError(
        'Received attribute "%s" of type %s; however, allowed types are %s' %
        (attribute, type(attribute), allowedtypes))


def imax(iterable):
    """return index of max value from iterable."""
    return max(range(len(iterable)), key=iterable.__getitem__)


@staticmethod
def _ask(question, type_func=int):
    """
        Helper to gather answers and convert them with the type_func.

        Parameters
        ----------
        question: str
        type_func: function

        """
    while True:
        raw_input = None
        try:
            raw_input = input(f'{question}:').strip()
            value = type_func(raw_input)
            break
        except ValueError:
            print(
                f'Please try again - {raw_input} is not a valid {type_func.__name__}'
                )
    return value


def addListing(parser):
    """
    Add option to request the list of versions.
    """
    parser.add_option('-l', '--list', action='store_true', help=
        'list the available versions of the requested project and exit')
    parser.add_option('--list-versions', action='store_true', dest='list',
        help='obsolete spelling of --list', default=False)
    parser.add_option('-L', '--list-platforms', action='store_true', help=
        'list the available platforms for the requested project/version and exit'
        )
    parser.set_defaults(list=False, list_platforms=False)
    return parser


def LoadControls(Slines, data):
    """Read values from a .imctrl (Image Controls) file"""
    cntlList = ['color', 'wavelength', 'distance', 'tilt', 'invert_x',
        'invert_y', 'type', 'Oblique', 'fullIntegrate', 'outChannels',
        'outAzimuths', 'LRazimuth', 'IOtth', 'azmthOff', 'DetDepth',
        'calibskip', 'pixLimit', 'cutoff', 'calibdmin', 'Flat Bkg',
        'varyList', 'setdist', 'PolaVal', 'SampleAbs', 'dark image',
        'background image', 'twoth']
    save = {}
    for S in Slines:
        if S[0] == '#':
            continue
        [key, val] = S.strip().split(':', 1)
        if key in ['type', 'calibrant', 'binType', 'SampleShape', 'color']:
            save[key] = val
        elif key in ['varyList']:
            save[key] = eval(val)
        elif key in ['rotation']:
            save[key] = float(val)
        elif key in ['center']:
            if ',' in val:
                save[key] = eval(val)
            else:
                vals = val.strip('[] ').split()
                save[key] = [float(vals[0]), float(vals[1])]
        elif key in cntlList:
            save[key] = eval(val)
    data.update(save)


def apply_cyclic(value, bounds):
    """Given a value, applies cyclic boundary conditions between the minimum
    and maximum bounds.

    Parameters
    ----------
    value : float
        The value to apply the cyclic conditions to.
    bounds : Bounds instance
        Boundaries to use for applying cyclic conditions.

    Returns
    -------
    float
        The value after the cyclic bounds are applied.
    """
    return (value - bounds._min) % (bounds._max - bounds._min) + bounds._min


@classmethod
def update_default_handler_map(cls, handler_map):
    """
        A class method to update the default handler map.
        """
    cls._default_handler_map.update(handler_map)


def lookup(key):
    """Resolve a value to a known revision.

        Returns a binary node of the resolved revision on success.
        """


def get_arraytype():
    """pygame.sndarray.get_arraytype (): return str

    DEPRECATED - only numpy arrays are now supported.
    """
    return 'numpy'


def __getstate__():
    """Get the object data.

        The state should not include persistent attributes ("_p_name").
        The result must be picklable.
        """


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 getId(collection):
    """ Get the ImageCollection id.

    **CLIENT SIDE**

    :type collection: ee.ImageCollection
    :return: the collection's id
    :rtype: str
    """
    return collection.limit(0).getInfo()['id']


def _rect_to_css(rect):
    """
    Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order

    :param rect: a dlib 'rect' object
    :return: a plain tuple representation of the rect in (top, right, bottom, left) order
    """
    return rect.top(), rect.right(), rect.bottom(), rect.left()


def get_method_attr(method, cls, attr_name, default=False):
    """Look up an attribute on a method/ function.
    If the attribute isn't found there, looking it up in the
    method's class, if any.
    """
    Missing = object()
    value = getattr(method, attr_name, Missing)
    if value is Missing and cls is not None:
        value = getattr(cls, attr_name, Missing)
    if value is Missing:
        return default
    return value


def _img_fname(img_url: str) ->str:
    """Return image file name including the extension given its url."""
    return img_url.split('/')[-1]


@classmethod
def find_one(cls, **kwargs):
    """Query this table for a single row matching kwargs filters."""
    return cls.query.filter_by(**kwargs).one()


@classmethod
def true_phase(cls, phase=None, phase_shift=None):
    """
        returns shifted phase of the orbit by the amount phase_shift

        :param phase: numpy.array
        :param phase_shift: numpy.float
        :return:
        """
    return phase + phase_shift


def calc_max_len(ser):
    """
    @doc: find the maximum length of a pandas Series of strings (for schema inference)
    @args: ser is a pandas Series of type 'O'
    @return: the maximum length of a string in ser
    """
    retser = ser.apply(lambda x: len(str(x)))
    ret = retser.max()
    return ret


def frame_jump():
    """Place the cursor on the midpoint of selected keyframes

    """
    pass


def get_pci_address_fields(pci_addr):
    """Parse a fully-specified PCI device address.

    Does not validate that the components are valid hex or wildcard values.

    :param pci_addr: A string of the form "<domain>:<bus>:<slot>.<function>".
    :return: A 4-tuple of strings ("<domain>", "<bus>", "<slot>", "<function>")
    """
    dbs, sep, func = pci_addr.partition('.')
    domain, bus, slot = dbs.split(':')
    return domain, bus, slot, func


@staticmethod
def _op_Iop_MAddF64(args):
    """
        Ternary operation.
            arg0 == 0
            return arg1 * arg2 + arg3

        :param args:    Arguments to this operation.
        :return:        The operation result.
        """
    return args[1] * args[2] + args[3]


@classmethod
def set_signature(cls, data, signature):
    """
        Set the clearsigned signature
        """
    doc_id = data['id']
    cls.write([cls(doc_id)], {'digital_signature': signature})


def validate_input(predictions, records, line_ids=None):
    """Validate the input features
    """
    for k in predictions:
        if predictions[k].shape[0] != len(records):
            raise Exception(
                'number of records does not match number the prediction rows for prediction %s.'
                 % str(k))
    if line_ids is not None:
        if line_ids.shape[0] != len(records):
            raise Exception(
                'number of line_ids does not match number of VCF records')


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


def _privateAttrMap(obj, ret=0):
    """clone obj._attrMap if required"""
    A = obj._attrMap
    oA = getattr(obj.__class__, '_attrMap', None)
    if ret:
        if oA is A:
            return A.clone(), oA
        else:
            return A, None
    elif oA is A:
        obj._attrMap = A.clone()


def get_wolfram_query_url(query):
    """Get Wolfram query URL."""
    base_url = 'www.wolframalpha.com'
    if not query:
        return 'http://{0}'.format(base_url)
    return 'http://{0}/input/?i={1}'.format(base_url, query)


def _calc_tstart(num_bins, binsize, t_stop):
    """
    Calculates the start point from given parameters.

    Calculates the start point `t_start` from the three parameters
    `num_bins`, `binsize`, `t_stop`.

    Parameters
    ----------
    num_bins : int
        Number of bins
    binsize : pq.Quantity
        Size of Bins
    t_stop : pq.Quantity
        Stop time

    Returns
    -------
    t_start : pq.Quantity
        Starting point calculated from given parameters.
    """
    if num_bins is not None and binsize is not None and t_stop is not None:
        return t_stop.rescale(binsize.units) - num_bins * binsize


def __init__(A):
    """TransactionStatus - a model defined in Swagger"""
    A.discriminator = None


def _get_datetime_cols(df):
    """
    Returns a list of column names of df for which the dtype starts with datetime
    """
    dtypes = df.dtypes
    return dtypes.loc[dtypes.apply(lambda x: str(x).startswith('datetime'))
        ].index.tolist()


def load_mean_distances(filein='dists.dat'):
    """Load and return mean distances of the reactant/intact-bond and
    product/broken-bond minima.

    Parameters
    ----------
    filein: str
        Name of the file created with method *save_mean_distances* of
        class *Dissociation2d*.

    Returns
    -------
    dists_i: list of floats
        Mean distances for reactant minimum.
    dists_b: list of floats
        Mean distances for the product minimum.
    forces: list of floats
        External forces.

    """
    dists_i = []
    dists_b = []
    forces = []
    fd = open(filein)
    first = True
    for line in fd:
        if first:
            first = False
            continue
        line_arr = line.rstrip().split()
        forces.append(float(line_arr[0]))
        dists_i.append(float(line_arr[1]))
        dists_b.append(float(line_arr[2]))
    fd.close()
    return dists_i, dists_b, forces


def reset(secondsFromNow):
    """
        Reset the scheduled call's timer.

        @param secondsFromNow: how many seconds from now it should fire,
            equivalent to C{.cancel()} and then doing another
            C{reactor.callLater(secondsLater, ...)}

        @raises twisted.internet.error.AlreadyCalled: if the call has already
            happened.
        @raises twisted.internet.error.AlreadyCancelled: if the call has already
            been cancelled.
        """


@staticmethod
def get_ip(instance):
    """Get instance IP."""
    return instance['public_net']['ipv4'].get('ip', '')


def supernova_pca_model(frequency_array, pc_coeff1, pc_coeff2, pc_coeff3,
    pc_coeff4, pc_coeff5, luminosity_distance, **kwargs):
    """ Supernova signal model """
    realPCs = kwargs['realPCs']
    imagPCs = kwargs['imagPCs']
    pc1 = realPCs[:, (0)] + 1.0j * imagPCs[:, (0)]
    pc2 = realPCs[:, (1)] + 1.0j * imagPCs[:, (1)]
    pc3 = realPCs[:, (2)] + 1.0j * imagPCs[:, (2)]
    pc4 = realPCs[:, (3)] + 1.0j * imagPCs[:, (3)]
    pc5 = realPCs[:, (4)] + 1.0j * imagPCs[:, (5)]
    scaling = 1e-23 * (10.0 / luminosity_distance)
    h_plus = scaling * (pc_coeff1 * pc1 + pc_coeff2 * pc2 + pc_coeff3 * pc3 +
        pc_coeff4 * pc4 + pc_coeff5 * pc5)
    h_cross = scaling * (pc_coeff1 * pc1 + pc_coeff2 * pc2 + pc_coeff3 *
        pc3 + pc_coeff4 * pc4 + pc_coeff5 * pc5)
    return {'plus': h_plus, 'cross': h_cross}


def write_identifier_section_simulate(init_dict, file_):
    """This function prints the information about the estimation results in the output
     file.
     """
    file_.write('\n\n {} \n\n'.format('Parameterization'))
    fmt_ = ' {:<10}' + '    {:>10}' + '{:>15}'
    file_.write(fmt_.format(*['Section', 'Identifier', 'Coef']) + '\n')
    num_treated = len(init_dict['TREATED']['order'])
    num_untreated = num_treated + len(init_dict['UNTREATED']['order'])
    num_choice = num_untreated + len(init_dict['CHOICE']['order'])
    identifier_treated = init_dict['TREATED']['order']
    identifier_untreated = init_dict['UNTREATED']['order']
    identifier_choice = init_dict['CHOICE']['order']
    identifier_distribution = ['sigma1', 'sigma10', 'sigma1v', 'sigma0',
        'sigma0v', 'sigmaV']
    identifier = (identifier_treated + identifier_untreated +
        identifier_choice + identifier_distribution)
    coeffs = init_dict['AUX']['init_values'].copy()
    fmt = '  {:>10}' + '   {:<15}' + ' {:>11.4f}'
    for i in range(len(init_dict['AUX']['init_values'])):
        if i == 0:
            file_.write('\n  {:<10} \n'.format('TREATED'))
        elif i == num_treated:
            file_.write('\n  {:<10} \n'.format('UNTREATED'))
        elif i == num_untreated:
            file_.write('\n  {:<10} \n'.format('CHOICE'))
        elif i == num_choice:
            file_.write('\n  {:<10} \n'.format('DIST'))
        file_.write('{0}\n'.format(fmt.format('', identifier[i], coeffs[i])))


def str(val):
    """Convert float to string, taking the locale into account."""
    return format('%.12g', val)


def int2uint64(value):
    """
    Convert a signed 64 bits integer into an unsigned 64 bits integer.

    >>> print(int2uint64(1))
    1
    >>> print(int2uint64(2**64 + 1))  # ignore bits larger than 64 bits
    1
    >>> print(int2uint64(-1))
    18446744073709551615
    >>> print(int2uint64(-2))
    18446744073709551614
    """
    return value & 18446744073709551615


def estimate_nmcmc(accept_ratio, old_act, maxmcmc, safety=5, tau=None):
    """ Estimate autocorrelation length of chain using acceptance fraction

    Using ACL = (2/acc) - 1 multiplied by a safety margin. Code adapated from
    CPNest:
        - https://github.com/johnveitch/cpnest/blob/master/cpnest/sampler.py
        - http://github.com/farr/Ensemble.jl

    Parameters
    ----------
    accept_ratio: float [0, 1]
        Ratio of the number of accepted points to the total number of points
    old_act: int
        The ACT of the last iteration
    maxmcmc: int
        The maximum length of the MCMC chain to use
    safety: int
        A safety factor applied in the calculation
    tau: int (optional)
        The ACT, if given, otherwise estimated.

    """
    if tau is None:
        tau = maxmcmc / safety
    if accept_ratio == 0.0:
        Nmcmc_exact = (1 + 1 / tau) * old_act
    else:
        Nmcmc_exact = (1.0 - 1.0 / tau) * old_act + safety / tau * (2.0 /
            accept_ratio - 1.0)
        Nmcmc_exact = float(min(Nmcmc_exact, maxmcmc))
    return max(safety, int(Nmcmc_exact))


def line_length(line, tab_width):
    """Calculate the length of a line taking TABs into account.

    :param str line: line of code
    :param int tab_width: tab width

    :returns: The length of the line
    :rtype: int

    """
    length = 0
    for i in line:
        if i == '\t':
            length = (length + tab_width) // tab_width * tab_width
        else:
            length += 1
    return length


def orifice_expansibility_1989(D, Do, P1, P2, k):
    """Calculates the expansibility factor for orifice plate calculations
    based on the geometry of the plate, measured pressures of the orifice, and
    the isentropic exponent of the fluid.

    .. math::
        \\epsilon = 1- (0.41 + 0.35\\beta^4)\\Delta P/\\kappa/P_1

    Parameters
    ----------
    D : float
        Upstream internal pipe diameter, [m]
    Do : float
        Diameter of orifice at flow conditions, [m]
    P1 : float
        Static pressure of fluid upstream of orifice at the cross-section of
        the pressure tap, [Pa]
    P2 : float
        Static pressure of fluid downstream of orifice at the cross-section of
        the pressure tap, [Pa]
    k : float
        Isentropic exponent of fluid, [-]

    Returns
    -------
    expansibility : float
        Expansibility factor (1 for incompressible fluids, less than 1 for
        real fluids), [-]

    Notes
    -----
    This formula was determined for the range of P2/P1 >= 0.75, and for fluids
    of air, steam, and natural gas. However, there is no objection to using
    it for other fluids.

    This is an older formula used to calculate expansibility factors for
    orifice plates.

    In this standard, an expansibility factor formula transformation in terms
    of the pressure after the orifice is presented as well. This is the more
    standard formulation in terms of the upstream conditions. The other formula
    is below for reference only:

    .. math::
        \\epsilon_2 = \\sqrt{1 + \\frac{\\Delta P}{P_2}} -  (0.41 + 0.35\\beta^4)
        \\frac{\\Delta P}{\\kappa P_2 \\sqrt{1 + \\frac{\\Delta P}{P_2}}}

    [2]_ recommends this formulation for wedge meters as well.

    Examples
    --------
    >>> orifice_expansibility_1989(D=0.0739, Do=0.0222, P1=1E5, P2=9.9E4, k=1.4)
    0.9970510687411718

    References
    ----------
    .. [1] American Society of Mechanical Engineers. MFC-3M-1989 Measurement
       Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2005.
    .. [2] Miller, Richard W. Flow Measurement Engineering Handbook. 3rd
       edition. New York: McGraw-Hill Education, 1996.
    """
    return 1.0 - (0.41 + 0.35 * (Do / D) ** 4) * (P1 - P2) / (k * P1)


def modify_instance_placement(InstanceId=None, Tenancy=None, Affinity=None,
    HostId=None):
    """
    Set the instance affinity value for a specific stopped instance and modify the instance tenancy setting.
    Instance affinity is disabled by default. When instance affinity is host and it is not associated with a specific Dedicated Host, the next time it is launched it will automatically be associated with the host it lands on. This relationship will persist if the instance is stopped/started, or rebooted.
    You can modify the host ID associated with a stopped instance. If a stopped instance has a new host ID association, the instance will target that host when restarted.
    You can modify the tenancy of a stopped instance with a tenancy of host or dedicated .
    Affinity, hostID, and tenancy are not required parameters, but at least one of them must be specified in the request. Affinity and tenancy can be modified in the same request, but tenancy can only be modified on instances that are stopped.
    See also: AWS API Documentation

    :example: response = client.modify_instance_placement(
        InstanceId='string',
        Tenancy='dedicated'|'host',
        Affinity='default'|'host',
        HostId='string'
    )

    :type InstanceId: string
    :param InstanceId: [REQUIRED]
            The ID of the instance that you are modifying.

    :type Tenancy: string
    :param Tenancy: The tenancy of the instance that you are modifying.

    :type Affinity: string
    :param Affinity: The new affinity setting for the instance.

    :type HostId: string
    :param HostId: The ID of the Dedicated Host that the instance will have affinity with.

    :rtype: dict
    :return: {
        'Return': True|False
    }

    """
    pass


def dash_case(name):
    """
    Convert a camel case string to dash case.

    Example:
        >>> dash_case('SomeName')
        'some-name'
    """
    letters = []
    for c in name:
        if c.isupper() and letters and letters[-1] != '-':
            letters.append('-' + c.lower())
        else:
            letters.append(c.lower())
    return ''.join(letters).replace('_', '-')


def make_comment(content: str) ->str:
    """Return a consistently formatted comment from the given `content` string.

    All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
    space between the hash sign and the content.

    If `content` didn't start with a hash sign, one is provided.
    """
    content = content.rstrip()
    if not content:
        return '#'
    if content[0] == '#':
        content = content[1:]
    if content and content[0] not in " !:#'%":
        content = ' ' + content
    return '#' + content


def _csr_filename(file_prefix):
    """
    Construct the name of a file for use in storing a certificate signing
    request.

    :param str file_prefix: base file name for the certificate signing request
        (without the extension)
    :return: certificate signing request file name
    :rtype: str
    """
    return file_prefix + '.csr'


@classmethod
def all_capabilities(cls):
    """
        Return a list of all possible capabilities.

        :rtype: list
        """
    return cls.ALL_CAPABILITIES


@staticmethod
def bg(value: int) ->str:
    """
        Returns the background escape code for a 256 color id.
        See https://jonasjacek.github.io/colors/ for full list.
        """
    return f'\x1b[48;5;{value}m'


def downsample_header(header, factor, axis):
    """
    Downsample a FITS header along an axis using the FITS convention for axis number
    """
    header = header.copy()
    cd = 'CDELT{0:d}'.format(axis)
    cp = 'CRPIX{0:d}'.format(axis)
    scalefactor = 1.0 / factor
    header[cp] = (header[cp] - 1) * scalefactor + scalefactor / 2.0 + 0.5
    header[cd] = header[cd] * factor
    return header


@classmethod
def _convert_to_stop(cls, stop_seq):
    """
        Convert ``stop_seq`` to a list of openpyxl v2 Color objects,
        suitable for initializing the ``GradientFill`` ``stop`` parameter.

        Parameters
        ----------
        stop_seq : iterable
            An iterable that yields objects suitable for consumption by
            ``_convert_to_color``.

        Returns
        -------
        stop : list of openpyxl.styles.Color
        """
    return map(cls._convert_to_color, stop_seq)


@classmethod
def _covariance(cls, Phi):
    """Returns the estimated covariance of a set of summaries, with the prefactor for a virtual signal field. See equations (13)-(14) in |Leclercqetal2019|_.

        Parameters
        ----------
        Phi : array, double, dimension=(N,P)
            a set of N simulations

        Returns
        -------
        Sigma^hat_theta' : array, double, dimension=(P,P)
            (N+1)/N * Sigma^hat_theta where Sigma^hat_theta is the unbiased covariance estimator

        """
    import numpy as np
    from ctypes import c_double
    N = Phi.shape[0]
    covariance_prefactor = (N + 1) / N
    return covariance_prefactor * np.cov(Phi.T, ddof=1).astype(c_double)


def acos(c):
    """acos -  Safe inverse cosine

       Input argument c is shrunk to admissible interval
       to avoid case where a small rounding error causes
       a math domain error.
    """
    from math import acos as _acos
    if c > 1:
        c = 1
    if c < -1:
        c = -1
    return _acos(c)


def truncate_float(number, precision, round=False):
    """ Truncate (shorten) a floating point value at given precision """
    precision = abs(precision)
    if round:
        short_float = round(number, precision)
        """short_float = float("{0:.{1}f}".format(number, precision))
        """
    else:
        operate_on = 1
        for _ in range(precision):
            operate_on *= 10
        short_float = float(int(number * operate_on)) / operate_on
    return short_float


def _clean_input(comma_string):
    """Clean comma separated option inputs in CLI"""
    return list(map(lambda term: term.strip(' '), comma_string.split(',')))


def getPortlets():
    """Return a list of IPortletAssignment's to be rendered.

        Returns a list of dicts with keys 'assignment', containing the actual
        assignment object; 'category', containing the category the
        assignment came from; 'key', being the key within this category; and
        'name' being the name of the assignment.
        """


@staticmethod
def _sort_labels(label_data):
    """Returns the labels in `label_data` sorted in descending order
        according to the 'size' (total token count) of their referent
        corpora.

        :param label_data: labels (with their token counts) to sort
        :type: `dict`
        :rtype: `list`

        """
    labels = list(label_data)
    labels.sort(key=label_data.get, reverse=True)
    return labels


@staticmethod
def get_data(index, role, column=None):
    """Get data of the given index

        If the column is is not None and different from
        the index column, will get the data from a sibling
        index with the same row.

        :param index: The index to query for data
        :type index: :class:`PySide.QtCore.QModelIndex`
        :param role: the data role
        :type role: :data:`PySide.QtCore.Qt.ItemDataRole`
        :param column: the column of the row to query for data.
        :type column: :class:`int` | None
        :returns: The data retrieved
        :raises: None
        """
    if column and index.column() != column:
        index = index.sibling(index.row(), column)
    if index.isValid():
        return index.data(role)


def add_global_colorbar(axes_colorbars, figure):
    """
    Add a global colorbar to a figure.

    Parameters
    ----------
    axes_colorbars : dict
    figure : syfigure.Figure
    """
    for ax_id, colorbars in axes_colorbars.items():
        for artist_type, artists in colorbars.items():
            if artists:
                for artist, colorbar_params in artists:
                    if colorbar_params.pop('show', 'False') == 'True':
                        figure.colorbar(artist, **colorbar_params)
                        break
                break
        break


def delete_compute_environment(computeEnvironment=None):
    """
    Deletes an AWS Batch compute environment.
    Before you can delete a compute environment, you must set its state to DISABLED with the  UpdateComputeEnvironment API operation and disassociate it from any job queues with the  UpdateJobQueue API operation.
    See also: AWS API Documentation

    Examples
    This example deletes the P2OnDemand compute environment.
    Expected Output:

    :example: response = client.delete_compute_environment(
        computeEnvironment='string'
    )

    :type computeEnvironment: string
    :param computeEnvironment: [REQUIRED]
            The name or Amazon Resource Name (ARN) of the compute environment to delete.

    :rtype: dict
    :return: {}

    """
    pass


def circuit_launched(circuit):
    """A new circuit has been started."""


def _seek_delimiter(file, delimiter, blocksize=2 ** 16):
    """ Seek current file to next byte after a delimiter
        from https://github.com/dask/hdfs3/blob/master/hdfs3/utils.py#L11

        Parameters
        ----------
        file: a file
        delimiter: bytes
            a delimiter like b'
'
        blocksize: int
            number of bytes to read
        """
    last = b''
    while True:
        current = file.read(blocksize)
        if not current:
            return
        full = last + current
        try:
            i = full.index(delimiter)
            file.seek(file.tell() - (len(full) - i) + len(delimiter))
            return
        except ValueError:
            pass
        last = full[-len(delimiter):]


def get_note_flags(note):
    """
    get the note flags

    Returns a fixed length string:
      'X' - needs sync
      '*' - favorite
    """
    flags = ''
    flags += 'X' if float(note['modified']) > float(note['syncdate']) else ' '
    if 'favorite' in note:
        flags += '*' if note['favorite'] else ' '
    else:
        flags += '  '
    return flags


def check_array_indices(imin, imax, jmin, jmax, framedim=None):
    """
    Return 4 indices for array slice compatible with framedim

    Parameters
    imin, imax, jmin, jmax: 4 integers
                            mini. and maxi. indices in both directions
    framedim : iterable of 2 integers
               shape of the array to be sliced by means of the 4 indices

    Return
    imin, imax, jmin, jmax: 4 integers
                            mini. and maxi. indices in both directions

    .. todo:: merge with getindices2cropArray()
    """
    if framedim is None:
        print('framedim is empty in check_array_indices()')
        return
    imin = max(imin, 0)
    jmin = max(jmin, 0)
    imax = min(framedim[0], imax)
    jmax = min(framedim[1], jmax)
    return imin, imax, jmin, jmax


def _check_classifer_response_method(estimator, response_method):
    """Return prediction method from the response_method

    Parameters
    ----------
    estimator: object
        Classifier to check

    response_method: {'auto', 'predict_proba', 'decision_function'}
        Specifies whether to use :term:`predict_proba` or
        :term:`decision_function` as the target response. If set to 'auto',
        :term:`predict_proba` is tried first and if it does not exist
        :term:`decision_function` is tried next.

    Returns
    -------
    prediction_method: callable
        prediction method of estimator
    """
    if response_method not in ('predict_proba', 'decision_function', 'auto'):
        raise ValueError(
            "response_method must be 'predict_proba', 'decision_function' or 'auto'"
            )
    error_msg = 'response method {} is not defined in {}'
    if response_method != 'auto':
        prediction_method = getattr(estimator, response_method, None)
        if prediction_method is None:
            raise ValueError(error_msg.format(response_method, estimator.
                __class__.__name__))
    else:
        predict_proba = getattr(estimator, 'predict_proba', None)
        decision_function = getattr(estimator, 'decision_function', None)
        prediction_method = predict_proba or decision_function
        if prediction_method is None:
            raise ValueError(error_msg.format(
                'decision_function or predict_proba', estimator.__class__.
                __name__))
    return prediction_method


def button_down_pressed(controller):
    """
    Callback function that is triggered, when the down button was pressed

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Button Down pressed')


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        Ensure data.message is string, since it can be very large

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
            "properties": {
                "id" : {
                    "type" : "keyword"
                },
                "interval_months" : {
                    "type" : "long"
                },
                "origin" : {
                    "type" : "keyword"
                },
                "study_creation_date" : {
                    "type" : "date"
                },
                "total_files": {
                    "type": "long"
                },
                "licensed_files": {
                    "type": "long"
                },
                "copyrighted_files": {
                    "type": "long"
                }
            }
        }
        """
    return {'items': mapping}


def uniquify(value, seen_values):
    """ Adds value to seen_values set and ensures it is unique """
    id = 1
    new_value = value
    while new_value in seen_values:
        new_value = '%s%s' % (value, id)
        id += 1
    seen_values.add(new_value)
    return new_value


def set_engineering_mode(expert):
    """
    Switches between expert mode and user mode for `BaseInterface` features.

    Current features:
       - Autocomplete filtering

    Parameters
    ----------
    expert: bool
        Set to ``True`` to enable expert mode, or ``False`` to disable it.
        ``True`` is the starting value.
    """
    global engineering_mode
    engineering_mode = bool(expert)


def readfile(filename, encoding='windows-1251'):
    """
    Reading file and moving it into dictionary

    filename - existing file
    encoding - encoding of given file
    """
    out = dict()
    with open(filename, encoding=encoding) as settings_file:
        for line in settings_file:
            line = line.rstrip()
            if line[:1] != '#' and len(line) > 0:
                key, value = line.split('=', 1)
                out[key] = value.rstrip()
    return out


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


@classmethod
def is_buy_ump(cls):
    """
        返回裁判本身是否是买入拦截裁判，类方法
        :return: bool，是否是买入拦截裁判
        """
    return getattr(cls, '_ump_type_prefix') == 'buy_'


@classmethod
def as_client(cls, host, port):
    """Return an address to use as a server address."""
    return cls(host, port, isserver=False)


@classmethod
def from_full(cls, color, fg=True):
    """Creates a color from full name or color number"""
    self = cls(fg=fg)
    self._from_full(color)
    return self


@staticmethod
def parse_order(line, *line_parsers):
    """Given a text line and any number of Line implementations, return the first that matches
       or None if no lines match."""
    for parser in line_parsers:
        try:
            return parser.parse(line)
        except ValueError:
            continue


def remove(callback):
    """
        Add a listener. The arguments to the callback are determined by whomever calls notify()
        """


def build_fun(bld):
    """
	Build function that is used for running configuration tests with ``conf.check()``
	"""
    if bld.kw['compile_filename']:
        node = bld.srcnode.make_node(bld.kw['compile_filename'])
        node.write(bld.kw['code'])
    o = bld(features=bld.kw['features'], source=bld.kw['compile_filename'],
        target='testprog')
    for k, v in bld.kw.items():
        setattr(o, k, v)
    if not bld.kw.get('quiet'):
        bld.conf.to_log('==>\n%s\n<==' % bld.kw['code'])


@classmethod
def hash_iter(cls, iterable, **kwargs):
    """Return hash of data from iterable of bytes."""
    ctx = cls(**kwargs)
    for chunk in iterable:
        ctx.update(chunk)
    return ctx.finalize()


def smart_project(angle_limit: float=66.0, island_margin: float=0.0,
    user_area_weight: float=0.0, use_aspect: bool=True, stretch_to_bounds:
    bool=True):
    """This script projection unwraps the selected faces of a mesh (it operates on all selected mesh objects, and can be used to unwrap selected faces, or all faces)

    :param angle_limit: Angle Limit, Lower for more projection groups, higher for less distortion
    :type angle_limit: float
    :param island_margin: Island Margin, Margin to reduce bleed from adjacent islands
    :type island_margin: float
    :param user_area_weight: Area Weight, Weight projections vector by faces with larger areas
    :type user_area_weight: float
    :param use_aspect: Correct Aspect, Map UVs taking image aspect ratio into account
    :type use_aspect: bool
    :param stretch_to_bounds: Stretch to UV Bounds, Stretch the final output to texture bounds
    :type stretch_to_bounds: bool
    """
    pass


def create_storage_location():
    """
    Creates the Amazon S3 storage location for the account.
    This location is used to store user log files.
    See also: AWS API Documentation

    Examples
    The following operation creates a new environment for version v1 of a java application named my-app:
    Expected Output:

    :example: response = client.create_storage_location()

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

    """
    pass


def _const_compare_digest_backport(a, b):
    """
    Compare two digests of equal length in constant time.

    The digests must be of type str/bytes.
    Returns True if the digests match, and False otherwise.
    """
    result = abs(len(a) - len(b))
    for l, r in zip(bytearray(a), bytearray(b)):
        result |= l ^ r
    return result == 0


def keyframe_jump(next: bool=True):
    """Jump to previous/next keyframe

    :param next: Next Keyframe
    :type next: bool
    """
    pass


def psi_Cs_H_Cl_PK74(T, P):
    """c-c'-a: caesium hydrogen chloride [PK74]."""
    psi = -0.019
    valid = T == 298.15
    return psi, valid


def describe(df):
    """Print out data frame description attribute if available"""
    if hasattr(df, 'description'):
        print(df.description)
    else:
        print('No description attribute available')
        return df.describe()


def clip(x, lowest, highest):
    """Return x clipped to the range [lowest..highest]."""
    return max(lowest, min(x, highest))


@classmethod
def fromstate(cls, state):
    """Return Statistics object from state."""
    stats = cls()
    stats.set_state(state)
    return stats


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


def _parse_dat_header(header_raw):
    """
    Parse point spectroscopy header.

    Each key-value pair is separated by '	' characters. Values may be
    further delimited by more '	' characters.

    Returns
    -------
    dict
        Parsed point spectroscopy header.
    """
    header_entries = header_raw.split('\r\n')
    header_entries = header_entries[:-3]
    header_dict = dict()
    for entry in header_entries:
        if entry[-1] == '\t':
            entry = entry[:-1]
        if '\t' not in entry:
            entry += '\t'
        key, val = entry.split('\t')
        header_dict[key] = val
    return header_dict


def _insert_graphviz_configs(c):
    """Insert configurations for graphviz to the state.

    Graphviz is primarily used by automodapi to create dependency
    diagrams for Python.
    """
    c['graphviz_output_format'] = 'svg'
    c['graphviz_dot_args'] = ['-Nfontsize=10',
        '-Nfontname=Helvetica Neue, Helvetica, Arial, sans-serif',
        '-Efontsize=10',
        '-Efontname=Helvetica Neue, Helvetica, Arial, sans-serif',
        '-Gfontsize=10',
        '-Gfontname=Helvetica Neue, Helvetica, Arial, sans-serif']
    return c


def paste_splines():
    """Paste splines from clipboard

    """
    pass


def to36(q):
    """
    Converts an integer to base 36 (a useful scheme for human-sayable IDs).

        >>> to36(35)
        'z'
        >>> to36(119292)
        '2k1o'
        >>> int(to36(939387374), 36)
        939387374
        >>> to36(0)
        '0'
        >>> to36(-393)
        Traceback (most recent call last):
            ...
        ValueError: must supply a positive integer

    """
    if q < 0:
        raise ValueError('must supply a positive integer')
    letters = '0123456789abcdefghijklmnopqrstuvwxyz'
    converted = []
    while q != 0:
        q, r = divmod(q, 36)
        converted.insert(0, letters[r])
    return ''.join(converted) or '0'


def _get_ids_for_cameras(cameras):
    """Get list of camera IDs from cameras"""
    return list(map(lambda camera: camera.id, cameras))


def delete(mlist):
    """Tell the MTA that the mailing list was deleted."""


def _chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def inch_to_EMU(value):
    """1 inch = 914400 EMUs"""
    return int(value * 914400)


def continue_check(prompt):
    """
    This function will help to check if the input is either 'n', 'N', 'y', or 'Y'
    to make sure computer get the right value to continue.

    Otherwise the prompt will show up again untill you input a valid value or
    forced to quit the program.

    INPUT:
        prompt: [string] the text shown on the terminal explaining what task to be continued.

    OUTPUT:
        check_value: [string] either 'n', 'N', 'y' or 'Y'.

    Example:
        check_value = continue_check('Do you want to continue this procedure? [Y/n]: ')
    """
    check_value = input(prompt)
    while True:
        try:
            if check_value not in ['n', 'N', 'y', 'Y']:
                error_message = (
                    "[Invalid input] please type 'y' as yes, or 'n' as no. ")
                print(error_message)
                raise ValueError(error_message)
            else:
                return check_value
        except ValueError:
            check_value = input(prompt)
            continue


@classmethod
def by_name(cls, name):
    """Returns a SerializationFormat object by the format name.

        Parameters
        ----------
        name : str
            The name of the serialization format. E.g. 'csv' or 'feather'.

        Returns
        -------
        SerializationFormat
            An object representing the given serialization format.

        Example
        -------
        >>> SerializationFormat.by_name('csv')
        <pdutil.serial.SerializationFormat.csv>
        """
    return cls.__NAME_TO_OBJ__[name]


def isunauthenticated(f):
    """
    Checks to see if the function is marked as not requiring authentication
    with the @unauthenticated decorator. Returns True if decorator is
    set to True, False otherwise.
    """
    return getattr(f, 'unauthenticated', False)


def _mpv_coax_proptype(value, proptype=str):
    """Intelligently coax the given python value into something that can be understood as a proptype property."""
    if type(value) is bytes:
        return value
    elif type(value) is bool:
        return b'yes' if value else b'no'
    elif proptype in (str, int, float):
        return str(proptype(value)).encode('utf-8')
    else:
        raise TypeError('Cannot coax value of type {} into property type {}'
            .format(type(value), proptype))


def get_forced_elements(connection, model):
    """
    Returns the force include and force exclude ids of elements
    :param connection:
    :param model:

    :return:Included and excluded elements
    :rtype: dict(str,list)
    """
    c = connection
    try:
        mod_obj = getattr(c, c.normalize_model_name(model))
    except Exception:
        mod_obj = c.model(model)
    include_search_params = [('criteri_regulatori', '=', 'incloure')]
    include_ids = mod_obj.search(include_search_params, False, False, False,
        {'active_test': False})
    include_search_params = [('criteri_regulatori', '=', 'excloure')]
    exclude_ids = mod_obj.search(include_search_params, False, False, False,
        {'active_test': False})
    return {'include': include_ids, 'exclude': exclude_ids}


def ParserTOC(obj):
    """The NCX file parsing"""
    result = []
    nav_points = obj.content.getElementsByTagName('navPoint')
    for np in nav_points:
        order = np.getAttribute('playOrder')
        chapter = np.getElementsByTagName('navLabel').item(0
            ).getElementsByTagName('text').item(0).firstChild.nodeValue
        result.append({'order': order, 'chapter': chapter})
    return result


def _get_tables(con):
    """ Return a list of table in sqlite database """
    out = con.execute("SELECT name FROM sqlite_master WHERE type='table';")
    return set(out)


def _convert_tick_position(tick_position):
    """Convert the given tick positions to ones that can be used by Matplotlib.

    Caution: Dependence on whether the scale is linear or logarithmic.

    References:
        - https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_xticks.html
        - https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.set_yticks.html
    """
    return tick_position


def _batch_job_generator(ts, query, indices, batch_size):
    """
    A generator that yields the iteration, batch_size, subsequence
    and query for both single and multi processing.

    Parameters
    ----------
    ts : np.array
        The time series to compute similarity distances for.
    query : np.array
        The query to find matches for within the time series.
    indices : list(int)
        Indices to generate tasks for. It is primarily used for subsequence
        partitioning.
    batch_size : int
        The subsequence size.

    Returns
    -------
    A yielded job to compute.
    """
    for iteration, i in enumerate(indices):
        subsequence = ts[i:i + batch_size]
        yield iteration, batch_size, subsequence, query