def format_input_source(input_source_name, input_source_number):
    """Format input source for display in UI."""
    return f'{input_source_name} {input_source_number}'


@classmethod
def _set_warehouse_parent(cls, locations):
    """
        Set the parent of child location of warehouse if not set
        """
    to_update = set()
    to_save = []
    for location in locations:
        if location.type == 'warehouse':
            if not location.input_location.parent:
                to_update.add(location.input_location)
            if not location.output_location.parent:
                to_update.add(location.output_location)
            if not location.storage_location.parent:
                to_update.add(location.storage_location)
            if to_update:
                for child_location in to_update:
                    child_location.parent = location
                    to_save.append(child_location)
                to_update.clear()
    cls.save(to_save)


def _read_moonshot_or_pnl_csv(filepath_or_buffer):
    """
    Load a Moonshot backtest CSV or PNL CSV into a DataFrame.

    This is a light wrapper around pd.read_csv that handles setting index
    columns and casting to proper data types.

    Parameters
    ----------
    filepath_or_buffer : string or file-like, required
        path to CSV

    Returns
    -------
    DataFrame
        a multi-index (Field, Date[, Time]) DataFrame of backtest or PNL
        results, with sids or strategy codes as columns
    """
    try:
        import pandas as pd
        import numpy as np
    except ImportError:
        raise ImportError('pandas must be installed to use this function')
    results = pd.read_csv(filepath_or_buffer, parse_dates=['Date'])
    index_cols = ['Field', 'Date']
    if 'Time' in results.columns:
        index_cols.append('Time')
    results = results.set_index(index_cols)
    fields_in_results = results.index.get_level_values('Field').unique()
    float_fields = ['Return', 'Pnl', 'Signal', 'Weight', 'NetExposure',
        'PositionQuantity', 'PositionValue', 'NetLiquidation', 'Turnover',
        'Commission', 'CommissionAmount', 'Slippage', 'Benchmark',
        'AbsWeight', 'AbsExposure', 'TotalHoldings', 'Price']
    for field in float_fields:
        if field in fields_in_results:
            results.loc[[field]] = results.loc[[field]].astype(np.float64)
    return results


def mpl_get_cb_bound_below_plot(ax):
    """ Return the coordinates for a colorbar axes below the provided axes
    object. Take into account the changes of the axes due to aspect ratio
    settings.

    Important: Use only AFTER fig.subplots_adjust(...)

    """
    position = ax.get_position()
    figW, figH = ax.get_figure().get_size_inches()
    fig_aspect = figH / figW
    box_aspect = ax.get_data_ratio()
    pb = position.frozen()
    pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect).bounds
    ax_size = ax.get_position().bounds
    sizes = [ax_size[0], ax_size[1], pb1[2], 0.03]
    return sizes


def URLPath():
    """
        @return: A L{URLPath<twisted.python.urlpath.URLPath>} instance
            which identifies the URL for which this request is.
        """


@staticmethod
def evaluate(x, amplitude, x_0, alpha):
    """One dimensional power law model function"""
    xx = x / x_0
    return amplitude * xx ** -alpha


def add_timing_pattern(matrix, is_micro):
    """    Adds the (horizontal and vertical) timinig pattern to the provided `matrix`.

    ISO/IEC 18004:2015(E) -- 6.3.5 Timing pattern (page 17)

    :param matrix: Matrix to add the timing pattern into.
    :param bool is_micro: Indicates if the timing pattern for a Micro QR Code
        should be added.
    """
    bit = 1
    y, stop = (0, len(matrix)) if is_micro else (6, len(matrix) - 8)
    for x in range(8, stop):
        matrix[x][y] = bit
        matrix[y][x] = bit
        bit ^= 1


def escape(ident):
    """Escape identifier."""
    string = []
    length = len(ident)
    start_dash = length > 0 and ident[0] == '-'
    if length == 1 and start_dash:
        string.append('\\{}'.format(ident))
    else:
        for index, c in enumerate(ident):
            codepoint = ord(c)
            if codepoint == 0:
                string.append('�')
            elif 1 <= codepoint <= 31 or codepoint == 127:
                string.append('\\{:x} '.format(codepoint))
            elif (index == 0 or start_dash and index == 1
                ) and 48 <= codepoint <= 57:
                string.append('\\{:x} '.format(codepoint))
            elif codepoint in (45, 95
                ) or codepoint >= 128 or 48 <= codepoint <= 57 or 48 <= codepoint <= 57 or 65 <= codepoint <= 90 or 97 <= codepoint <= 122:
                string.append(c)
            else:
                string.append('\\{}'.format(c))
    return ''.join(string)


@classmethod
def JSON(cls):
    """Postgres JSON Type"""
    return cls(dict, 'JSON')


@staticmethod
def clearPolar(widget=None):
    """
        clearPolar clears and setups the canvas widget for drawing. it sets the labels,
        ticks and some other ui styles.

        :param      widget:    matplotlib canvas widget for drawing
        :return:    fig        figure in widget
        :return:    axes       axes in figure
        """
    if not widget:
        return None, None
    if not hasattr(widget, 'figure'):
        return None, None
    fig = widget.figure
    fig.clf()
    axes = fig.add_subplot(1, 1, 1, polar=True, facecolor='none')
    axes.grid(True, color='#404040')
    axes.set_title('Actual Mount Model', color='white', fontweight='bold',
        pad=15)
    axes.set_facecolor((32 / 256, 32 / 256, 32 / 256))
    axes.tick_params(axis='x', colors='#2090C0', labelsize=12)
    axes.tick_params(axis='y', colors='#2090C0', labelsize=12)
    axes.set_theta_zero_location('N')
    axes.set_theta_direction(-1)
    axes.set_yticks(range(0, 90, 10))
    yLabel = ['', '', '', '', '', '', '', '', '', '']
    axes.set_yticklabels(yLabel, color='#2090C0', fontweight='bold')
    axes.set_rlabel_position(45)
    return fig, axes


@staticmethod
def get_output_node_name():
    """Name of a special node that defines data produced by the pipeline.

        The node with this name might not be present in the pipeline."""
    return 'OUTPUT'


def normalize_bool_option(option_value):
    """
    Convert option value to Python's boolean.

    ``option_value`` is what all those internal option processing return,
    which may be a default value set for an option, or what user passed in.

    As switches, options with values can be used:

    .. code-block:: bash

       --foo=yes|no
       --foo=true|false
       --foo=1|0
       --foo=Y|N
       --foo=on|off

    With combination of ``store_true``/``store_false`` and a default value module developer
    sets for the option, simple form without value is evaluated as easily. With ``store_true``
    and ``False`` default, following option turn the feature `foo` on:

    .. code-block:: bash

       --enable-foo

    With ``store_false`` and ``True`` default, following simple option turn the feature `foo` off:

    .. code-block:: bash

       --disable-foo
    """
    if str(option_value).strip().lower() in ('yes', 'true', '1', 'y', 'on'):
        return True
    return False


def align_yaxis(ax1, v1, ax2, v2):
    """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
    _, y1 = ax1.transData.transform((0, v1))
    _, y2 = ax2.transData.transform((0, v2))
    if y2 > y1:
        ratio = y1 / y2
    else:
        ratio = y2 / y1
    inv = ax2.transData.inverted()
    _, dy = inv.transform((0, 0)) - inv.transform((0, y1 - y2))
    miny2, maxy2 = ax2.get_ylim()
    ax2.set_ylim((miny2 + dy) / ratio, (maxy2 + dy) / ratio)


@staticmethod
def compute_mro_class_method(some_object):
    """Compute the mro if we dispatch for classes."""
    if isinstance(some_object, type):
        return some_object.__mro__
    else:
        return (some_object,) + type(some_object).__mro__


def create_label(support, taxon, auxiliary_info):
    """Create label for Newick tree.

    Parameters
    ----------
    float
      Support value specified by label, or None
    str
      Taxon specified by label, or None
    str
      Auxiliary information, on None

    Returns
    -------
    str
      Valid newick label.
    """
    label = ''
    if support is not None and taxon:
        label = str(support) + ':' + taxon
    elif support is not None:
        label = str(support)
    elif taxon:
        label = taxon
    if auxiliary_info:
        label += '|' + auxiliary_info
    return label


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

        :param AccessLevel val:
        :rtype: FileMemberActionIndividualResult
        """
    return cls('success', val)


def unitary_test():
    """ Unitary test for parallel.py script.
    """


@staticmethod
def compute_ldap_message_size(data):
    """
        Compute LDAP Message size according to BER definite length rules
        Returns -1 if too few data to compute message length
        """
    if isinstance(data, str):
        data = bytearray(data)
    ret_value = -1
    if len(data) > 2:
        if data[1] <= 127:
            ret_value = data[1] + 2
        else:
            bytes_length = data[1] - 128
            if len(data) >= bytes_length + 2:
                value_length = 0
                cont = bytes_length
                for byte in data[2:2 + bytes_length]:
                    cont -= 1
                    value_length += byte * 256 ** cont
                ret_value = value_length + 2 + bytes_length
    return ret_value


def __mul__(L1, L2):
    """Take the dot product of two numeric lists.
        Not using Vector for this because it is limited to three dimensions.
        Lists must have the same number of elements."""
    return sum(map(lambda x, y: x * y, L1, L2))


def cable_type(nom_power, nom_voltage, avail_cables):
    """Determine suitable type of cable for given nominal power

    Based on maximum occurring current which is derived from nominal power
    (either peak load or max. generation capacity) a suitable cable type is
    chosen. Thus, no line overloading issues should occur.

    Parameters
    ----------
    nom_power : float
        Nominal power of generators or loads connected via a cable
    nom_voltage : float
        Nominal voltage in kV
    avail_cables : :pandas:`pandas.DataFrame<dataframe>`
        Available cable types including it's electrical parameters

    Returns
    -------
    :pandas:`pandas.DataFrame<dataframe>`
        Parameters of cable type
    """
    I_max_load = nom_power / (3 ** 0.5 * nom_voltage)
    suitable_cables = avail_cables[avail_cables['I_max_th'] > I_max_load]
    if not suitable_cables.empty:
        cable_type = suitable_cables.loc[(suitable_cables['I_max_th'].
            idxmin()), :]
    else:
        cable_type = avail_cables.loc[(avail_cables['I_max_th'].idxmax()), :]
    return cable_type


@classmethod
def supports_metadata(cls):
    """returns True if this audio type supports MetaData"""
    return True


def SizeBenefitAnn(t):
    """Annuity benefit per policy"""
    return 0


def delete_policy(policy):
    """
    Delete IAM policy.

    Args:
        policy (obj): boto3 IAM resource object
    """
    if policy.attachment_count > 0:
        for group in policy.attached_groups.all():
            policy.detach_group(GroupName=group.name)
        for user in policy.attached_users.all():
            policy.detach_user(UserName=user.name)
        for role in policy.attached_roles.all():
            policy.detach_role(RoleName=role.name)
    for version in policy.versions.all():
        if not version.is_default_version:
            version.delete()
    policy.delete()


@classmethod
def get_tag_type(cls, instance):
    """
        Return the tag_type used to render this plugin.
        """
    return instance.glossary.get('tag_type', getattr(cls, 'tag_type', ''))


def get_weekday_occurrence(day):
    """Calculate how often this weekday has already occurred in a given month.

    :type day: datetime.date
    :returns: weekday (0=Monday, ..., 6=Sunday), occurrence
    :rtype: tuple(int, int)
    """
    xthday = 1 + (day.day - 1) // 7
    return day.weekday(), xthday


def _days(d_t):
    """Get the days (floating point) from *d_t*.
    """
    return d_t.days + (d_t.seconds + d_t.microseconds / 1000000.0) / (24 *
        3600.0)


def _get_data(isotherm, data_name, current_branch, drange, **kwargs):
    """Get different data from an isotherm."""
    if data_name == 'pressure':
        data = isotherm.pressure(branch=current_branch, pressure_mode=
            kwargs['pressure_mode'], pressure_unit=kwargs['pressure_unit'],
            min_range=drange[0], max_range=drange[1], indexed=True)
    elif data_name == 'loading':
        data = isotherm.loading(branch=current_branch, loading_basis=kwargs
            ['loading_basis'], loading_unit=kwargs['loading_unit'],
            adsorbent_basis=kwargs['adsorbent_basis'], adsorbent_unit=
            kwargs['adsorbent_unit'], min_range=drange[0], max_range=drange
            [1], indexed=True)
    else:
        data = isotherm.other_data(data_name, branch=current_branch,
            min_range=drange[0], max_range=drange[1], indexed=True)
    return data


def get_shipping_label(jobIds=None, name=None, company=None, phoneNumber=
    None, country=None, stateOrProvince=None, city=None, postalCode=None,
    street1=None, street2=None, street3=None, APIVersion=None):
    """
    This operation generates a pre-paid UPS shipping label that you will use to ship your device to AWS for processing.
    See also: AWS API Documentation

    :example: response = client.get_shipping_label(
        jobIds=[
            'string',
        ],
        name='string',
        company='string',
        phoneNumber='string',
        country='string',
        stateOrProvince='string',
        city='string',
        postalCode='string',
        street1='string',
        street2='string',
        street3='string',
        APIVersion='string'
    )

    :type jobIds: list
    :param jobIds: [REQUIRED]
            (string) --

    :type name: string
    :param name: Specifies the name of the person responsible for shipping this package.

    :type company: string
    :param company: Specifies the name of the company that will ship this package.

    :type phoneNumber: string
    :param phoneNumber: Specifies the phone number of the person responsible for shipping this package.

    :type country: string
    :param country: Specifies the name of your country for the return address.

    :type stateOrProvince: string
    :param stateOrProvince: Specifies the name of your state or your province for the return address.

    :type city: string
    :param city: Specifies the name of your city for the return address.

    :type postalCode: string
    :param postalCode: Specifies the postal code for the return address.

    :type street1: string
    :param street1: Specifies the first part of the street address for the return address, for example 1234 Main Street.

    :type street2: string
    :param street2: Specifies the optional second part of the street address for the return address, for example Suite 100.

    :type street3: string
    :param street3: Specifies the optional third part of the street address for the return address, for example c/o Jane Doe.

    :type APIVersion: string
    :param APIVersion: Specifies the version of the client tool.

    :rtype: dict
    :return: {
        'ShippingLabelURL': 'string',
        'Warning': 'string'
    }

    :returns:
    (dict) --
    ShippingLabelURL (string) --
    Warning (string) --

    """
    pass


def get_short_hash(repo_path):
    """
    Get git short hash
    """
    return "git -C {repo_path} log --pretty=format:'%h' -n 1".format(repo_path
        =repo_path)


def combine_request_approved(access_requests):
    """Combine pending and approved requests for the same user.

       Emergency Access Service returns both requests and approved access.
       If a request is already approved we don't want to show the request, so
       we merge the requests by user."""
    current_access = {}
    for request in access_requests:
        req = current_access.get(request['user'], request)
        if not req.get('approved', False):
            req['approved'] = request.get('approved', False)
            req['expiry_time'] = request['expiry_time']
        if req.get('reason', '') == '':
            req['reason'] = request['reason']
        current_access[request['user']] = req
    return current_access


def print_solution(solution):
    """Prints a solution

    Arguments
    ---------
    solution : BaseSolution

    Example
    -------
    ::

        [8, 9, 10, 7]: 160
        [5, 6]: 131
        [3, 4, 2]: 154
        Total cost: 445

    """
    total_cost = 0
    for solution in solution.routes():
        cost = solution.length()
        total_cost = total_cost + cost
        print('{}: {}'.format(solution, cost))
    print('Total cost: {}'.format(total_cost))


def is_type(x, types, full=False):
    """
    Returns true if x is of type in types tuple
    :param x:
    :param types:
    :param full:
    :return:
    """
    types = types if isinstance(types, tuple) else (types,)
    ins = isinstance(x, types)
    sub = False
    try:
        sub = issubclass(x, types)
    except Exception:
        pass
    res = ins or sub
    return res if not full else (res, ins)


def set_optional_field(message_obj, field, dic, key):
    """
    Sets field in the protocol buffer object. If the object does not
    accept it or if the key is not in dic the error is ignored.

    Args:
        message_obj (proto): protocol buffer object
        field (str): the field to test for existence in message_obj
        dic (dict): the dictionary where to copy the value into
        key (str): the dictionary key to use

    """
    try:
        setattr(message_obj, field, dic[key])
    except KeyError:
        pass


def isstrallowed(s, form):
    """
    Checks is input string conforms to input regex (`form`).

    :param s: input string.
    :param form: eg. for hdf5: `"^[a-zA-Z_][a-zA-Z0-9_]*$"`
    """
    import re
    match = re.match(form, s)
    return match is not None


def write_out(out, triple, outfile):
    """
    Take the output from test_triple() and write it to file.
    """
    print(triple[0], '\t', triple[1], '\t', triple[2], '\t', sep='', end='',
        file=outfile)
    print(out['Zscore'], '\t', sep='', end='', file=outfile)
    print(out['Pvalue'], '\t', sep='', end='', file=outfile)
    print(out['Gamma'], '\t', sep='', end='', file=outfile)
    print(out['AAAA'], '\t', sep='', end='', file=outfile)
    print(out['AAAB'], '\t', sep='', end='', file=outfile)
    print(out['AABA'], '\t', sep='', end='', file=outfile)
    print(out['AABB'], '\t', sep='', end='', file=outfile)
    print(out['AABC'], '\t', sep='', end='', file=outfile)
    print(out['ABAA'], '\t', sep='', end='', file=outfile)
    print(out['ABAB'], '\t', sep='', end='', file=outfile)
    print(out['ABAC'], '\t', sep='', end='', file=outfile)
    print(out['ABBA'], '\t', sep='', end='', file=outfile)
    print(out['BAAA'], '\t', sep='', end='', file=outfile)
    print(out['ABBC'], '\t', sep='', end='', file=outfile)
    print(out['CABC'], '\t', sep='', end='', file=outfile)
    print(out['BACA'], '\t', sep='', end='', file=outfile)
    print(out['BCAA'], '\t', sep='', end='', file=outfile)
    print(out['ABCD'], '\n', sep='', end='', file=outfile)


def obj_make_list(context, list_obj, item_cls, db_list, **extra_args):
    """Construct an object list from a list of primitives.

    This calls item_cls._from_db_object() on each item of db_list, and
    adds the resulting object to list_obj.

    :param:context: Request context
    :param:list_obj: An ObjectListBase object
    :param:item_cls: The MasakariObject class of the objects within the list
    :param:db_list: The list of primitives to convert to objects
    :param:extra_args: Extra arguments to pass to _from_db_object()
    :returns: list_obj
    """
    list_obj.objects = []
    for db_item in db_list:
        item = item_cls._from_db_object(context, item_cls(), db_item, **
            extra_args)
        list_obj.objects.append(item)
    list_obj._context = context
    list_obj.obj_reset_changes()
    return list_obj


@staticmethod
def _iterate_by_losses(losses: {}, callback: callable) ->None:
    """
        Internal method for unify iteration by losses dict

        :param losses: dic of losses
        :param callback: callable, that call for every loss value and get params loss_name and loss_values: ``callback(name: str, values: np.ndarray)``
        """
    for m, v in losses.items():
        callback(m, v)


@classmethod
def exists(cls, session, tar_sum, filename):
    """ Retrieve the file that has:

        - a particular tarball md5sum
        - a particular filename
        """
    query = session.query(cls).filter(cls.tar_sum == tar_sum).filter(cls.
        filename == filename).order_by(cls.pkg_name, cls.tar_file, cls.filename
        )
    return query.first()


@classmethod
def validate(cls, value):
    """
        Validate the value and convert it to its native type, if
        necessary.
        """
    return value


def delete():
    """Erase selected strips from the sequencer

    """
    pass


def node_color_preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Node Color Preset

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


@staticmethod
def chunk_it(input_list, chunk_size=1.0):
    """ Chunk it method to slice a list into smaller chunks"""
    avg = len(input_list) / float(chunk_size)
    out = []
    last = 0.0
    while last < len(input_list):
        check_not_null = input_list[int(last):int(last + avg)]
        if check_not_null:
            out.append(check_not_null)
        last += avg
    return out


def save_version(sender, instance, **kwargs):
    """Whena post is saved, so is a version of it
    """
    from omblog.models import PostVersion
    v = PostVersion()
    v.instance = instance
    v.save()


def merge_record_extra(record, target, reserved):
    """
    Merges extra attributes from LogRecord object into target dictionary
    :param record: logging.LogRecord
    :param target: dict to update
    :param reserved: dict or list with reserved keys to skip
    """
    for key, value in record.__dict__.items():
        if key not in reserved:
            if not hasattr(key, 'startswith') or not key.startswith('_'):
                target[key] = value
    return target


@classmethod
def isproduct(cls):
    """Check if the DataType is the product of a Recipe"""
    return False


def compilable(text, mode='exec'):
    """Return True if a string can be compiled"""
    if not mode in ['eval', 'exec']:
        raise ValueError(f'"{mode}" is an invalid compile mode')
    try:
        compile(text, '', mode)
        return True
    except:
        pass
    return False


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

        :param DurationLogInfo val:
        :rtype: WebSessionsIdleLengthPolicy
        """
    return cls('defined', val)


def keyframe_delete_v3d():
    """Remove keyframes on current frame for selected objects and bones

    """
    pass


def writeDrizKeywords(hdr, imgnum, drizdict):
    """ Write basic drizzle-related keywords out to image header as a record
        of the processing performed to create the image

        The dictionary 'drizdict' will contain the keywords and values to be
        written out to the header.
    """
    _keyprefix = 'D%03d' % imgnum
    for key in drizdict:
        val = drizdict[key]['value']
        if val is None:
            val = ''
        comment = drizdict[key]['comment']
        if comment is None:
            comment = ''
        hdr[_keyprefix + key] = val, drizdict[key]['comment']


def get_volume_id_to_instance_id_map(volume_info):
    """Generate volume id to instance id map.  Unattached volumes will be ignored."""
    instance_id_to_volume_id_map = {}
    for volume_id in volume_info:
        volume = volume_info.get(volume_id)
        if volume.get('Attachments'):
            ec2_instance_id = volume.get('Attachments')[0].get('InstanceId')
            instance_id_to_volume_id_map[volume_id] = ec2_instance_id
    return instance_id_to_volume_id_map


def isint(x):
    """Test if value is an integer"""
    try:
        a = float(x)
        b = int(a)
    except ValueError:
        return False
    else:
        return a == b


def add_to_specified_database(item, database):
    """ add an item to a database"""
    database['items'][database['name'], item['code']] = item


def transform_apply(location: bool=True, rotation: bool=True, scale: bool=
    True, properties: bool=True):
    """Apply the object’s transformation to its data

    :param location: Location
    :type location: bool
    :param rotation: Rotation
    :type rotation: bool
    :param scale: Scale
    :type scale: bool
    :param properties: Apply Properties, Modify properties such as curve vertex radius, font size and bone envelope
    :type properties: bool
    """
    pass


def run_and_read_all(run_lambda, command):
    """Runs command using run_lambda; reads and returns entire output if rc is 0"""
    rc, out, _ = run_lambda(command)
    if rc != 0:
        return None
    return out


def sort(X):
    """
    Return sorted elements of :param:`X` and array of corresponding
    sorted indices.

    :param X: Target vector.
    :type X: :class:`scipy.sparse` of format csr, csc, coo, bsr, dok, lil,
    dia or :class:`numpy.matrix`
    """
    assert 1 in X.shape, 'X should be vector.'
    X = X.flatten().tolist()[0]
    return sorted(X), sorted(list(range(len(X))), key=X.__getitem__)


def isBytes(s):
    """Return True if s is a bytes type."""
    return isinstance(s, bytes)


def canonicClassString(x):
    """ the __class__ attribute changed from old-style to new-style classes... """
    if isinstance(x, object):
        return repr(x.__class__).split("'")[1]
    else:
        return repr(x.__class__)


def get(isamAppliance, kdb_id, cert_id, check_mode=False, force=False):
    """
    Retrieving a signer certificate from a certificate database
    """
    return isamAppliance.invoke_get(
        'Retrieving a signer certificate from a certificate database',
        '/isam/ssl_certificates/{0}/signer_cert/{1}'.format(kdb_id, cert_id))


@classmethod
def create_engine(cls, *args, **kwargs):
    """
        Return engine from :func:`sqlalchemy.create_engine`

        Parameters
        ----------
        *args : any
            Positional arguments to :func:`sqlalchemy.create_engine`.
        **kwargs : any
            Keyword arguments to :func:`sqlalchemy.create_engine`.

        See Also
        --------
        :func:`sqlalchemy.create_engine`

        Returns
        -------
        :class:`SQLAlchemy` engine

        """
    from sqlalchemy import create_engine
    return create_engine(*args, **kwargs)


def _desc_has_possible_number_data(desc):
    """Returns true if there is any possible number data set for a particular PhoneNumberDesc."""
    if desc is None:
        return False
    return len(desc.possible_length) != 1 or desc.possible_length[0] != -1


def unauthenticated(func):
    """Adds 'unauthenticated' attribute to decorated function.

    Usage:

    >>> @unauthenticated
    ... def mymethod(f):
    ...     pass
    """
    func.unauthenticated = True
    return func


@staticmethod
def op(value, comparable):
    """Return whether `value` contains `comparable`."""
    try:
        return comparable in value
    except (TypeError, ValueError):
        return False


def current_piv(power, voltage):
    """Usage: current_piv(power, voltage)"""
    return power / voltage


def lattice_to_spacegroup_number(lattice):
    """Return the spacegroup number corresponding to the lowest symmetry
    possible for a given Bravais lattice."""
    _lattice_to_spacegroup_number = {'aP': 1, 'mP': 3, 'mC': 5, 'oP': 16,
        'oC': 20, 'oF': 22, 'oI': 23, 'tP': 75, 'tI': 79, 'hP': 143, 'hR':
        146, 'cP': 195, 'cF': 196, 'cI': 197}
    if not lattice in _lattice_to_spacegroup_number.keys():
        raise RuntimeError('lattice %s unknown' % lattice)
    return _lattice_to_spacegroup_number[lattice]


@classmethod
def breakline(cls):
    """Creates breakline Chunk.

    Returns:
      A chunk (:obj:`budou.chunk.Chunk`)
    """
    chunk = cls(u'\n', cls._BREAK_POS)
    return chunk


def extend_knots(internal_knots, k):
    """
    Extend the knots sequence to add the external knots. This is done because
    :meth:`extract_coeffs_knots_from_splines` returns only the internal knots.
    Therefore they should be extended on both sides by **k** knots.

    :param internal_knots: [array] containing the internal knots
    :param k: [int] spline degree
    :return: [list] containing the extended knots
    """
    extended_knots = []
    for i in range(k):
        extended_knots.append(internal_knots[0])
    extended_knots += list(internal_knots)
    for i in range(k):
        extended_knots.append(internal_knots[-1])
    return extended_knots


@classmethod
def range(cls):
    """
        Returns for how many codes this Exception, matches with the eventual
        goal of matching an error to the most specific error class
        """
    range = 0
    codes_list = cls.codes_list()
    for c in codes_list:
        if isinstance(c, tuple):
            start, stop = c
            range += stop - start + 1
        else:
            range += 1
    if not range:
        range = 1000
    return range


def total_asset_turnover(revenue, average_total_assets):
    """Computes total asset turnover.

    @params
    -------
    revenue: revenue
    average_total_assets: average total assets in period

    returns
    -------
    Total asset turnover, int or float

    explanation
    -----------

    """
    return revenue / average_total_assets


@classmethod
def _append_text_validator(cls, append_text):
    """
        Validates the append text string.
        """


def parameters_ui(layout, params):
    """ Create the ui for the rig parameters.

    """
    r = layout.row()
    r.label(text='Primary rotation axis:')
    r.prop(params, 'palm_rotation_axis', text='')


def _p100(part, total, prec=1):
    """Return percentage as string.
    """
    r = float(total)
    if r:
        r = part * 100.0 / r
        return '%.*f%%' % (prec, r)
    return 'n/a'


def parse_qs(query):
    """
        parse a uri query string into a dict
    """
    pd = {}
    if '&' in query:
        for el in query.split('&'):
            nm, junk, vl = el.partition('=')
            pd.setdefault(nm, []).append(vl)
    return pd


def create_stage(restApiId=None, stageName=None, deploymentId=None,
    description=None, cacheClusterEnabled=None, cacheClusterSize=None,
    variables=None, documentationVersion=None):
    """
    Creates a new  Stage resource that references a pre-existing  Deployment for the API.
    See also: AWS API Documentation

    :example: response = client.create_stage(
        restApiId='string',
        stageName='string',
        deploymentId='string',
        description='string',
        cacheClusterEnabled=True|False,
        cacheClusterSize='0.5'|'1.6'|'6.1'|'13.5'|'28.4'|'58.2'|'118'|'237',
        variables={
            'string': 'string'
        },
        documentationVersion='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The identifier of the RestApi resource for the Stage resource to create.

    :type stageName: string
    :param stageName: [REQUIRED]
            The name for the Stage resource.

    :type deploymentId: string
    :param deploymentId: [REQUIRED]
            The identifier of the Deployment resource for the Stage resource.

    :type description: string
    :param description: The description of the Stage resource.

    :type cacheClusterEnabled: boolean
    :param cacheClusterEnabled: Whether cache clustering is enabled for the stage.

    :type cacheClusterSize: string
    :param cacheClusterSize: The stage's cache cluster size.

    :type variables: dict
    :param variables: A map that defines the stage variables for the new Stage resource. Variable names can have alphanumeric and underscore characters, and the values must match [A-Za-z0-9-._~:/?#=,]+ .
            (string) --
            (string) --

    :type documentationVersion: string
    :param documentationVersion: The version of the associated API documentation.

    :rtype: dict
    :return: {
        'deploymentId': 'string',
        'clientCertificateId': 'string',
        'stageName': 'string',
        'description': 'string',
        'cacheClusterEnabled': True|False,
        'cacheClusterSize': '0.5'|'1.6'|'6.1'|'13.5'|'28.4'|'58.2'|'118'|'237',
        'cacheClusterStatus': 'CREATE_IN_PROGRESS'|'AVAILABLE'|'DELETE_IN_PROGRESS'|'NOT_AVAILABLE'|'FLUSH_IN_PROGRESS',
        'methodSettings': {
            'string': {
                'metricsEnabled': True|False,
                'loggingLevel': 'string',
                'dataTraceEnabled': True|False,
                'throttlingBurstLimit': 123,
                'throttlingRateLimit': 123.0,
                'cachingEnabled': True|False,
                'cacheTtlInSeconds': 123,
                'cacheDataEncrypted': True|False,
                'requireAuthorizationForCacheControl': True|False,
                'unauthorizedCacheControlHeaderStrategy': 'FAIL_WITH_403'|'SUCCEED_WITH_RESPONSE_HEADER'|'SUCCEED_WITHOUT_RESPONSE_HEADER'
            }
        },
        'variables': {
            'string': 'string'
        },
        'documentationVersion': 'string',
        'createdDate': datetime(2015, 1, 1),
        'lastUpdatedDate': datetime(2015, 1, 1)
    }

    :returns:
    (string) --
    (string) --

    """
    pass


@staticmethod
def tabulate(link):
    """Make a given a href link parsed on bs4 printable."""
    return link.parent.find(class_='detName').text, link.parent.find(class_
        ='detDesc').text, link['href']


@staticmethod
def valuesAreEqual(a, b, tol=1e-14):
    """
        Returns true if two numeric values are equal. Optionally supply a tolerance.
        """
    diff = a - b
    if diff < 0:
        diff = diff * -1
    if diff <= tol:
        return True
    else:
        return False


def scroll(string: str, delay: int=150, *, wait: bool=True, loop: bool=
    False, monospace: bool=False) ->None:
    """Similar to ``show``, but scrolls the ``string`` horizontally instead. The
    ``delay`` parameter controls how fast the text is scrolling.

    If ``wait`` is ``True``, this function will block until the animation is
    finished, otherwise the animation will happen in the background.

    If ``loop`` is ``True``, the animation will repeat forever.

    If ``monospace`` is ``True``, the characters will all take up 5 pixel-columns
    in width, otherwise there will be exactly 1 blank pixel-column between each
    character as they scroll.

    Note that the ``wait``, ``loop`` and ``monospace`` arguments must be specified
    using their keyword.
    """


def notifySuccess(ob, action, result):
    """ Notification that a workflow action has taken place.

        o 'ob' is the target object of the action.

        o 'action' is a string identifying the succesful action;
          usually it corresponds to a method name.

        o 'result' is the return value from the method called.

        o Invoked by the portal_workflow tool.

        o Permission:  Private (Python only)
        """


def _get_line(current_output):
    """ Back up in the output buffer to
        find the start of the current line,
        and return the entire line.
    """
    myline = []
    index = len(current_output)
    while index:
        index -= 1
        try:
            s = str(current_output[index])
        except:
            raise
        myline.append(s)
        if '\n' in s:
            break
    myline = ''.join(reversed(myline))
    return myline.rsplit('\n', 1)[-1]


@staticmethod
def _source_google_storage():
    """Method to add google storage as source."""
    pass


@staticmethod
def _get_save_messages_photo(session, photo, server, hash):
    """
        https://vk.com/dev/photos.saveMessagesPhoto
        """
    response = session.fetch('photos.saveMessagesPhoto', photo=photo,
        server=server, hash=hash)[0]
    return response['id'], response['owner_id']


@staticmethod
def header_info():
    """Return a list of elements that should be added to the VCF header so:

    vcf_in.header.info.add(*lc.header_info())
    """
    return 'LC', 1, 'Float', 'Linguistic complexity of local sequence'


def prefix(a, b):
    """Check if sequence a is a prefix of sequence b."""
    if len(a) > len(b):
        return False
    for i in range(0, len(a)):
        if a[i] != b[i]:
            return False
    return True


@staticmethod
def _positem(size):
    """Account for negative indices."""
    if size < 0:
        return 2 * (size + 1) - 1
    else:
        return size * 2


def is_integer_like(val):
    """Returns validation of a value as an integer."""
    try:
        int(val)
        return True
    except (TypeError, ValueError, AttributeError):
        return False


def _py3_compat_decode(item_out_of_redis):
    """Py3 redis returns bytes, so we must handle the decode."""
    if not isinstance(item_out_of_redis, str):
        return item_out_of_redis.decode('utf-8')
    return item_out_of_redis


@conf
def find_icpc(conf):
    """
	Finds the program icpc, and execute it to ensure it really is icpc
	"""
    cxx = conf.find_program('icpc', var='CXX')
    conf.get_cc_version(cxx, icc=True)
    conf.env.CXX_NAME = 'icc'


def spatial_window(alpha, delta, spx, spy, alpha_axis, delta_axis):
    """
    Compute a 2D window centered at (alpha,delta) within alpha_axis and delta_axis.

    spatial_window() returns a tuple (alpha_window,delta_window), where each element
    are the lower and upper indices for each axis. The window correspond to a window
    of freq +- spx or freq +- spy depending on the axis. This window is limited by
    the axis borders. Equispaced axes are assumed.
    @rtype : tuple
    @param alpha: RA center
    @param delta: DEC center
    @param spx: Semiaxis X
    @param spy: Semiaxis Y
    @param alpha_axis: a equispaced array of elements
    @param delta_axis: a equispaced array of elements
    """
    dlta_x = alpha_axis[1] - alpha_axis[0]
    dlta_y = delta_axis[1] - delta_axis[0]
    xbord = [int(round((alpha - spx - alpha_axis[0]) / dlta_x)), int(round(
        (alpha + spx - alpha_axis[0]) / dlta_x))]
    ybord = [int(round((delta - spy - delta_axis[0]) / dlta_y)), int(round(
        (delta + spy - delta_axis[0]) / dlta_y))]
    if xbord[0] < 0:
        xbord[0] = 0
    if ybord[0] < 0:
        ybord[0] = 0
    if xbord[1] > len(alpha_axis):
        xbord[1] = len(alpha_axis)
    if ybord[1] > len(delta_axis):
        ybord[1] = len(delta_axis)
    return ybord, xbord


def single_key(dict_):
    """dict must have exactly one key, return it.

    Raises ValueError if the dict has more than one key.
    """
    keys = list(dict_.keys())
    if len(keys) != 1:
        raise ValueError("dict hasn't exactly one key: %s" % repr(keys))
    return keys[0]


def optional(*typs):
    """ Convenience function to specify that a value may be of any of the types in type 'typs' or None """
    return tuple(typs) + (type(None),)


def refund_address(refund_address):
    """
    Makes sure refund_address is valid.

    Currently not implemented.
    """
    if refund_address is None:
        return True
    if not isinstance(refund_address, str):
        raise TypeError('refund_address must be none or str.')
    return True


def create_configuration_set(ConfigurationSet=None):
    """
    Creates a configuration set.
    Configuration sets enable you to publish email sending events. For information about using configuration sets, see the Amazon SES Developer Guide .
    This action is throttled at one request per second.
    See also: AWS API Documentation

    :example: response = client.create_configuration_set(
        ConfigurationSet={
            'Name': 'string'
        }
    )

    :type ConfigurationSet: dict
    :param ConfigurationSet: [REQUIRED]
            A data structure that contains the name of the configuration set.
            Name (string) -- [REQUIRED]The name of the configuration set. The name must:
            Contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-).
            Contain less than 64 characters.

    :rtype: dict
    :return: {}

    """
    pass


def group_select():
    """Select bones in active Bone Group

    """
    pass


def set_session(session):
    """Sets the global TensorFlow session.

    # Arguments
        session: A TF Session.
    """
    global _SESSION
    _SESSION = session


def _clear_cache():
    """Clear the config cache."""
    global __config
    __config = None


def make_replicator_config(topics, src_kafka, dest_kafka,
    topic_rename_format, tasks, schema_registry_topic, schema_registry_url,
    group_id, filter_regex, blacklist, check_interval):
    """Make Replicator connector configuration.

    Parameters
    ----------
    topics : `list`
        List of topics to whitelist.
    src_kafka : `str`
        Source Kafka broker.
    dest_kafka : `str`
        Destination kafka broker.
    topic_rename_format : `str`
        Format string for destination topics, e.g. `summit_$(topic)`.
    tasks : `int`
        Number of Kafka connect tasks.
    schema_registry_url : `str`
        Schema registry URL for the destination cluster.
    group_id : `str`
        Kafka Connect group.id
    filter_regex : `str`
        Regex of topics to replicate to the destination cluster.
    blacklist : `str`
        Topics to exclude from replication.
    check_interval : `int`
        How often to poll the source cluster for new topics.
    """
    DEFAULT_CONVERTER = (
        'io.confluent.connect.replicator.util.ByteArrayConverter')
    config = {}
    config['connector.class'
        ] = 'io.confluent.connect.replicator.ReplicatorSourceConnector'
    config['tasks.max'] = tasks
    config['key.converter'] = DEFAULT_CONVERTER
    config['value.converter'] = DEFAULT_CONVERTER
    config['header.converter'] = DEFAULT_CONVERTER
    config['schema.registry.topic'] = schema_registry_topic
    config['topic.regex'] = filter_regex
    topics = list(set(topics))
    topics.sort()
    topics.append(schema_registry_topic)
    if blacklist:
        config['topic.blacklist'] = ','.join(blacklist)
        for blacklisted_topic in blacklist:
            topics.remove(blacklisted_topic)
    config['topic.whitelist'] = ','.join(topics)
    config['topic.rename.format'] = topic_rename_format
    config['topic.poll.interval.ms'] = check_interval
    config['src.kafka.bootstrap.servers'] = src_kafka
    config['dest.kafka.bootstrap.servers'] = dest_kafka
    config['schema.subject.translator.class'
        ] = 'io.confluent.connect.replicator.schemas.DefaultSubjectTranslator'
    config['schema.registry.url'] = schema_registry_url
    if group_id:
        config['src.consumer.group.id'] = group_id
    return config


def freestyle_module_open(filepath: str='', make_internal: bool=True):
    """Open a style module file

    :param filepath: filepath
    :type filepath: str
    :param make_internal: Make internal, Make module file internal after loading
    :type make_internal: bool
    """
    pass


def upload_project_run(upload_context):
    """
    Function run by CreateProjectCommand to create the project.
    Runs in a background process.
    :param upload_context: UploadContext: contains data service setup and project name to create.
    """
    data_service = upload_context.make_data_service()
    project_name = upload_context.project_name
    result = data_service.create_project(project_name, project_name)
    return result.json()['id']


def get_metallicity_from_atm_table_filename(filename):
    """
    Get metallicity as number from filename / directory.

    :param filename: str;
    :return: float;
    """
    m = str(filename).split('_')[0][-3:]
    sign = 1 if str(m).startswith('p') else -1
    value = float(m[1:]) / 10.0
    return value * sign


@classmethod
def from_moneyline_odds_against(cls, numerator=0, denominator=None):
    """Create a probability from moneyline odds against."""
    n, d = cls._format_moneyline(numerator, denominator)
    return cls(d, n + d)


def describe():
    """Return a short string describing where in the object tree this
        unslicer is sitting, relative to its parent. These strings are
        obtained from every unslicer in the stack, and joined to describe
        where any problems occurred."""


@staticmethod
def _pretty_print_event(event, colored):
    """
        Basic formatter to convert an event object to string
        """
    event.timestamp = colored.yellow(event.timestamp)
    event.log_stream_name = colored.cyan(event.log_stream_name)
    return ' '.join([event.log_stream_name, event.timestamp, event.message])


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


def strings(n, k):
    """Number of DUSWR of k items from a set of n items."""
    return pow(n, k)


def theta_B4O5OH4_HCO3_FW86(T, P):
    """a-a': tetraborate bicarbonate [FW86]."""
    theta = -0.087
    valid = T == 298.15
    return theta, valid


def validate_width_height(dims):
    """
    Checks if dims (width, height) is a valid specification,
    meaning width and height are both integers above zero.

    :param dims: (width, height)
    :raises: TypeError, ValueError
    :returns: True
    """
    if dims is None:
        raise ValueError('Null input for (width, height).')
    width, height = dims
    if not isinstance(width, int):
        raise TypeError('Width should be an integer.')
    if not isinstance(height, int):
        raise TypeError('Height should be an integer.')
    if width < 1:
        raise ValueError('Width should be >= 1.')
    if height < 1:
        raise ValueError('Height should be >= 1.')
    return True


def GetAtomItemsById(atomData, atomLookUp, IdList, itemLoc, numItems=1):
    """gets atom parameters for atoms using atom IDs

    :param list atomData: Atom table to be used
    :param dict atomLookUp: dictionary of atom indexes with atom IDs as keys
    :param list IdList: atom IDs to be found
    :param int itemLoc: pointer to desired 1st item in an atom table entry
    :param int numItems: number of items to be retrieved

    :returns: type name: description

    """
    Items = []
    if not isinstance(IdList, list):
        IdList = [IdList]
    for Id in IdList:
        if numItems == 1:
            Items.append(atomData[atomLookUp[Id]][itemLoc])
        else:
            Items.append(atomData[atomLookUp[Id]][itemLoc:itemLoc + numItems])
    return Items


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


def _tkerror(err):
    """Internal function."""
    pass


def get_command_invocation(CommandId=None, InstanceId=None, PluginName=None):
    """
    Returns detailed information about command execution for an invocation or plugin.
    See also: AWS API Documentation

    :example: response = client.get_command_invocation(
        CommandId='string',
        InstanceId='string',
        PluginName='string'
    )

    :type CommandId: string
    :param CommandId: [REQUIRED]
            (Required) The parent command ID of the invocation plugin.

    :type InstanceId: string
    :param InstanceId: [REQUIRED]
            (Required) The ID of the managed instance targeted by the command. A managed instance can be an Amazon EC2 instance or an instance in your hybrid environment that is configured for Systems Manager.

    :type PluginName: string
    :param PluginName: (Optional) The name of the plugin for which you want detailed results. If the document contains only one plugin, the name can be omitted and the details will be returned.

    :rtype: dict
    :return: {
        'CommandId': 'string',
        'InstanceId': 'string',
        'Comment': 'string',
        'DocumentName': 'string',
        'PluginName': 'string',
        'ResponseCode': 123,
        'ExecutionStartDateTime': 'string',
        'ExecutionElapsedTime': 'string',
        'ExecutionEndDateTime': 'string',
        'Status': 'Pending'|'InProgress'|'Delayed'|'Success'|'Cancelled'|'TimedOut'|'Failed'|'Cancelling',
        'StatusDetails': 'string',
        'StandardOutputContent': 'string',
        'StandardOutputUrl': 'string',
        'StandardErrorContent': 'string',
        'StandardErrorUrl': 'string'
    }

    :returns:
    Pending: The command has not been sent to the instance.
    In Progress: The command has been sent to the instance but has not reached a terminal state.
    Delayed: The system attempted to send the command to the target, but the target was not available. The instance might not be available because of network issues, the instance was stopped, etc. The system will try to deliver the command again.
    Success: The command or plugin was executed successfully. This is a terminal state.
    Delivery Timed Out: The command was not delivered to the instance before the delivery timeout expired. Delivery timeouts do not count against the parent command's MaxErrors limit, but they do contribute to whether the parent command status is Success or Incomplete. This is a terminal state.
    Execution Timed Out: The command started to execute on the instance, but the execution was not complete before the timeout expired. Execution timeouts count against the MaxErrors limit of the parent command. This is a terminal state.
    Failed: The command wasn't executed successfully on the instance. For a plugin, this indicates that the result code was not zero. For a command invocation, this indicates that the result code for one or more plugins was not zero. Invocation failures count against the MaxErrors limit of the parent command. This is a terminal state.
    Canceled: The command was terminated before it was completed. This is a terminal state.
    Undeliverable: The command can't be delivered to the instance. The instance might not exist or might not be responding. Undeliverable invocations don't count against the parent command's MaxErrors limit and don't contribute to whether the parent command status is Success or Incomplete. This is a terminal state.
    Terminated: The parent command exceeded its MaxErrors limit and subsequent command invocations were canceled by the system. This is a terminal state.

    """
    pass


@staticmethod
def to_link(standard_object, title):
    """
        Many objects from the ReST API have reference to other objects that can
        also be retrieved from the ReST API.  That reference is typically a Link object.
        This function converts a standard API object to a Link.
        :param dict standard_object: the object to be converted to a link
        :param str title: an optional title value to give this object
        :rtype: Link
        """
    return {'id': standard_object['id'], 'href': standard_object['href'],
        'title': title}


def coefficient_aug(acceleration, gravity):
    """Usage: Find friction coefficient using acceleration and gravitational constant"""
    return acceleration / gravity


def shell_config(shell):
    """
    Returns a dict in the following form, depending on the given shell:
    return {
        'prefix': '<preffix-to-use>',
        'suffix': 'suffix-to-use',
        'delimiter': '<delimiter-to-use>',
    }
    Logic from Docker Machine:
    https://github.com/docker/machine/blob/master/commands/env.go#L125
    """
    if shell == 'fish':
        return {'prefix': 'set -gx ', 'suffix': '";\n', 'delimiter': ' "'}
    elif shell == 'powershell':
        return {'prefix': '$Env:', 'suffix': '"\n', 'delimiter': ' = "'}
    elif shell == 'cmd':
        return {'prefix': 'SET ', 'suffix': '\n', 'delimiter': '='}
    elif shell == 'tcsh':
        return {'prefix': 'setenv ', 'suffix': '";\n', 'delimiter': ' "'}
    elif shell == 'emacs':
        return {'prefix': '(setenv "', 'suffix': '")\n', 'delimiter': '" "'}
    else:
        return {'prefix': 'export ', 'suffix': '"\n', 'delimiter': '="'}


def _np_ones_like(a):
    """
    Return an array of ones with the same shape and type as a given array.

    Parameters
    ----------
    a : ndarray
        The shape and data-type of `a` define these same attributes of
        the returned array.

    Returns
    -------
    out : ndarray
        Array of ones with the same shape and type as `a`.

    Examples
    --------
    >>> x = np.arange(6)
    >>> x = x.reshape((2, 3))
    >>> x
    array([[0., 1., 2.],
           [3., 4., 5.]])
    >>> np.ones_like(x)
    array([[1., 1., 1.],
           [1., 1., 1.]])

    >>> y = np.arange(3, dtype=float)
    >>> y
    array([0., 1., 2.], dtype=float64)
    >>>
    >>> np.ones_like(y)
    array([1., 1., 1.], dtype=float64)
    """
    pass


def closest_value(value, list_of_values):
    """

    Get the closet value in a list of values.

    :param value: a numeric value.
    :type value: ``int``, ``float`` or ``datetime``
    :param list_of_values: an iterable.
    :type list_of_values: ``tuple``, ``list``, ``np.array``
    :return: item in `list_of_values` closet to `value`.
    :rtype: ``int``, ``float`` or ``datetime``
    """
    return min(list_of_values, key=lambda i: abs(i - value))


def polynomial_reduce_mod(poly, polymod, p):
    """Reduce poly by polymod, integer arithmetic modulo p.

  Polynomials are represented as lists of coefficients
  of increasing powers of x."""
    assert polymod[-1] == 1
    assert len(polymod) > 1
    while len(poly) >= len(polymod):
        if poly[-1] != 0:
            for i in range(2, len(polymod) + 1):
                poly[-i] = (poly[-i] - poly[-1] * polymod[-i]) % p
        poly = poly[0:-1]
    return poly


def iterable(obj):
    """Returns ``True`` if *obj* can be iterated over and is *not* a  string."""
    if type(obj) is str:
        return False
    if hasattr(obj, 'next'):
        return True
    try:
        len(obj)
    except TypeError:
        return False
    return True


def get_object_from_string(object_path):
    """
    Return python object from string
    :param object_path: e.g os.path.join
    :return: python object
    """
    try:
        module_name, object_name = object_path.rsplit('.', maxsplit=1)
        module_ = __import__(module_name, globals(), locals(), ['App'], 0)
        variable_ = getattr(module_, object_name)
    except Exception:
        variable_ = None
    return variable_


def prepare_data(dictionary, key_name, value_name, limit=10):
    """Prepare data for the bar plot. Convert key, value pairs to named objects"""
    data = []
    for key, value in dictionary.items():
        record = {key_name: key, value_name: value}
        data.append(record)
    return data[:limit]


def milestone_data_is_valid(milestone_data):
    """
    Milestone data validation
    """
    if milestone_data is None:
        return False
    if 'id' in milestone_data and not milestone_data.get('id'):
        return False
    if 'name' in milestone_data and not milestone_data.get('name'):
        return False
    if 'namespace' in milestone_data and not milestone_data.get('namespace'):
        return False
    return True


def translate(string, c_map):
    """Translate according to character mapping table
    :param str string:
    :param dict c_map:
    :rtype: str
    """
    mapped_string = ''
    for c in string:
        if c in c_map:
            mapped_string += c_map[c]
        else:
            mapped_string += c
    return mapped_string


def sync():
    """Synchronize computation.

    In DL frameworks such as MXNet and TensorFlow, the computation in operators
    are done asynchronously. This is to synchronize computation and makes sure
    that all computation is complete after this function call.
    """
    pass


def STD(src_column):
    """
    Builtin standard deviation aggregator for groupby. Synonym for tc.aggregate.STDV

    Example: Get the rating standard deviation of each user.

    >>> sf.groupby("user",
    ...            {'rating_std':tc.aggregate.STD('rating')})
    """
    return '__builtin__stdv__', [src_column]


def tethys_gizmos_context(request):
    """
    Add the gizmos_rendered context to the global context.
    """
    context = {'gizmos_rendered': []}
    return context


@classmethod
def from_path(cls, path):
    """Open an UNC file at the given path.

        Args:
            path (str): The filename to open
        """
    with open(path, 'rb') as f:
        instance = cls.from_file(f)
    return instance


def object_type():
    """ Display name of the object to be created
        """


def protein_subsequences_around_mutations(effects, padding_around_mutation):
    """
    From each effect get a mutant protein sequence and pull out a subsequence
    around the mutation (based on the given padding). Returns a dictionary
    of subsequences and a dictionary of subsequence start offsets.
    """
    protein_subsequences = {}
    protein_subsequence_start_offsets = {}
    for effect in effects:
        protein_sequence = effect.mutant_protein_sequence
        if protein_sequence:
            mutation_start = effect.aa_mutation_start_offset
            mutation_end = effect.aa_mutation_end_offset
            seq_start_offset = max(0, mutation_start - padding_around_mutation)
            first_stop_codon_index = protein_sequence.find('*')
            if first_stop_codon_index < 0:
                first_stop_codon_index = len(protein_sequence)
            seq_end_offset = min(first_stop_codon_index, mutation_end +
                padding_around_mutation)
            subsequence = protein_sequence[seq_start_offset:seq_end_offset]
            protein_subsequences[effect] = subsequence
            protein_subsequence_start_offsets[effect] = seq_start_offset
    return protein_subsequences, protein_subsequence_start_offsets


def lambd_H3PO4_Cl_PS76(T, P):
    """n-a: phosphoric-acid chloride [PS76]."""
    lambd = 0
    valid = T == 298.15
    return lambd, valid


def calc_ndsi(green, swir1):
    """NDSI calculation
    normalized difference snow index

    Parameters
    ----------
    green: ndarray
    swir1: ndarray
        ~1.62 µm
        Band 6 in Landsat 8

    Output
    ------
    ndarray:
        unitless index
    """
    return (green - swir1) / (green + swir1)


def table_name(model):
    """
    Return tablename from a model
    Careful: Accesses a private class _meta on the model
    """
    return model._meta.db_table


def cvtToMag(rh, size):
    """
    Convert a size value to a number with a magnitude appended.

    Input:
       Request Handle
       Size bytes

    Output:
       Converted value with a magnitude
    """
    rh.printSysLog('Enter generalUtils.cvtToMag')
    mSize = ''
    size = size / (1024 * 1024)
    if size > 1024 * 5:
        size = size / 1024
        mSize = '%.1fG' % size
    else:
        mSize = '%.1fM' % size
    rh.printSysLog('Exit generalUtils.cvtToMag, magSize: ' + mSize)
    return mSize


@classmethod
def preprocess_func(cls, func):
    """Preprocess a function before an `apply` call.

        Note: This is a classmethod because the definition of how to preprocess
            should be class-wide. Also, we may want to use this before we
            deploy a preprocessed function to multiple `BaseFramePartition`
            objects.

        Args:
            func: The function to preprocess.

        Returns:
            An object that can be accepted by `apply`.
        """
    return func


def read_conll(fstream):
    """
    Reads a input stream @fstream (e.g. output of `open(fname, 'r')`) in CoNLL file format.
    @returns a list of examples [(tokens), (labels)]. @tokens and @labels are lists of string.
    """
    ret = []
    current_toks, current_lbls = [], []
    for line in fstream:
        line = line.strip()
        if len(line) == 0 or line.startswith('-DOCSTART-'):
            if len(current_toks) > 0:
                assert len(current_toks) == len(current_lbls)
                ret.append((current_toks, current_lbls))
            current_toks, current_lbls = [], []
        else:
            assert '\t' in line, "Invalid CONLL format; expected a '\\t' in {}".format(
                line)
            tok, lbl = line.split('\t')
            current_toks.append(tok)
            current_lbls.append(lbl)
    if len(current_toks) > 0:
        assert len(current_toks) == len(current_lbls)
        ret.append((current_toks, current_lbls))
    return ret


def argument(*name_or_flags, **kwargs):
    """Convenience function to properly format arguments to pass to the
    subcommand decorator.
    """
    args = list()
    for arg in name_or_flags:
        args.append(arg)
    return args, kwargs


def human(size):
    """human readable size"""
    div = 1024.0
    suf = ['B', 'K', 'M', 'G', 'T', 'P']
    if size < div:
        return '{}'.format(size)
    for i in suf:
        if size < div:
            return '{:.1f}{}'.format(size, i)
        size = size / div
    return '{:.1f}{}'.format(size, suf[-1])


def initiate_document_version_upload(Id=None, Name=None,
    ContentCreatedTimestamp=None, ContentModifiedTimestamp=None,
    ContentType=None, DocumentSizeInBytes=None, ParentFolderId=None):
    """
    Creates a new document object and version object.
    The client specifies the parent folder ID and name of the document to upload. The ID is optionally specified when creating a new version of an existing document. This is the first step to upload a document. Next, upload the document to the URL returned from the call, and then call  UpdateDocumentVersion .
    To cancel the document upload, call  AbortDocumentVersionUpload .
    See also: AWS API Documentation

    :example: response = client.initiate_document_version_upload(
        Id='string',
        Name='string',
        ContentCreatedTimestamp=datetime(2015, 1, 1),
        ContentModifiedTimestamp=datetime(2015, 1, 1),
        ContentType='string',
        DocumentSizeInBytes=123,
        ParentFolderId='string'
    )

    :type Id: string
    :param Id: The ID of the document.

    :type Name: string
    :param Name: The name of the document.

    :type ContentCreatedTimestamp: datetime
    :param ContentCreatedTimestamp: The time stamp when the content of the document was originally created.

    :type ContentModifiedTimestamp: datetime
    :param ContentModifiedTimestamp: The time stamp when the content of the document was modified.

    :type ContentType: string
    :param ContentType: The content type of the document.

    :type DocumentSizeInBytes: integer
    :param DocumentSizeInBytes: The size of the document, in bytes.

    :type ParentFolderId: string
    :param ParentFolderId: [REQUIRED]
            The ID of the parent folder.

    :rtype: dict
    :return: {
        'Metadata': {
            'Id': 'string',
            'CreatorId': 'string',
            'ParentFolderId': 'string',
            'CreatedTimestamp': datetime(2015, 1, 1),
            'ModifiedTimestamp': datetime(2015, 1, 1),
            'LatestVersionMetadata': {
                'Id': 'string',
                'Name': 'string',
                'ContentType': 'string',
                'Size': 123,
                'Signature': 'string',
                'Status': 'INITIALIZED'|'ACTIVE',
                'CreatedTimestamp': datetime(2015, 1, 1),
                'ModifiedTimestamp': datetime(2015, 1, 1),
                'ContentCreatedTimestamp': datetime(2015, 1, 1),
                'ContentModifiedTimestamp': datetime(2015, 1, 1),
                'CreatorId': 'string',
                'Thumbnail': {
                    'string': 'string'
                },
                'Source': {
                    'string': 'string'
                }
            },
            'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED'
        },
        'UploadMetadata': {
            'UploadUrl': 'string',
            'SignedHeaders': {
                'string': 'string'
            }
        }
    }

    :returns:
    (string) --
    (string) --

    """
    pass


@staticmethod
def remover(fn):
    """Tag the method as the collection remover.

        The remover method is called with one positional argument: the value
        to remove. The method will be automatically decorated with
        :meth:`removes_return` if not already decorated::

            @collection.remover
            def zap(self, entity): ...

            # or, equivalently
            @collection.remover
            @collection.removes_return()
            def zap(self, ): ...

        If the value to remove is not present in the collection, you may
        raise an exception or return None to ignore the error.

        If the remove method is internally instrumented, you must also
        receive the keyword argument '_sa_initiator' and ensure its
        promulgation to collection events.

        """
    fn._sa_instrument_role = 'remover'
    return fn


def get_default_settings():
    """
    Return the default settings for the circuit drawing function to_latex().

    Returns:
        settings (dict): Default circuit settings
    """
    settings = dict()
    settings['gate_shadow'] = True
    settings['lines'] = {'style': 'very thin', 'double_classical': True,
        'init_quantum': True, 'double_lines_sep': 0.04}
    settings['gates'] = {'HGate': {'width': 0.5, 'offset': 0.3,
        'pre_offset': 0.1}, 'XGate': {'width': 0.35, 'height': 0.35,
        'offset': 0.1}, 'SqrtXGate': {'width': 0.7, 'offset': 0.3,
        'pre_offset': 0.1}, 'SwapGate': {'width': 0.35, 'height': 0.35,
        'offset': 0.1}, 'SqrtSwapGate': {'width': 0.35, 'height': 0.35,
        'offset': 0.1}, 'Rx': {'width': 1.0, 'height': 0.8, 'pre_offset':
        0.2, 'offset': 0.3}, 'Ry': {'width': 1.0, 'height': 0.8,
        'pre_offset': 0.2, 'offset': 0.3}, 'Rz': {'width': 1.0, 'height':
        0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'Ph': {'width': 1.0,
        'height': 0.8, 'pre_offset': 0.2, 'offset': 0.3}, 'EntangleGate': {
        'width': 1.8, 'offset': 0.2, 'pre_offset': 0.2},
        'DeallocateQubitGate': {'height': 0.15, 'offset': 0.2, 'width': 0.2,
        'pre_offset': 0.1}, 'AllocateQubitGate': {'height': 0.15, 'width':
        0.2, 'offset': 0.1, 'pre_offset': 0.1, 'draw_id': False,
        'allocate_at_zero': False}, 'MeasureGate': {'width': 0.75, 'offset':
        0.2, 'height': 0.5, 'pre_offset': 0.2}}
    settings['control'] = {'size': 0.1, 'shadow': False}
    return settings


@classmethod
def map_back(cls, entity_properties: dict) ->dict:
    """Map properties from AiiDA to OPTiMaDe

        :param entity_properties: Found AiiDA properties through QueryBuilder query
        :type entity_properties: dict

        :return: A resource object in OPTiMaDe format
        :rtype: dict
        """


def do_float(value, default=0.0):
    """Convert the value into a floating point number. If the
    conversion doesn't work it will return ``0.0``. You can
    override this default using the first parameter.
    """
    try:
        return float(value)
    except (TypeError, ValueError):
        return default


def flat_map_impl(func, sequence):
    """
    Implementation for flat_map_t
    :param func: function to map
    :param sequence: sequence to flat_map over
    :return: flat_map generator
    """
    for element in sequence:
        for value in func(element):
            yield value


def list_sectie_adapter(obj, request):
    """
    Adapter for rendering a list of
    :class: `crabpy.gateway.capakey.Sectie` to json.
    """
    return {'id': obj.id, 'afdeling': obj.afdeling}


def _iso_datetime(value):
    """
    If value appears to be something datetime-like, return it in ISO format.

    Otherwise, return None.
    """
    if hasattr(value, 'strftime'):
        if hasattr(value, 'hour'):
            return value.isoformat()
        else:
            return '%sT00:00:00' % value.isoformat()


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 associate_web_acl(WebACLId=None, ResourceArn=None):
    """
    Associates a web ACL with a resource.
    See also: AWS API Documentation

    :example: response = client.associate_web_acl(
        WebACLId='string',
        ResourceArn='string'
    )

    :type WebACLId: string
    :param WebACLId: [REQUIRED]
            A unique identifier (ID) for the web ACL.

    :type ResourceArn: string
    :param ResourceArn: [REQUIRED]
            The ARN (Amazon Resource Name) of the resource to be protected.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def percent(string):
    """Convert a string (i.e. 85) to a fraction (i.e. .85)."""
    return float(string) / 100.0


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

        :param SharedFolderAccessError val:
        :rtype: UpdateFolderPolicyError
        """
    return cls('access_error', val)


def get_elapsed_time_string(start_time, end_time):
    """
    Get a string representing the elapsed time given a start and end time.
    :param start_time: Start time (time.time())
    :param end_time: End time (time.time())
    :return:
    """
    elapsed = end_time - start_time
    hours = str(int(elapsed / 3600))
    elapsed = elapsed - elapsed / 3600
    mins = str(int(elapsed / 60))
    secs = str(int(elapsed) % 60)
    time_string = hours + ' HOURS ' + mins + ' MINS ' + secs + ' SECS.'
    return time_string


def _common_bytes(blocks1, blocks2):
    """Count the number of common bytes in two block count dicts.

    :param block1: The first dict of block hashcode -> total bytes.
    :param block2: The second dict of block hashcode -> total bytes.
    :return: The number of bytes in common between blocks1 and blocks2. This is
        only approximate due to possible hash collisions.
    """
    if len(blocks1) > len(blocks2):
        blocks1, blocks2 = blocks2, blocks1
    score = 0
    for block, count1 in blocks1.iteritems():
        count2 = blocks2.get(block)
        if count2:
            score += min(count1, count2)
    return score


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


def hide():
    """Hide selected objects and collections

    """
    pass


def RSI(df, n, price='Close'):
    """
    Relative Strength Index
    Returns: list of floats = jhta.RSI(df, n, price='Close')
    Source: https://www.fmlabs.com/reference/default.htm?url=rsi.htm
    """
    rsi_list = []
    upavg = 0.0
    dnavg = 0.0
    for i in range(len(df[price])):
        if i + 1 < n:
            rsi = float('NaN')
        else:
            if df[price][i] > df[price][i - 1]:
                up = df[price][i] - df[price][i - 1]
                dn = 0
            else:
                up = 0
                dn = df[price][i - 1] - df[price][i]
            upavg = (upavg * (n - 1) + up) / n
            dnavg = (dnavg * (n - 1) + dn) / n
            rsi = 100 * upavg / (upavg + dnavg)
        rsi_list.append(rsi)
    return rsi_list


@staticmethod
def _run_on_subset(func, df_subset):
    """Applies a function to a dataframe subset."""
    return df_subset.apply(func, axis=1)


def appendleft(thing):
    """
        append `thing` to left side of incoming things

        @param thing: some thing
        """


@classmethod
def __array_function__(cls, func, types, args, kwargs):
    """Array function protocol.
           https://numpy.org/neps/nep-0018-array-function-protocol.html
        """
    raise NotImplementedError()


def cir_RsC_fit(params, w):
    """
    Fit Function: -Rs-C-
    """
    Rs = params['Rs']
    C = params['C']
    return Rs + 1 / (C * (w * 1.0j))


def inique(iterable):
    """ Generate unique elements from `iterable`

    Parameters
    ----------
    iterable : iterable

    Returns
    -------
    gen : generator
       generator that yields unique elements from `iterable`

    Examples
    --------
    >>> tuple(inique([0, 1, 2, 0, 2, 3]))
    (0, 1, 2, 3)
    """
    history = []
    for val in iterable:
        if val not in history:
            history.append(val)
            yield val


def fix_id(id):
    """
  fixes the id such that is it a resource identifier
  :param id:
  :return:
  """
    import re
    r = re.sub("[!#$%&'\\(\\)\\*\\+,\\./:;<=>\\?@\\[\\\\\\]\\^`\\{\\|}~_]+",
        ' ', id)
    r = r.title()
    r = r[0].lower() + r[1:]
    r = re.sub('\\s+', '', r, flags=re.UNICODE)
    return r


def factorize(num):
    """ Provide prime number factors for integer num
    :returns: dictionary of prime factors (keys) & power for each (data)
    """
    factors = {}
    orig = num
    i, sqi = 2, 4
    while sqi <= num:
        while not num % i:
            num /= i
            factors[i] = factors.get(i, 0) + 1
        sqi += 2 * i + 1
        i += 1
    if num != 1 and num != orig:
        factors[num] = factors.get(num, 0) + 1
    if factors:
        return factors
    else:
        return {num: 1}


def _override_period(period_override):
    """
    Indicates whether period can be overridden if the period derived from granularity does
    not match the generated period.

      period_override : int
        the user-specified period that overrides the value calculated from granularity
    """
    return period_override is not None


def submit_qlaunch(project, queue, nodes, time_minutes, job_mode, wf_filter):
    """Submit Balsam launcher job to batch scheduler"""
    from balsam.service import service
    from balsam.core import models
    QueuedLaunch = models.QueuedLaunch
    qlaunch = QueuedLaunch(project=project, queue=queue, nodes=nodes,
        wall_minutes=time_minutes, job_mode=job_mode, wf_filter=wf_filter,
        prescheduled_only=False)
    qlaunch.save()
    service.submit_qlaunch(qlaunch, verbose=True)


def find_divisors(n):
    """ Find all the positive divisors of the given integer n.

    Args:
        n (int): strictly positive integer

    Returns:
        A generator of all the positive divisors of n

    Raises:
        TypeError: if n is not an integer
        ValueError: if n is negative

    """
    if not isinstance(n, int):
        raise TypeError('Expecting a strictly positive integer')
    if n <= 0:
        raise ValueError('Expecting a strictly positive integer')
    for i in range(1, int(n ** 0.5) + 1):
        if n % i == 0:
            divisors = {i, n // i}
            for divisor in divisors:
                yield divisor


@classmethod
def _parse_header(cls, xmlelements, tns, operation):
    """Parse the soap:header and optionally included soap:headerfault elements

          <soap:header
            message="qname"
            part="nmtoken"
            use="literal|encoded"
            encodingStyle="uri-list"?
            namespace="uri"?
          />*

        The header can optionally contain one ore more soap:headerfault
        elements which can contain the same attributes as the soap:header::

           <soap:headerfault message="qname" part="nmtoken" use="literal|encoded"
                             encodingStyle="uri-list"? namespace="uri"?/>*

        """
    result = []
    for xmlelement in xmlelements:
        data = cls._parse_header_element(xmlelement, tns)
        data['faults'] = []
        fault_elements = xmlelement.findall('soap:headerfault', namespaces=
            operation.binding.nsmap)
        for fault_element in fault_elements:
            fault_data = cls._parse_header_element(fault_element, tns)
            data['faults'].append(fault_data)
        result.append(data)
    return result


def get_mode(counter):
    """
    Helper function to return the count of the most common
    element from an instance of Counter()
    :param counter: collections.Counter instance
    """
    mode = counter.most_common(1)
    if not mode:
        return 0
    return mode[0][1]


@staticmethod
def exit_app(_env, gui):
    """Exit GUI application."""
    gui.exit_app()


@classmethod
def get_by_uuid(cls, context, uuid):
    """Find a node based on UUID and return a Node object.

        :param cls: the :class:`Node`
        :param context: Security context
        :param uuid: the UUID of a node.
        :returns: a :class:`Node` object.
        """
    db_node = cls.dbapi.get_node_by_uuid(uuid)
    node = cls._from_db_object(context, cls(), db_node)
    return node


def close(callback):
    """Close this file.  Move it to its final location.

        @param callback: A no-argument callable which will be invoked
        when this file is ready to be moved to its final location.  It
        must return the segment of the path relative to per-user
        storage of the owner of this file.  Alternatively, a string
        with semantics the same as those previously described for the
        return value of the callable.

        @rtype: C{axiom.store.StoreRelativePath}
        @return: A Deferred which fires with the full path to the file
        when it has been closed, or which fails if there is some error
        closing the file.
        """


def classinit_pic_dif_bit_width(cls):
    """
        Decorator that adds the PIC dif_bit_width static table to *cls*.
        """
    cls._dif_bit_width = []
    for i in range(0, 128):
        cls._dif_bit_width.append((2 * i).bit_length())
    for i in range(-128, 0):
        cls._dif_bit_width.append((-2 * i - 1).bit_length())
    return cls


def configure(conf):
    """
	Configuration for g++
	"""
    conf.find_gxx()
    conf.find_ar()
    conf.gxx_common_flags()
    conf.gxx_modifier_platform()
    conf.cxx_load_tools()
    conf.cxx_add_flags()
    conf.link_add_flags()
    conf.check_gcc_o_space('cxx')


def produce_ver_num(major, minor, release):
    """produce the version number
    """
    num = major * 1000000 + minor * 1000 + release
    return num


def rangePick(target, min, max):
    """Validates an integer target from within a min/max boundary. If target is outside the defined range then return the range boundary as the choice

    :param target: The desired answer
    :type target: int
    :param min: The lowest possible value allowed
    :type min: int
    :param max: The highest possible value allowed
    :type max: int
    :return: An integer as close to target as possible given the defined range
    :rtype: int
    """
    if int(target) < int(min):
        return int(min)
    if int(target) > int(max):
        return int(max)
    return int(target)


def add_translation(object, intid):
    """
        create the translated content and register the translation
        """


def to_bytes(data):
    """
    only valid for python3
    """
    if isinstance(data, str):
        return data.encode(encoding='utf-8')
    else:
        return data


def compute_ber_size(data):
    """
    Compute size according to BER definite length rules
    Returns size of value and value offset
    """
    if data[1] <= 127:
        return data[1], 2
    else:
        bytes_length = data[1] - 128
        value_length = 0
        cont = bytes_length
        for byte in data[2:2 + bytes_length]:
            cont -= 1
            value_length += byte * 256 ** cont
        return value_length, bytes_length + 2


def left_screen_edge(desktop, rect):
    """ Get the x-coordinate of the effective left screen edge.

    Parameters
    ----------
    desktop : QDesktopWidget
        The desktop widget for the application.

    rect : QRect
        The rect of interest.

    Returns
    -------
    result : int
        the x-coordinate of the effective left screen edge.

    """
    p1 = rect.topLeft()
    p2 = rect.bottomLeft()
    g1 = desktop.availableGeometry(p1)
    g2 = desktop.availableGeometry(p2)
    return max(p1.x(), g1.left(), g2.left())


@classmethod
def get_gene_name(cls, entry):
    """
        get primary gene name from XML node entry

        :param entry: XML node entry
        :return: str
        """
    gene_name = entry.find("./gene/name[@type='primary']")
    return gene_name.text if gene_name is not None and gene_name.text.strip(
        ) else None


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


def extract(name, data, config):
    """Updates the value of the into the data dict.
        Params:

            - name: String - Name of the field.
            - data: Dict.
            - config: Dict - Holds additional/optional configurations.
        """


def _check_if_index_name_in_cols(df):
    """
    Check if existing index is in the passed dataframe list of column names

    Parameters
    ----------
    df : pandas.DataFrame
        interpolated stop_time dataframe

    Returns
    -------
    iname : tuple
    """
    cols = df.columns.values
    iname = df.index.name
    return iname in cols


def p_term_parens(p):
    """term : PAREN_BEGIN or_terms PAREN_END"""
    p[0] = p[2]


def getCurrentRevision(obj):
    """Get the currently active revision of the object.

        If no revision or active revision is found for the object, `None` is
        returned.
        """


@classmethod
def facts(cls, options=None):
    """
        List all fact values.

        Usage::

            hammer host facts [OPTIONS]

        Options::

            --id ID                       resource id
            --name NAME                   resource name
            --order ORDER                 sort results
            --page PAGE                   paginate results
            --per-page PER_PAGE           number of entries per request
            --search SEARCH               filter results
            -h, --help                    print help
        """
    cls.command_sub = 'facts'
    result = cls.execute(cls._construct_command(options), output_format='csv')
    facts = []
    if result:
        facts = result
    return facts


def ismacro(name):
    """ Is the name a macro?

    >>> ismacro('@time')
    True
    >>> ismacro('sum')
    False
    """
    return name.startswith('@')


def default_introspection_processing_hook(introspection_response, client,
    id_token):
    """
    Hook to customise the returned data from the token introspection endpoint
    :param introspection_response:
    :param client:
    :param id_token:
    :return:
    """
    return introspection_response


def millis_offset_between_epochs(reference_epoch, target_epoch):
    """
    Calculates the signed milliseconds delta between the reference unix epoch and the provided target unix epoch
    :param reference_epoch: the unix epoch that the millis offset has to be calculated with respect to
    :type reference_epoch: int
    :param target_epoch: the unix epoch for which the millis offset has to be calculated
    :type target_epoch: int
    :return: int
    """
    assert isinstance(reference_epoch, int)
    assert isinstance(target_epoch, int)
    return (target_epoch - reference_epoch) * 1000


def rectangle_clip(recta, rectb):
    """
    Return the clipped rectangle of ``recta`` and ``rectb``. If they
    do not intersect, ``None`` is returned.

    >>> rectangle_clip((0, 0, 20, 20), (10, 10, 20, 20))
    (10, 10, 10, 10)
    """
    ax, ay, aw, ah = recta
    bx, by, bw, bh = rectb
    x = max(ax, bx)
    y = max(ay, by)
    w = min(ax + aw, bx + bw) - x
    h = min(ay + ah, by + bh) - y
    if w < 0 or h < 0:
        return None
    return x, y, w, h


def get_link_loops(vert):
    """
    Get loop linked to vertex
    """
    link_loops = []
    for f in vert.link_faces:
        adj_loops = []
        for loop in f.loops:
            if loop.vert == vert:
                l = loop
            else:
                for e in loop.vert.link_edges:
                    if e.other_vert(loop.vert) == vert:
                        adj_loops.append(loop)
        if len(adj_loops) < 2:
            return None
        link_loops.append({'l': l, 'l0': adj_loops[0], 'l1': adj_loops[1]})
    return link_loops


def nice_frequency(frequency):
    """return a string of the frequency with SI unit and a reasonable number
       of digits"""
    if frequency < 1000.0:
        return '%dHz' % frequency
    elif frequency < 10000.0:
        return '%.3fkHz' % (frequency / 1000.0)
    elif frequency < 100000.0:
        return '%.2fkHz' % (frequency / 1000.0)
    elif frequency < 1000000.0:
        return '%.1fkHz' % (frequency / 1000.0)
    elif frequency < 10000000.0:
        return '%.3fMHz' % (frequency / 1000000.0)
    elif frequency < 1000000000.0:
        return '%.2fMHz' % (frequency / 1000000.0)
    return '%.2fGHz' % (frequency / 1000000000.0)


def consistent(old, new):
    """
    Asserts that either first argument is None or
    both arguments are equal, and returns the non-None
    argument.
    """
    if old is None:
        return new
    assert old == new
    return old


@classmethod
def from_fn(cls, data_fn):
    """setup the class variable
        """
    cls.data_fn = staticmethod(data_fn)
    return cls


@classmethod
def set_debug_level(cls, level):
    """Set AsyncSSH debug log level"""
    if level < 1 or level > 3:
        raise ValueError('Debug log level must be between 1 and 3')
    cls._debug_level = level


def rpc(address, func_name, *args):
    """Performs an RPC function call with the given arguments.

    * http://uwsgi.readthedocs.io/en/latest/RPC.html

    .. warning:: Bytes are returned for Python 3.

    :param str|unicode address:

    :param str|unicode func_name: Function name to call.

    :param list[str|bytes] args:

    :rtype: bytes|str

    :raises ValueError: If unable to call RPC function.
    """


def original_scorer(worda_count, wordb_count, bigram_count, len_vocab,
    min_count, corpus_word_count):
    """Bigram scoring function, based on the original `Mikolov, et. al: "Distributed Representations
    of Words and Phrases and their Compositionality" <https://arxiv.org/abs/1310.4546>`_.

    Parameters
    ----------
    worda_count : int
        Number of occurrences for first word.
    wordb_count : int
        Number of occurrences for second word.
    bigram_count : int
        Number of co-occurrences for phrase "worda_wordb".
    len_vocab : int
        Size of vocabulary.
    min_count: int
        Minimum collocation count threshold.
    corpus_word_count : int
        Not used in this particular scoring technique.

    Returns
    -------
    float
        Score for given bi-gram, greater than or equal to 0.

    Notes
    -----
    Formula: :math:`\\frac{(bigram\\_count - min\\_count) * len\\_vocab }{ (worda\\_count * wordb\\_count)}`.

    """
    return (bigram_count - min_count) / worda_count / wordb_count * len_vocab


def divide(elem_count, group_count):
    """Random divide elems into groups."""
    sizes = [elem_count // group_count] * group_count
    prefix = elem_count % group_count
    sizes[:prefix] = [elem_count // group_count + 1] * prefix
    return sizes


def diff_counts_dict(fp1, fp2, only_positive=False):
    """Given two fingerprints, returns difference of their counts dicts.

    Parameters
    ----------
    fp1, fp2 : Fingerprint
        `Fingerprint` objects, `fp2` subtracted from `fp1`.
    only_positive : bool, optional
        Return only positive counts, negative being thresholded to 0.

    Returns
    -------
    counts_diff : dict
        Count indices in either `fp1` or `fp2` with value as diff of counts.

    See Also
    --------
    sum_counts_dict
    """
    counts_diff = fp1.counts.copy()
    for k, v in fp2.counts.items():
        counts_diff[k] = counts_diff.get(k, 0) - v
        if only_positive and counts_diff[k] < 0:
            del counts_diff[k]
    return counts_diff


def de_select_last():
    """(De)select last of visible part of each NURBS

    """
    pass


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

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


def create_headers(user_id, token=None):
    """Return header dict that is needed to talk to the Emby API.

    :param user_id: Emby user ID
    :param token: Authentication token for Emby
    :type user_id: str
    :type token: str
    :returns: Headers for requests
    :rtype: dict
    """
    headers = {}
    authorization = (
        'MediaBrowser UserId="{user_id}", Client="other", Device="beets", DeviceId="beets", Version="0.0.0"'
        .format(user_id=user_id))
    headers['x-emby-authorization'] = authorization
    if token:
        headers['x-mediabrowser-token'] = token
    return headers


@classmethod
def getViewUserPhpName(cls):
    """
        Get the name of the user PHP script, by default 'viewuser.php'
        """
    return 'viewuser.php'


def get_gunicorn_logconfig_dict():
    """
    Get a dict to be used as ``logconfig_dict`` in a Gunicorn config file.
    """
    return {'version': 1, 'disable_existing_loggers': False, 'loggers': {
        'gunicorn.error': {'level': 'NOTSET', 'propagate': True}}}


def do_overlap(start1: int, endex1: int, start2: int, endex2: int) ->bool:
    """Do ranges overlap?

    Arguments:
        start1 (int):
            Inclusive start index of the first range.

        endex1 (int):
            Exclusive end index of the first range.

        start2 (int):
            Inclusive start index of the second range.

        endex2 (int):
            Exclusive end index of the second range.

    Returns:
        bool: Ranges do overlap.

    Note:
        Start and end of each range are sorted before the final comparison.

    Examples:
        >>> do_overlap(0, 4, 4, 8)
        False

        >>> do_overlap(0, 4, 2, 6)
        True

        >>> do_overlap(4, 0, 2, 6)
        True

        >>> do_overlap(8, 4, 4, 0)
        False
    """
    if start1 > endex1:
        start1, endex1 = endex1, start1
    if start2 > endex2:
        start2, endex2 = endex2, start2
    return endex1 > start2 and endex2 > start1


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


def p_newtypedecl(p):
    """newtypedecl : NEWTYPE CONID EQUAL constructor"""
    p[0] = [p[1], [p[2], [p[4]]]]


@staticmethod
def get_attr_on_node(node, xpath, attr_name, default='', namespaces=None):
    """
        获取指定节点的属性值(从节点开始检索)

        @param {Element} node - 开始检索的节点
        @param {string} xpath - - 符合XPath语法的搜索路径
        @param {string} attr_name - 属性名
        @param {string} default='' - 如果找不到节点或具体属性时默认返回的值
        @param {dict} namespaces=None - 命名空间

        @return {string} - 第一个匹配节点的指定属性文本值，如果没有找到匹配节点或属性，返回''
        """
    _nodes = node.xpath(xpath, namespaces=namespaces)
    if len(_nodes) == 0:
        return default
    else:
        return _nodes[0].get(attr_name, default=default)


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def lambd_BOH3_Na_FW86(T, P):
    """n-c: boric-acid sodium [FW86]."""
    lambd = -0.097
    valid = T == 298.15
    return lambd, valid


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

        :param ShowcaseUnresolveCommentDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_unresolve_comment_details', val)


def vslide(vel_1, vel_2):
    """

    Calculate the sliding speed in a tribological contact based on contact body
    velocities.

    Parameters
    ----------
    vel_1: ndarray, scalar
        The contact velocity of body 1.
    vel_2: ndarray, scalar
        The contact velocity of body 2

    Returns
    -------
    vel_slide: ndarray, scalar
        The sliding velocity in the tribological contact.

    """
    vel_slide = vel_1 - vel_2
    return vel_slide


def Kelvin_F(Fahrenheit):
    """Usage: Convert to Kelvin from Fahrenheit
    Kelvin_F(Fahrenheit)"""
    return (Fahrenheit - 32) * 5 / 9 + 273.15


def c_array(ctype, values):
    """Create ctypes array from a python array

    Parameters
    ----------
    ctype : ctypes data type
        data type of the array we want to convert to

    values : tuple or list
        data content

    Returns
    -------
    out : ctypes array
        Created ctypes array
    """
    return (ctype * len(values))(*values)


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


def _line_ranges(statements, lines):
    """Produce a list of ranges for `format_lines`."""
    statements = sorted(statements)
    lines = sorted(lines)
    pairs = []
    start = None
    lidx = 0
    for stmt in statements:
        if lidx >= len(lines):
            break
        if stmt == lines[lidx]:
            lidx += 1
            if not start:
                start = stmt
            end = stmt
        elif start:
            pairs.append((start, end))
            start = None
    if start:
        pairs.append((start, end))
    return pairs


def _ADD_shifted_register(cpu, res_op, reg_op1, reg_op2):
    """
        ADD (shifted register).

        :param res_op: destination register.
        :param reg_op1: source register.
        :param reg_op2: source register.
        """
    cpu._adds_subs_shifted_register(res_op, reg_op1, reg_op2, mnem='add')


def delete_target_group(TargetGroupArn=None):
    """
    Deletes the specified target group.
    You can delete a target group if it is not referenced by any actions. Deleting a target group also deletes any associated health checks.
    See also: AWS API Documentation

    Examples
    This example deletes the specified target group.
    Expected Output:

    :example: response = client.delete_target_group(
        TargetGroupArn='string'
    )

    :type TargetGroupArn: string
    :param TargetGroupArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the target group.

    :rtype: dict
    :return: {}

    """
    pass