def format_time(seconds, nanos):
    """ return float of seconds.nanos when nanos set, or seconds when not """
    if nanos:
        return float(seconds) + float(nanos) / 1000000000.0
    return int(seconds)


def lists_are_the_same(a, b):
    """
    Function that checks if two `lists` have the same elements in the same
    order.

    Returns
    -------
    _lists_are_the_same : `bool`
        ``True`` if the lists are the same.
    """
    if len(a) == len(b):
        for i, j in zip(a, b):
            if i != j:
                return False
        return True
    else:
        return False


def get_query_kwargs(**kwargs):
    """Construct page and page size kwargs (if present)."""
    query_kwargs = {}
    query = kwargs.pop('query')
    if query:
        query_kwargs['query'] = query
    return query_kwargs


def extrude_verts_indiv(mirror: bool=False):
    """Extrude individual vertices only

    :param mirror: Mirror Editing
    :type mirror: bool
    """
    pass


def is_square_matrix(array):
    """ Returns if array is a square matrix """
    return array.shape.ndims == 2 and array.shape[0].value == array.shape[1
        ].value


def role_users(request, role):
    """ Users receive a certain role """
    db = request.db
    if type(role) == str:
        doc = db.doc.find_one({'_id': role}, {'users': 1})
    else:
        doc = db.doc.find_one({'_id': {'$in': role}}, {'users': 1})
    return doc['users'].keys()


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 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 _isascii(string):
    """Tests if a given string is pure ASCII; works for both Python 2 and 3"""
    try:
        return len(string) == len(string.encode())
    except UnicodeDecodeError:
        return False
    except UnicodeEncodeError:
        return False


def load_inputvariablesfile(intputfile):
    """
    Loads inputfile which must be in the bifacial_radiance directory,
    and must be a ``.py`` file with all the variables, and organizes the variables
    into dictionaries that it returns

    Parameters
    ----------
    inputfile : str
        String of a ``.py`` file in the bifacial_radiance directory.

    Returns
    -------
    simulationParamsDict : Dictionary
        Dictionary containing the parameters for performing the simulation,
        including simulation names, and types of sky, fixed or tracked systems:
            ========================  =======  =============================
            variable                   type         Description
            ========================  =======  =============================
            testfolder                str      Path to testfolder
            weatherfile               str      File (with path) to weatherfile
            getEPW                    bool
            simulationname            str      Name for simulation
            moduletype                str      Module name as is / or will be defined in JSON
            rewritemodule             bool     If moduletype exists in JSON, True will rewrite with new parameters
            cellLevelmodule           bool
            axisofrotationtorquetube  bool
            torqueTube                bool
            hpc                       bool
            tracking                  bool
            cumulativesky             bool
            daydateSimulation         bool
            timeIndexSimulation  bool
            ========================  =======  =============================
    sceneParamsDict : Dictionary
        gcrorpitch, gcr, pitch, albedo, nMods, nRows,
        hub_height, clearance_height, azimuth, hub_height, axis_Azimuth
    timeControlParamsDict : Dictionary
        hourstart, hourend, daystart, dayend, monthstart, monthend,
        timestampstart, timestampend,
    moduleParamsDict : Dictionary
        numpanels, x, y, bifi, xgap, ygap, zgap
    cellLevelModuleParamsDict : Dictionary
        numcellsx, numcellsy, xcell, ycell, xcellgap, ycellgap
    trackingParamsDict : Dictionary
        backtrack, limit_angle,angle_delta
    torquetubeParamsDict : Dictionary
         diameter, tubetype, torqueTubeMaterial
    analysisParamsDict : Dictionary
        sensorsy, modWanted, rowWanted
    """
    import inputfile as ibf
    simulationParamsDict = {'testfolder': ibf.testfolder, 'epwfile': ibf.
        epwfile, 'simulationname': ibf.simulationname, 'moduletype': ibf.
        moduletype, 'rewriteModule': ibf.rewriteModule, 'cellLevelModule':
        ibf.cellLevelModule, 'axisofrotationTorqueTube': ibf.
        axisofrotationTorqueTube, 'torqueTube': ibf.torqueTube}
    simulationControlDict = {'fixedortracked': ibf.fixedortracked,
        'cumulativeSky': ibf.cumulativeSky, 'timestampSimulation': ibf.
        timestampSimulation, 'timeIndexSimulation': ibf.timeIndexSimulation,
        'hpc': ibf.hpc, 'daydateSimulation': ibf.dayDateSimulation,
        'singleKeySimulation': ibf.singleKeySimulation,
        'singleKeyRangeSimulation': ibf.singleKeyRangeSimulation}
    timeControlParamsDict = {'timestampstart': ibf.timestampstart,
        'timestampend': ibf.timestampend, 'startdate': ibf.startdate,
        'enddate': ibf.enddate, 'singlekeystart': ibf.singlekeystart,
        'singlekeyend': ibf.singlekeyend, 'day_date': ibf.daydate}
    moduleParamsDict = {'numpanels': ibf.numpanels, 'x': ibf.x, 'y': ibf.y,
        'bifi': ibf.bifi, 'xgap': ibf.xgap, 'ygap': ibf.ygap, 'zgap': ibf.zgap}
    sceneParamsDict = {'gcr': ibf.gcr, 'pitch': ibf.pitch, 'albedo': ibf.
        albedo, 'nMods': ibf.nMods, 'nRows': ibf.nRows, 'azimuth': ibf.
        azimuth_ang, 'tilt': ibf.tilt, 'clearance_height': ibf.
        clearance_height, 'hub_height': ibf.hub_height, 'axis_azimuth': ibf
        .axis_azimuth}
    trackingParamsDict = {'backtrack': ibf.backtrack, 'limit_angle': ibf.
        limit_angle, 'angle_delta': ibf.angle_delta}
    torquetubeParamsDict = {'diameter': ibf.diameter, 'tubetype': ibf.
        tubetype, 'torqueTubeMaterial': ibf.torqueTubeMaterial}
    analysisParamsDict = {'sensorsy': ibf.sensorsy, 'modWanted': ibf.
        modWanted, 'rowWanted': ibf.rowWanted}
    cellLevelModuleParamsDict = {'numcellsx': ibf.numcellsx, 'numcellsy':
        ibf.numcellsy, 'xcell': ibf.xcell, 'ycell': ibf.ycell, 'xcellgap':
        ibf.xcellgap, 'ycellgap': ibf.ycellgap}
    return (simulationParamsDict, simulationControlDict,
        timeControlParamsDict, moduleParamsDict, cellLevelModuleParamsDict,
        sceneParamsDict, trackingParamsDict, analysisParamsDict)


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

        :param SharePathError val:
        :rtype: ShareFolderErrorBase
        """
    return cls('bad_path', val)


def _convert_round(builder, node, graph, err):
    """
    convert to CoreML Round Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L5029
    """
    builder.add_round(name=node.name, input_name=node.inputs[0],
        output_name=node.outputs[0])


def compare_floats(float1, float2, f_error=0.01, zero_tolerance=1e-08,
    inf_tolerance=1e+80):
    """
    Compare two numeric objects according to the following algorithm:

    1. If float1 < zero_tolerance and float2 < zero_tolerance, then returns True.
    2. If abs(float1) > inf_tolerance and abs(float2) > inf_tolerance, and
       sign(float1) = sign(float2), then returns True.
    3. If zero_tolerance < abs(float1, float2) < inf_tolerance, and
       2*abs(float1 - float2)/(abs(float1) + abs(float2)) <= f_error, return True.
    4. Otherwise, return False.

    :param float1: First numeric field.
    :param float2: Second numeric field.

    :param f_error: Fractional margin of error (default: 0.01)
    :param zero_tolerance: Zero tolerance (default: 1e-8)
    :param inf_tolerance: Infinite tolerance (default: 1e80)
    """
    if abs(float1) < zero_tolerance and abs(float2) < zero_tolerance:
        return True
    elif abs(float1) > inf_tolerance and abs(float2) > inf_tolerance:
        if float1 / float2 > 0:
            return True
        else:
            return False
    elif 2 * abs(float1 - float2) / (abs(float1) + abs(float2)) <= f_error:
        return True
    else:
        return False


def inplace_identity_derivative(Z, delta):
    """Apply the derivative of the identity function: do nothing.

    Parameters
    ----------
    Z : {array-like, sparse matrix}, shape (n_samples, n_features)
        The data which was output from the identity activation function during
        the forward pass.

    delta : {array-like}, shape (n_samples, n_features)
         The backpropagated error signal to be modified inplace.
    """


def ep_ping():
    """Check service availability.

    """
    return 'pong'


def _is_crumb_arg(crumb_arg: str) ->bool:
    """ Return True if `crumb_arg` is a well formed crumb argument, i.e.,
    is a string that starts with `start_sym` and ends with `end_sym`.
    False otherwise.
    """
    if not isinstance(crumb_arg, str):
        return False
    start_sym, end_sym = '{', '}'
    return crumb_arg.startswith(start_sym) and crumb_arg.endswith(end_sym)


def adjustPhyLengthToFirst(ImageA, ImageB):
    """
    Adjust physical length (such as fps to meter per pixel etc) to first image
    !!!Warning: editing input class!!!
    """
    ImageB.dimlen = ImageA.dimlen[:]
    return


@classmethod
def _pre_delete_hook(cls, key):
    """
        Removes instance from index.
        """
    if cls.searching_enabled:
        doc_id = cls.search_get_document_id(key)
        index = cls.search_get_index()
        index.delete(doc_id)


def search(term, corpora):
    """Find all sources that have a given term in them"""
    term = term.upper()
    for corpus in corpora:
        for speaker, content, audio_filename, mfcc in corpus.mfcc_utterances():
            if term in content.upper():
                yield speaker, content, audio_filename, mfcc


@staticmethod
def identify(pattern):
    """Returns pattern category.

        :param pattern: normalized pattern.
        Identify if a pattern is fullpath, basename or extension
        and returns the appropriate type.
        """
    if pattern.startswith('RE:') or '/' in pattern:
        return 'fullpath'
    elif pattern.startswith('*.'):
        return 'extension'
    else:
        return 'basename'


def remove():
    """Delete current cache

    """
    pass


@classmethod
def create_flavor(cls, name, description, service_type):
    """Wrapper utility that returns a test flavor."""
    body = cls.admin_client.create_flavor(description=description,
        service_type=service_type, name=name)
    flavor = body['flavor']
    cls.flavors.append(flavor)
    return flavor


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


def subscope(paths, language):
    """
    Download subtitles for multiple video files via subscope script.

    NOTE: Runs subscope via shell to support Python 2 version of subscope
          (and the Python 3 version has issues)
    """
    from subsystem.subsystem import multithreader
    multithreader(['subscope', '-l', language], paths)


def fill(use_beauty: bool=True):
    """Fill a selected edge loop with faces

    :param use_beauty: Beauty, Use best triangulation division
    :type use_beauty: bool
    """
    pass


@staticmethod
def _default_next_colour(particle):
    """
        Default next colour implementation - linear progression through
        each colour tuple.
        """
    return particle.colours[(len(particle.colours) - 1) * particle.time //
        particle.life_time]


@classmethod
def line_tag_remove(cls, string, symbol_or_re, is_re=False, delimiters=None):
    """Remove tagged lines.

        Default tag delimiters are :attr:`line_delimiters`.

        >>> tpl = AdHoc.get_named_template("col-param-closure")

        .. >>> printf(str(AdHoc.line_tag_remove(tpl, "adhoc_run_time_section")))
        """
    transform = lambda blob: ''
    return cls.transform_lines(transform, string, symbol_or_re, is_re,
        delimiters)


def walk(root, depthfirst=False, error_handler=None):
    """Walk the directory tree starting from root, optionally ignoring
    access errors.

    :param root: anything accepted by :func:`dir`
    :param depthfirst: passed to :meth:`Dir.walk`
    :param error_handler: passed to :meth:`Dir.walk`
    :returns: as :meth:`Dir.walk`
    """
    return dir(root).walk(depthfirst=depthfirst, error_handler=error_handler)


def set_attr_filter(target, key, value):
    """
    Jinja2 filter that sets an attribute of an object.
    """
    target[key] = value
    return target


def value_for_keypath(dict, keypath):
    """
    Returns the value of a keypath in a dictionary
    if the keypath exists or None if the keypath
    does not exist.
    """
    if len(keypath) == 0:
        return dict
    keys = keypath.split('.')
    value = dict
    for key in keys:
        if key in value:
            value = value[key]
        else:
            return None
    return value


@classmethod
def from_circuits(cls, label: str, circuits: dict):
    """Circuit creation method that takes multiple circuits (templates or instances of `CircuitIR`) as inputs to
        create one larger circuit out of these. With additional `connectivity` information, these circuit can directly
        be interlinked.

        Parameters
        ----------
        label
            Name of new circuit. Should not collide with any circuit label given in `circuits`.
        circuits
            Dictionary with unique circuit labels as keys and circuits as items. Circuits may either be instances of
            `CircuitTemplate` or `CircuitIR`. Alternatively, a circuit template may also be given via a sub-dictionary
            with keys `template` and `values`, where `values` is a dictionary of variable value updates for the given
            template.

        Returns
        -------
        circuit
            instance of `CircuitIR`
        """
    circuit = cls(label, nodes={}, edges=[])
    for name, circ in circuits.items():
        circuit.add_circuit(name, circ)
    return circuit


def no_spaces(field):
    """Validates that there are no spaces in a string

    Args:
        field:str
    Returns:
        returns Boolean
    """
    if (' ' in field) == True:
        return False
    else:
        return True


@staticmethod
def _get_common_data_template():
    """ Data for tool specific """
    data_template = {'includes': [], 'linker_file': '', 'macros': [],
        'sources': []}
    return data_template


def validate_string(s):
    """
    Check input has length and that length > 0

    :param s:
    :return: True if len(s) > 0 else False
    """
    try:
        return len(s) > 0
    except TypeError:
        return False


def configure(conf):
    """
	Configuration for gcc
	"""
    conf.find_gcc()
    conf.find_ar()
    conf.gcc_common_flags()
    conf.gcc_modifier_platform()
    conf.cc_load_tools()
    conf.cc_add_flags()
    conf.link_add_flags()
    conf.check_gcc_o_space()


def derive_resource_name(name):
    """A stable, human-readable name and identifier for a resource."""
    if name.startswith('Anon'):
        name = name[4:]
    if name.endswith('Handler'):
        name = name[:-7]
    if name == 'Maas':
        name = 'MAAS'
    return name


def avg(generator_expression):
    """Return the average of the numbers listed in @generator_expression."""
    l = list(generator_expression)
    return sum(l) / len(l) if l else 0


@classmethod
def _from_dict(cls, _dict):
    """Initialize a TableHeaders object from a json dictionary."""
    args = {}
    if 'cell_id' in _dict:
        args['cell_id'] = _dict.get('cell_id')
    if 'location' in _dict:
        args['location'] = _dict.get('location')
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    if 'row_index_begin' in _dict:
        args['row_index_begin'] = _dict.get('row_index_begin')
    if 'row_index_end' in _dict:
        args['row_index_end'] = _dict.get('row_index_end')
    if 'column_index_begin' in _dict:
        args['column_index_begin'] = _dict.get('column_index_begin')
    if 'column_index_end' in _dict:
        args['column_index_end'] = _dict.get('column_index_end')
    return cls(**args)


def FindAtomIndexByIDs(atomData, loc, IDs, Draw=True):
    """finds the set of atom array indices for a list of atom IDs. Will search
    either the Atom table or the drawAtom table.

    :param list atomData: Atom or drawAtom table containting coordinates, etc.
    :param int loc: location of atom id in atomData record
    :param list IDs: atom IDs to be found
    :param bool Draw: True if drawAtom table to be searched; False if Atom table
      is searched

    :returns: list indx: atom (or drawAtom) indices

    """
    indx = []
    for i, atom in enumerate(atomData):
        if Draw and atom[loc] in IDs:
            indx.append(i)
        elif atom[loc] in IDs:
            indx.append(i)
    return indx


def quote(value):
    """
    Encapsulates `value` in double-quotes and coerces it into a string, if
    necessary.
    """
    return '"%(value)s"' % {'value': str(value)}


@classmethod
def get_resources(cls):
    """Returns Ext Resources."""
    return []


def createMainWidget(argv):
    """
    Function to create the main widget.

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from SqlBrowser.SqlBrowser import SqlBrowser
    if len(argv) > 1:
        connections = argv[1:]
    else:
        connections = []
    browser = SqlBrowser(connections)
    return browser


def SizeExpsOther(t):
    """Other expenses per policy at time t"""
    return 0


def cancel_conversion_task(DryRun=None, ConversionTaskId=None,
    ReasonMessage=None):
    """
    Cancels an active conversion task. The task can be the import of an instance or volume. The action removes all artifacts of the conversion, including a partially uploaded volume or instance. If the conversion is complete or is in the process of transferring the final disk image, the command fails and returns an exception.
    For more information, see Importing a Virtual Machine Using the Amazon EC2 CLI .
    See also: AWS API Documentation

    :example: response = client.cancel_conversion_task(
        DryRun=True|False,
        ConversionTaskId='string',
        ReasonMessage='string'
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type ConversionTaskId: string
    :param ConversionTaskId: [REQUIRED]
            The ID of the conversion task.

    :type ReasonMessage: string
    :param ReasonMessage: The reason for canceling the conversion task.

    """
    pass


def _shallow_annotate(element, annotations):
    """Annotate the given ClauseElement and copy its internals so that
    internal objects refer to the new annotated object.

    Basically used to apply a "dont traverse" annotation to a
    selectable, without digging throughout the whole
    structure wasting time.
    """
    element = element._annotate(annotations)
    element._copy_internals()
    return element


def is_valid_name(name):
    """Returns True if name is a valid package name, else False."""
    if name != name.strip():
        return False
    if name in ('package', 'packages'):
        return False
    return True


def is_anonymized(pnr):
    """Returns True iff the pnr has been anonymized.
    """
    return pnr[0] == '9'


@classmethod
def _get_base_vectors(cls, base):
    """Get unit vectors and scale factors from base.

        Parameters
        ----------
        base : instance of ``self.base_representation``
            The points for which the unit vectors and scale factors should be
            retrieved.

        Returns
        -------
        unit_vectors : dict of `CartesianRepresentation`
            In the directions of the coordinates of base.
        scale_factors : dict of `~astropy.units.Quantity`
            Scale factors for each of the coordinates

        Raises
        ------
        TypeError : if the base is not of the correct type
        """
    cls._check_base(base)
    return base.unit_vectors(), base.scale_factors()


def create_application(applicationName=None):
    """
    Creates an application.
    See also: AWS API Documentation

    :example: response = client.create_application(
        applicationName='string'
    )

    :type applicationName: string
    :param applicationName: [REQUIRED]
            The name of the application. This name must be unique with the applicable IAM user or AWS account.

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

    """
    pass


def total_file_count(path):
    """Returns total number of files under specified path.

    The path should be a pathlib.Path instance referring to a file
    or directory. For a file this will return 1. Directories will be
    traversed recursively.
    """
    if path.is_file():
        return 1
    return sum(1 for child in path.glob('**/*') if child.is_file())


def get_schema_dict(name, method, all_task_schemas, software_instance=None):
    """Get the schema associated with the method/implementation of this task."""
    match_task_idx = None
    match_method_idx = None
    match_imp_idx = None
    for task_ref_idx, task_ref in enumerate(all_task_schemas):
        if task_ref['name'] == name:
            match_task_idx = task_ref_idx
            for met_idx, met in enumerate(task_ref['methods']):
                if met['name'] == method:
                    match_method_idx = met_idx
                    implementations = met.get('implementations')
                    if implementations:
                        for imp_idx, imp in enumerate(implementations):
                            if imp['name'] == software_instance['name']:
                                match_imp_idx = imp_idx
                                break
                    break
            break
    if match_task_idx is None:
        msg = f'No matching task found with name: "{name}"'
        raise ValueError(msg)
    if match_method_idx is None:
        msg = (
            f'No matching method found with name: "{method}" in task: "{name}""'
            )
        raise ValueError(msg)
    task_ref = all_task_schemas[match_task_idx]
    met_ref = task_ref['methods'][met_idx]
    inputs = task_ref.get('inputs', []) + met_ref.get('inputs', [])
    outputs = task_ref.get('outputs', []) + met_ref.get('outputs', [])
    imp_ref = None
    in_map = None
    out_map = None
    command_opt = None
    if match_imp_idx is not None:
        imp_ref = met_ref['implementations'][match_imp_idx]
        inputs += imp_ref.get('inputs', [])
        outputs += imp_ref.get('outputs', [])
        in_map = imp_ref.get('input_map', [])
        out_map = imp_ref.get('output_map', [])
        command_opt = imp_ref.get('commands', [])
    outputs = list(set(outputs))
    if software_instance:
        implementation = software_instance['name']
        command_group = {'commands': command_opt, 'env_pre':
            software_instance.get('env_pre'), 'env_post': software_instance
            .get('env_post')}
    else:
        implementation = None
        command_group = None
    schema_dict = {'name': name, 'method': method, 'implementation':
        implementation, 'inputs': inputs, 'outputs': outputs, 'input_map':
        in_map, 'output_map': out_map, 'command_group': command_group}
    return schema_dict


def too_few_otus(tree, threshold):
    """
    Return true if the provided tree node object have fewer OTUs than the
    provided threshold.

    Parameters
    ----------
    tree : TreeNode object
        The tree you wish to consider.
    threshold : int
        Minimum number of OTUs allowed in the provided tree.

    Returns
    -------
    True or False
        True if the tree contains to few OTUs.
    """
    return len(set(tree.iter_otus())) < threshold


@classmethod
def _has_start(cls, s):
    """
        Tests if the first codon is the START codon, assumes uppercase
        """
    return s[0:3] == 'ATG'


def create_search_group(recordset=None, field=None, values=None,
    criteria_operator='EqualTo'):
    """
    Create a Coalesce search group/filter object (the value of "group" in a
    `Coalesce search request object
    <https://github.com/InCadence/coalesce/wiki/REST-API#search-query-data-format>`_)
    that combines all entered values for a given field, either including or
    excluding (depending on the value of "criteria_operator") all records
    matching any of the supplied values.

    :param recordset:  the (:class:`str`) recordset of the field to be
        search on
    :param field:  the (:class:`str`) field to be searched on
    :param values:  a :class:`list` or list-like of values to search for.
        The values themselves should be of simple, JSON-serializable types
        (e.g., strings, numbers, Boolean).
    :param criteria_operator:  "EqualTo", if the search is to *include*
        a record matching *any* element of "values", or "NotEqualTo", if
        the search is to *exclude all* records matching *any* element of
        "values".

    :returns:  a Coalesce search group as a :class:`dict`, or ``None`` if
        "values" is empty

    """
    if not isinstance(recordset, str):
        raise TypeError('Please supply a recordset as a string.')
    if not isinstance(field, str):
        raise TypeError('Please supply a field to search on, as a string.')
    values_error_msg = ('Please supply a list or list-like of values to ' +
        'search for.')
    if not values:
        raise TypeError(values_error_msg)
    elif isinstance(values, str):
        raise TypeError(values_error_msg)
    else:
        try:
            values[0]
        except:
            raise TypeError(values_error_msg)
    if criteria_operator == 'EqualTo':
        group_operator = 'OR'
    elif criteria_operator == 'NotEqualTo':
        group_operator = 'AND'
    else:
        raise ValueError('The value of "criteria_operator" must be either ' +
            '"EqualTo" or "NotEqualTo".')
    criteria = []
    for value in values:
        criteria_set = {'recordset': recordset, 'field': field, 'operator':
            criteria_operator, 'value': value, 'matchCase': False}
        criteria.append(criteria_set)
    if len(criteria) > 0:
        group = {'operator': group_operator, 'criteria': criteria}
    else:
        group = None
    return group


def _group_records_for_split(record_gen, split_size, reducer_key=None):
    """Helper for _split_records()."""
    split_num = 0
    bytes_in_split = 0
    last_key_value = None
    for record in record_gen:
        same_key = False
        if reducer_key:
            key_value = reducer_key(record)
            same_key = key_value == last_key_value
            last_key_value = key_value
        if bytes_in_split >= split_size and not same_key:
            split_num += 1
            bytes_in_split = 0
        yield split_num, record
        bytes_in_split += len(record)


@staticmethod
def to_delisle(romer):
    """ Convert romer to delisle """
    return (60 - romer) * 20 / 7


@staticmethod
def replaceNode(oldNode, newNode):
    """
        Replace instance of Nonterminal or Terminal in the tree with another one.
        :param oldNode: Old nonterminal or terminal already in the tree.
        :param newNode: Instance of nonterminal or terminal to replace with.
        :return: Instance `newNode` in the tree.
        """
    if oldNode.from_rule is not None and len(oldNode.from_rule.to_symbols) > 0:
        indexParent = oldNode.from_rule.to_symbols.index(oldNode)
        oldNode.from_rule.to_symbols[indexParent] = newNode
        newNode._set_from_rule(oldNode.from_rule)
    if oldNode.to_rule is not None and len(oldNode.to_rule.from_symbols) > 0:
        indexChild = oldNode.to_rule.from_symbols.index(oldNode)
        oldNode.to_rule._from_symbols[indexChild] = newNode
        newNode._set_to_rule(oldNode.to_rule)
    return newNode


def iscensored(rev):
    """Return whether a revision's content has been censored."""


@classmethod
def reset_instance(cls, *args, **kwargs):
    """
        Completely resets the instance of the class
        (representing the singleton), makes a new one and
        returns this instance.
        """
    cls._instance = None
    cls._instance = cls(*args, **kwargs)
    return cls._instance


def total_msgs(xml):
    """count total number of msgs"""
    count = 0
    for x in xml:
        count += len(x.message)
    return count


def x_offset_gff(GFFParseobj, x_offset):
    """Takes in a gff object (a gff file parsed as a pandas dataframe),
    and an x_offset value and shifts the start, stop, center, lmost, and rmost.

    Returns a GFFParse object with the shifted values in GFFParse.features.
    """
    for columnname in ['start', 'stop', 'center', 'lmost', 'rmost']:
        GFFParseobj.features[columnname] = GFFParseobj.features[columnname
            ] + x_offset
    return GFFParseobj


def oddEven(num):
    """returns 1 if num is even, returns -1 if num is odd"""
    if num % 2:
        return -1
    return 1


def get_has_been_seen(request):
    """Return ``True`` if the request has the ``has_been_seen_before`` cookie.

          >>> from mock import Mock
          >>> mock_request = Mock()

      False if the request doesn't have the cookie::

          >>> mock_request.cookies = {}
          >>> get_has_been_seen(mock_request)
          False

      True if the request does::

          >>> mock_request.cookies = {'has_been_seen_before': 'true'}
          >>> get_has_been_seen(mock_request)
          True

    """
    return bool(request.cookies.get('has_been_seen_before', False))


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


@classmethod
def from_js_error(cls, js_error):
    """Convert a JSON Schema ValidationError instance into a
        ValidationError instance.
        """
    e = cls()
    e.path = list(getattr(js_error, 'releative_path', js_error.path))
    e.message = js_error.message
    e.validator = js_error.validator
    e.validator_value = js_error.validator_value
    e.raw = js_error._contents()
    return e


def psi_Mnjj_Na_Cl_PK74(T, P):
    """c-c'-a: manganese(II) sodium chloride [PK74]."""
    psi = -0.003
    valid = T == 298.15
    return psi, valid


def overlapping_bb(bb1, bb2):
    """
	Check whether the two given bounding boxes overlap.

	:param bb1: The first bounding box.
	:type bb1: :class:`matplotlib.transforms.Bbox`
	:param bb2: The second bounding box.
	:type bb2: :class:`matplotlib.transforms.Bbox`

	:return: A boolean indicating whether the two bounding boxes overlap.
	:rtype: bool
	"""
    return (bb2.x0 < bb1.x0 < bb2.x1 or bb2.x0 < bb1.x1 < bb2.x1) and (bb2.
        y0 < bb1.y0 < bb2.y1 or bb2.y0 < bb1.y1 < bb2.y1) or (bb1.x0 < bb2.
        x0 < bb1.x1 or bb1.x0 < bb2.x1 < bb1.x1) and (bb1.y0 < bb2.y0 < bb1
        .y1 or bb1.y0 < bb2.y1 < bb1.y1)


def copy():
    """Undocumented contribute <https://developer.blender.org/T51061>

    """
    pass


def is_hybi00(headers):
    """
    Determine whether a given set of headers is HyBi-00-compliant.

    Hixie-76 and HyBi-00 use a pair of keys in the headers to handshake with
    servers.
    """
    return 'Sec-WebSocket-Key1' in headers and 'Sec-WebSocket-Key2' in headers


@classmethod
def _split_strip(cls, line):
    """
        Separate the -p<num> option from the patch name

        >>> PatchSeries._split_strip("asdf -p1")
        ('asdf', 1)
        >>> PatchSeries._split_strip("a/nice/patch")
        ('a/nice/patch', None)
        >>> PatchSeries._split_strip("asdf foo")
        ('asdf foo', None)
        """
    patch = line
    strip = None
    split = line.rsplit(None, 1)
    if len(split) > 1:
        m = cls.level_re.match(split[1])
        if m:
            patch = split[0]
            strip = int(m.group('level'))
    return patch, strip


def project_edit():
    """Edit a snapshot of the view-port in an external image editor

    """
    pass


def palettecolor_isolate(affect_visibility: bool=False):
    """Toggle whether the active color is the only one that is editable and/or visible

    :param affect_visibility: Affect Visibility, In addition to toggling the editability, also affect the visibility
    :type affect_visibility: bool
    """
    pass


def _hls_seg_ext(hls):
    """
    @TODO: add documentation
    """
    return 'm4s' if hls.options.get('hls_segment_type', '') == 'fmp4' else 'ts'


@staticmethod
def _extract_address(bitcoin_url):
    """
        Extract address from bitcoin url
        :param bitcoin_url: bitcoin url
        :return: Bitcoin address
        """
    address_text, _ = bitcoin_url.split('?')
    address = address_text.split(':')[1]
    return address


def _calc_bar_width(width):
    """
    Calculate width (in points) of bar plot from figure width (in inches).
    """
    if width <= 7:
        bar_width = width * 3.35
    elif width <= 9:
        bar_width = width * 2.6
    elif width <= 10:
        bar_width = width * 2.1
    else:
        bar_width = width * 1.2
    return bar_width


def validate_format(*_arg):
    """
    This method can be overridden with format validation logic.
    """
    return True


def soy(date, offset=0):
    """
    Returns the start of the year at a given offset
    """
    return type(date)(date.year + offset, 1, 1)


def enable_evaluation():
    """
    Enable Add, Mul and Pow contractions
    """
    global _evaluate
    _evaluate = True


@staticmethod
def _decode_array(payload: str, elements: dict) ->list:
    """
        Maps the elements of an array present in the payload string

        Args:
            payload (str): An influx WM message
            elements (dict): A dictionary of elements to look for

        Returns:
            An array with named fields as dictionary
        """
    payload = payload.replace('[', '').replace(']', '')
    payload = payload.split(',')
    array = list()
    target = dict()
    for entry in payload:
        values = entry.split(':')
        for _type, _convertion in elements.items():
            if _type in values[0]:
                target[_type] = _convertion['base'](''.join(filter(lambda c:
                    c not in "{}'", values[1])))
                break
        if len(target.keys()) == len(elements.keys()):
            array.append(target.copy())
            target = dict()
    return array


def valid_url(url):
    """
    Validate a URL and make sure that it has the correct URL syntax.

    Args:
        url (str): URL string to be evaluated.

    Returns:
        True if the URL is valid. False if it is invalid.
    """
    if 'http://' not in url and 'https://' not in url:
        return False
    return True


def LSTM(lstm, inputs, batch_size=None, dropout_x=0.0, dropout_h=0.0):
    """
    unidirectional LSTM
    :param lstm: one LSTM layer
    :param inputs: # seq_len x batch_size
    :param batch_size:
    :param dropout_x:
    :param dropout_h:
    :return: Output of LSTM layer, seq_len x hidden_dim x batch_size
    """
    s = lstm.initial_state()
    lstm.set_dropouts(dropout_x, dropout_h)
    if batch_size is not None:
        lstm.set_dropout_masks(batch_size)
    hs = s.add_inputs(inputs)
    return hs


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def provider_parser(subparser):
    """Configure provider parser for Zeit"""
    subparser.description = """
        Zeit Provider requires a token to access its API.
        You can generate one for your account on the following URL:
        https://zeit.co/account/tokens"""
    subparser.add_argument('--auth-token', help='specify your API token')


def p_compound_stmt_7(p):
    """compound_stmt : classdef"""
    p[0] = [p[1]]


def compute_scores_on_distance_measure(first_data, memento_data,
    distance_function):
    """Calculates the distance between scores for those measures that use
    functions from the distance library.
    """
    score = None
    if len(memento_data) == 0:
        if len(first_data) == 0:
            score = 0
        else:
            score = distance_function(first_data, memento_data)
    else:
        score = distance_function(first_data, memento_data)
    return score


def iter_slices(string, slice_length):
    """Iterate over slices of a string."""
    pos = 0
    if slice_length is None or slice_length <= 0:
        slice_length = len(string)
    while pos < len(string):
        yield string[pos:pos + slice_length]
        pos += slice_length


def historical_player_salary_values(html_text):
    """ historical_player_salary_values returns a dictionary of
    salary information keyed by Hoopshype player ID

    @param **html_text** (*str*): String of the HTML response
    from a Hoopshype team URL

    Returns:

        **player_salaries** (*dict*): Dictionary keyed by Hoopshype
            player ID with a list of salary and inflation-adjusted
            salary (followed by player salary URL) as values
    """
    value_str = 'data-value="'
    option_str = 'style="'
    player_salaries = {}
    url_val = html_text.find('Totals	')
    while url_val < total_val:
        player_list = []
        start_ind = html_text.find('<a')
        end_ind = html_text.find('')
        play_key = html_text[start_ind + 2:end_ind]
        play_key = play_key[play_key.find('href="') + 6:play_key.find('">\n')]
        player_key = play_key.split('/')[-3]
        html_text = html_text[end_ind + 4:]
        for col_count in range(0, 2):
            start_ind = html_text.find(option_str) + len(option_str)
            end_ind = html_text.find('" ')
            html_text = html_text[end_ind + 2:]
            start_ind = html_text.find(value_str) + len(value_str)
            end_ind = html_text.find('">')
            try:
                salary_value = int(html_text[start_ind:end_ind])
            except:
                salary_value = 0
            player_list.append(salary_value)
            html_text = html_text[end_ind + 2:]
        player_list.append(play_key)
        player_salaries[player_key] = {}
        player_salaries[player_key]['salary'] = player_list
        total_val = html_text.find('class="name">Totals	')
        url_val = html_text.find('<a')
    return player_salaries


def _get_consecutive_portions_of_front(front):
    """
    Yields lists of the form [(f, s), (f, s)], one at a time from the given front (which is a list of the same form),
    such that each list yielded is consecutive in frequency.
    """
    last_f = None
    ls = []
    for f, s in front:
        if last_f is not None and f != last_f + 1:
            yield ls
            ls = []
        ls.append((f, s))
        last_f = f
    yield ls


def linear_annuity_mapping_fprime(underlying, alpha0, alpha1):
    """linear_annuity_mapping_fprime
    first derivative of linear annuity mapping function.
    See :py:func:`linear_annuity_mapping_func`.
    The function calculates following formula:

    .. math::
        \\alpha^{\\prime}(S) := \\alpha_{0.}

    where
    :math:`S` is underlying,
    :math:`\\alpha_{0}` is alpha0.

    :param float underlying:
    :param float alpha0:
    :param float alpha1: not used.
    :return: value of first derivative of linear annuity mapping function.
    :rtype: float.
    """
    return alpha0


def rip_edge_move(MESH_OT_rip_edge=None, TRANSFORM_OT_translate=None):
    """Extend vertices and move the result

    :param MESH_OT_rip_edge: Extend Vertices, Extend vertices along the edge closest to the cursor
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def get_gcd(a, b):
    """Return greatest common divisor for a and b."""
    while a:
        a, b = b % a, a
    return b


def identify_two_list_duplicates(item1_list, item2_list):
    """Identify duplicate items between two lists.

    :param item1_list: The first input list to be checked.
    :type item1_list: list
    :param item2_list: The second input list to be checked.
    :type item2_list: list
    :returns:
        The set of non-unique/duplicated items between the two lists
        (but not duplicate items within each list).
    :rtype: set
    """
    item1_set = set(item1_list)
    item2_set = set(item2_list)
    item3_set = item1_set & item2_set
    return item3_set


def p_head(p):
    """uag_ref  : UAG  '(' string_list ')'
       hag_ref  : HAG  '(' string_list ')'
       calc_head : CALC '(' STRING ')'
    """
    p[0] = p[1], p[3]


def make_move(moving_area, new_label, labels):
    """
    Modify the `labels` argument in place (no return value!) such that the
    area `moving_area` has the new region label `new_label`.

    Parameters
    ----------
    moving_area :
        The area to be moved (assigned to a new region).
    new_label : `int`
        The new region label of area `moving_area`.
    labels : :class:`numpy.ndarray`
        Each element is a region label of the area corresponding array index.

    Examples
    --------
    >>> import numpy as np
    >>> labels = np.array([0, 0, 0, 0, 1, 1])
    >>> make_move(3, 1, labels)
    >>> (labels == np.array([0, 0, 0, 1, 1, 1])).all()
    True
    """
    labels[moving_area] = new_label


def strip_html(text):
    """ strip html code. """
    if text.startswith('http'):
        return text
    import bs4
    soup = bs4.BeautifulSoup(text, 'lxml')
    res = ''
    for chunk in soup.findAll(text=True):
        if isinstance(chunk, bs4.CData):
            res += str(chunk.content[0]) + ' '
        else:
            res += str(chunk) + ' '
    return res


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

        :param MemberSpaceLimitsChangePolicyType val:
        :rtype: EventType
        """
    return cls('member_space_limits_change_policy', val)


def parse_bip32_path(path):
    """Takes bip32 path, "m/0'/2H" or "m/0H/1/2H/2/1000000000.pub", returns list of ints """
    path = path.lstrip('m/').rstrip('.pub')
    if not path:
        return []
    patharr = []
    for v in path.split('/'):
        if not v:
            continue
        elif v[-1] in "'H":
            v = int(v[:-1]) | 2147483648
        else:
            v = int(v) & 2147483647
        patharr.append(v)
    return patharr


@classmethod
def init_cli(cls):
    """Initialize swipl if it was not initialized yet"""
    from . import Trial
    if not cls.prolog_cli:
        from pyswip import Prolog
        cls.prolog_cli = Prolog()
        cls.prolog_cli.assertz(Trial.prolog_description.empty()[:-1])
        cls.prolog_cli.assertz('load_rules(0)')


def _rewrite(s, sRepl, iGroup, m, bUppercase):
    """text processor: write sRepl in s at iGroup position"""
    nLen = m.end(iGroup) - m.start(iGroup)
    if sRepl == '*':
        sNew = ' ' * nLen
    elif sRepl == '>' or sRepl == '_' or sRepl == '~':
        sNew = sRepl + ' ' * (nLen - 1)
    elif sRepl == '@':
        sNew = '@' * nLen
    elif sRepl[0:1] == '=':
        sNew = globals()[sRepl[1:]](s, m)
        sNew = sNew + ' ' * (nLen - len(sNew))
        if bUppercase and m.group(iGroup)[0:1].isupper():
            sNew = sNew.capitalize()
    else:
        sNew = m.expand(sRepl)
        sNew = sNew + ' ' * (nLen - len(sNew))
    return s[0:m.start(iGroup)] + sNew + s[m.end(iGroup):]


@classmethod
def names(cls):
    """Implement :meth:`~.solver.Solver.names`."""
    return 'mskfsn', 'MOSEK (Fusion)', 'MOSEK via Fusion API'


def DirectionalCoupler(ports):
    """DirectionalCoupler
    Directional Coupler
    @param ports integer number of ports (3 or 4)
    @return s-parameter matrix of a three or four port directional coupler
    port 1 and 2 are a thru connection.

    port 3 picks off the wave going from port 1 to 2.

    port 4 (optional) picks off the wave going from port 2 to port 1.

    @note the directional coupler is completely ideal and is not passive
    in that the picked off wave is an exact copy of the wave going between
    the ports specified above.
    """
    if ports == 3:
        return [[0, 1, 0], [1, 0, 0], [1, 0, 0]]
    elif ports == 4:
        return [[0, 1, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0]]


def getBlockParams(ws, use_head_block=False):
    """ Auxiliary method to obtain ``ref_block_num`` and
        ``ref_block_prefix``. Requires a websocket connection to a
        witness node!
    """
    raise DeprecationWarning(
        "This method shouldn't be called anymore. It is part of transactionbuilder now"
        )


def local():
    """Returns a local repository instance.

        If the peer represents a local repository, returns an object that
        can be used to interface with it. Otherwise returns ``None``.
        """


def squashDicts(*dict_args):
    """
  Given any number of dicts, shallow copy and merge into a new dict,
  precedence goes to key value pairs in later dicts.
  """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


def error_msg_from_exception(e):
    """Translate exception into error message

    Database have different ways to handle exception. This function attempts
    to make sense of the exception object and construct a human readable
    sentence.

    TODO(bkyryliuk): parse the Presto error message from the connection
                     created via create_engine.
    engine = create_engine('presto://localhost:3506/silver') -
      gives an e.message as the str(dict)
    presto.connect("localhost", port=3506, catalog='silver') - as a dict.
    The latter version is parsed correctly by this function.
    """
    msg = ''
    if hasattr(e, 'message'):
        if type(e.message) is dict:
            msg = e.message.get('message')
        elif e.message:
            msg = '{}'.format(e.message)
    return msg or '{}'.format(e)


@classmethod
def from_2d_array(cls, array):
    """
        Create an instance using a 2-dimensional array.

        Arguments:
        array ([[object, ...], ...])
            The array to use in creating the grid instance.

        Return: Grid
            The resulting grid.
        """
    x_size = len(array[0])
    y_size = len(array)
    grid = cls(x_size, y_size)
    for coord in grid.all_coords:
        x, y = coord
        grid[coord] = array[y][x]
    return grid


def prepare_arguments(arguments):
    """Set proper maximum track length. Convert length arguments to seconds."""
    if 'max_tracklist_length' in arguments:
        if 0 < arguments['max_tracklist_length'] < arguments['max']:
            arguments['max'] = arguments['max_tracklist_length']
        arguments['max_tracklist_length'] *= 60
    arguments['max'] *= 60
    arguments['min'] *= 60


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

        :param SharedContentRelinquishMembershipDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_relinquish_membership_details', val)


def reverse(arr, b):
    """Reverse elements in a list.

    This function is equivalent to:

    .. code-block:: javascript

       function(a, b) { a.reverse() }

    This method takes an unused ``b`` variable as their transform functions
    universally sent two arguments.

    **Example**:

    >>> reverse([1, 2, 3, 4])
    [4, 3, 2, 1]
    """
    return arr[::-1]


def dictmerge(x, y):
    """
    merge two dictionaries
    """
    z = x.copy()
    z.update(y)
    return z


def write_html_column(cssclass, file, header, rows):
    """Create a column in the output."""
    file.write("

" + "
" + header + "" + str(len(rows)) +
        '
')
    for row in rows:
        task_uuid = str(row['uuid']) if row['uuid'] is not None else ''
        task_title = str(row['title']) if row['title'] is not None else ''
        context_title = str(row['context']) if row['context'
            ] is not None else ''
        context_uuid = str(row['context_uuid']) if row['context_uuid'
            ] is not None else ''
        deadline = str(row['due']) if row['due'] is not None else ''
        task_link = ('' +
            task_title + '' if task_uuid != '' else task_title)
        context_link = ('' +
            context_title + '' if context_uuid != '' else context_title)
        css_class = 'hasProject' if context_title != '' else 'hasNoProject'
        css_class = 'hasDeadline' if deadline != '' else css_class
        file.write('
' + task_link +
            '
' + deadline + '
' +
            '
' + context_link +
            '
' + '
')
    file.write('

')


@classmethod
def empty(kls, force_refresh=False):
    """Create an empty filter"""
    return kls.from_options({'force_refresh': force_refresh})


def remap_oscar_credit_card(card):
    """Remaps Oscar credit card object as Helcim dictionary.

        Parameters:
            card (obj): A credit card object provided by Django Oscar.

        Returns:
            dict: Credit card details formatted for django-helcim.
    """
    if card.expiry_date:
        cc_expiry = card.expiry_date.strftime('%m%y')
    else:
        cc_expiry = None
    return {'cc_name': card.name, 'cc_number': card.number, 'cc_expiry':
        cc_expiry, 'cc_cvv': card.ccv}


@classmethod
def authenticate(cls, login_data):
    """ Here you can implement select in the database
            to garantee that the username and the password
            are from the same user. This method must return
            a dict
        """
    raise NotImplementedError()


@staticmethod
def _format_method_name(request_name: str) ->str:
    """Приводит к единой форме имя метода."""
    request_name = request_name if not request_name.startswith('/'
        ) else request_name[1:]
    request_name = request_name if request_name.endswith('/'
        ) else request_name + '/'
    return request_name


@staticmethod
def get_compatable_connection_types():
    """
        This is needed so the service framework knows which
        connections this current connection is compatable.
        return::['str'] A list of the compatable connections
        """
    return ['subscriber']


def is_db_connection_error(args):
    """Return True if error in connecting to db."""
    conn_err_codes = '2002', '2003', '2006'
    for err_code in conn_err_codes:
        if args.find(err_code) != -1:
            return True
    return False


def convert_float(value, parser):
    """
    Converts the specified value to a float if possible. If
    conversion fails, exit by calling parser.error.
    """
    try:
        return float(value)
    except ValueError:
        parser.error("invalid float value '{}'".format(value))


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

    Usage:

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


@staticmethod
def complement_doc(name, docstr):
    """ complement the process docstring
        """
    docstring = docstr.split('\n')
    indent = -1
    for line in docstring[1:]:
        lstrip = line.strip()
        if not lstrip:
            continue
        lindent = line.index(line.strip())
        if indent == -1 or lindent < indent:
            indent = lindent
    if indent < 0:
        indent = 0
    docstring += [(' ' * indent + line) for line in ['', '.. note::', '',
        "    * Type '{0}.help()' for a full description of this process parameters."
        .format(name),
        "    * Type '<{0}>.get_input_spec()' for a full description of this process input trait types."
        .format(name),
        "    * Type '<{0}>.get_output_spec()' for a full description of this process output trait types."
        .format(name), '']]
    return '\n'.join(docstring)


def list_clusters(nextToken=None, maxResults=None):
    """
    Returns a list of existing clusters.
    See also: AWS API Documentation

    Examples
    This example lists all of your available clusters in your default region.
    Expected Output:

    :example: response = client.list_clusters(
        nextToken='string',
        maxResults=123
    )

    :type nextToken: string
    :param nextToken: The nextToken value returned from a previous paginated ListClusters request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.
            Note
            This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.

    :type maxResults: integer
    :param maxResults: The maximum number of cluster results returned by ListClusters in paginated output. When this parameter is used, ListClusters only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another ListClusters request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then ListClusters returns up to 100 results and a nextToken value if applicable.

    :rtype: dict
    :return: {
        'clusterArns': [
            'string',
        ],
        'nextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def kwargs_extract(default, **kwargs):
    """
    like kwargs_update but extracts keys of default from kwargs

    Returns:
    k -- dictionary based on default update for kwargs
    l -- kwargs without keys defined in default
    """
    k = default.copy()
    l = {}
    for key, val in kwargs.items():
        if key in k.keys():
            k[key] = val
        else:
            l[key] = val
    return k, l


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

    The ".dev0" means dirty.

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


def is_naive(dt):
    """
    Determines if a given datetime.datetime is naive.
    The concept is defined in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    Assuming value.tzinfo is either None or a proper datetime.tzinfo,
    value.utcoffset() implements the appropriate logic.
    """
    return dt.utcoffset() is None


def get_permitted_algorithm_names():
    """ returns permitted algorithm names. """
    return ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'PS256',
        'PS384', 'PS512']


def set_nodes(entries, overwrite=True):
    """Add multiple children to a directory node. Takes a dict mapping
        unicode childname to (child_node, metdata) tuples. If metdata=None,
        the original metadata is left unmodified. Returns a Deferred that
        fires (with this dirnode) when the operation finishes. This is
        equivalent to calling set_node() multiple times, but is much more
        efficient."""


def identity(*args):
    """
    Return whatever is passed in
    """
    return args if len(args) > 1 else args[0]


def pythonVersion():
    """Returns python version in a string format"""
    from platform import python_version
    return python_version()


def p_main(p):
    """entries : entries entry
               | entry"""
    pass


@staticmethod
def sort_votes(votes):
    """ Sorts the votes in decreasing order and returns the result.

        Usually you don't have to sort the elements by yourself, the __init__
        method will take care of this. But if the elements are already sorted
        from for example a database there is no need to sort them again.

        Args:
            votes (list of MedianVote): The votes to sort.

        Returns:
            list of MedianVote: The sorted votes.
        """
    return sorted(votes, key=lambda vote: vote.value, reverse=True)


def setWscriptVars(module, bconf):
    """
    Set wscript vars: top, out, APPNAME, VERSION
    """
    module.top = bconf.confPaths.wscripttop
    module.out = bconf.confPaths.wscriptout
    module.APPNAME = bconf.projectName
    module.VERSION = bconf.projectVersion


def name_assignment(spectrum: str):
    """
    assigns a name to the filename in which the spectrum is going to be saved
    """
    m0_aces = 'lte03900'
    m3_aces = 'lte03500'
    m6_aces = 'lte02800'
    m9_aces = 'lte02600'
    base = 'PHOENIX-ACES-AGSS-COND-2011-HiRes_wave.dat'
    if m0_aces in spectrum and base in spectrum:
        name = 'M0-PHOENIX-ACES'
    elif m3_aces in spectrum and base in spectrum:
        name = 'M3-PHOENIX-ACES'
    elif m6_aces in spectrum and base in spectrum:
        name = 'M6-PHOENIX-ACES'
    elif m9_aces in spectrum and base in spectrum:
        name = 'M9-PHOENIX-ACES'
    else:
        raise ValueError('Name {0} not found!'.format(spectrum))
    return name


@classmethod
def _createForTesting(cls, sparkContext):
    """(Internal use only) Create a new HiveContext for testing.

        All test code that touches HiveContext *must* go through this method. Otherwise,
        you may end up launching multiple derby instances and encounter with incredibly
        confusing error messages.
        """
    jsc = sparkContext._jsc.sc()
    jtestHive = (sparkContext._jvm.org.apache.spark.sql.hive.test.
        TestHiveContext(jsc, False))
    return cls(sparkContext, jtestHive)


def resource_from_cache_prefix(resource, cache):
    """
    Combine the resource name with the cache prefix (if any)
    """
    if getattr(cache, 'key_prefix', None):
        name = '{} {}'.format(resource, cache.key_prefix)
    else:
        name = resource
    return name.lower()


def delete():
    """Remove selected bones from the armature

    """
    pass


def trim(chips, dates):
    """Eliminates chips that are not from the specified dates

    Args:
        chips: Sequence of chips
        dates: Sequence of dates that should be included in result

    Returns:
        tuple: filtered chips
    """
    return tuple(filter(lambda c: c['acquired'] in dates, chips))


def __call__():
    """Render the widget."""


def line_last_three_words(line):
    """return last three words"""
    if len(line.split()) > 2:
        return ' '.join([line.split()[-3], line.split()[-2], line.split()[-1]])
    else:
        return ''


@staticmethod
def normalize_name(st):
    """remove dashes from a name."""
    if st.startswith('--'):
        st = st.replace('--', '', 1)
    elif st.startswith('-'):
        st = st.replace('-', '', 1)
    return st.replace('-', '_')


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 _get_sysfs_netdev_path(pci_addr, pf_interface):
    """Get the sysfs path based on the PCI address of the device.

    Assumes a networking device - will not check for the existence of the path.
    """
    if pf_interface:
        return '/sys/bus/pci/devices/%s/physfn/net' % pci_addr
    return '/sys/bus/pci/devices/%s/net' % pci_addr


@staticmethod
def rebuild_include(name_match, group_number):
    """Adds appropriate brackets around include name and "#include" before
        that based on group number.

        Keyword arguments:
        name_match -- include name's regex Match object
        group_number -- include classification index

        Returns include name with approriate brackets and "#include" prefix.
        """
    if 1 <= group_number <= 3:
        output = '#include <' + name_match.group('name'
            ) + '>' + name_match.group('postfix')
    else:
        output = '#include "' + name_match.group('name'
            ) + '"' + name_match.group('postfix')
    if name_match.group('comment'):
        return name_match.group('comment') + output
    else:
        return output


def __and__(i1, i2):
    """Return the intersection of i1 and i2."""
    return i1.__class__(*i1._intersection(i1, i2))


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 GetProperties(mol, items=['MW', 'Vol', 'Dense', 'fChar', 'nBond',
    'nAtom', 'nHD', 'nHA', 'nHB', 'nHet', 'nStero', 'nHev', 'nRot', 'nRig',
    'Flex', 'nRing', 'logP', 'logD', 'pKa', 'logSw', 'ab', 'MR', 'TPSA',
    'AP', 'HetRatio', 'Fsp3', 'MaxRing', 'QEDmean', 'QEDmax', 'QEDnone',
    'SAscore', 'NPscore', 'nSingle', 'nDouble', 'nTriple', 'nC', 'nB', 'nF',
    'nCl', 'nBr', 'nI', 'nP', 'nS', 'nO', 'nN']):
    """
    Get all properties in scopy
    """
    funcl = {'MW': 'CalculateMolWeight(mol)', 'Vol':
        'CalculateMolVolume(mol)', 'Dense': 'CalculateMolDensity(mol)',
        'fChar': 'CalculateMolFCharge(mol)', 'nBond':
        'CalculateNumBonds(mol)', 'nAtom': 'CalculateNumAtoms(mol)', 'nHet':
        'CalculateNumHetero(mol)', 'nRot':
        'CalculateNumRotatableBonds(mol)', 'nRig':
        'CalculateNumRigidBonds(mol)', 'Flex': 'CalculateFlexibility(mol)',
        'nRing': 'CalculateNumRing(mol)', 'nHev':
        'CalculateNumHeavyAtom(mol)', 'logP': 'CalculateLogP(mol)', 'logD':
        'CalculateLogD(mol)', 'pKa': 'CalculatepKa(mol)', 'ab':
        'CheckAcid(mol)', 'MR': 'CalculateMolMR(mol)', 'nHD':
        'CalculateNumHDonors(mol)', 'nHA': 'CalculateNumHAcceptors(mol)',
        'nHB': 'CalculateNumHyBond(mol)', 'AP':
        'CalculateAromaticProportion(mol)', 'logSw': 'CalculateLogSw(mol)',
        'Fsp3': 'CalculateFsp3(mol)', 'TPSA': 'CalculateTPSA(mol)',
        'MaxRing': 'CalculateMaxSizeSystemRing(mol)', 'nStero':
        'CalculateNumStereocenters(mol)', 'HetRatio':
        'CalculateHetCarbonRatio(mol)', 'QEDmean': 'CalculateQEDmean(mol)',
        'QEDmax': 'CalculateQEDmax(mol)', 'QEDnone':
        'CalculateQEDnone(mol)', 'SAscore': 'CalculateSAscore(mol)',
        'NPscore': 'CalculateNPscore(mol)', 'nSingle':
        'CalculateNumSinBond(mol)', 'nDouble': 'CalculateNumDouBond(mol)',
        'nTriple': 'CalculateNumTriBond(mol)', 'nC':
        'CalculateNumCarbon(mol)', 'nB': 'CalculateNumBoron(mol)', 'nF':
        'CalculateNumFluorin(mol)', 'nCl': 'CalculateNumChlorin(mol)',
        'nBr': 'CalculateNumBromine(mol)', 'nI': 'CalculateNumIodine(mol)',
        'nP': 'CalculateNumPhosphor(mol)', 'nS': 'CalculateNumSulfur(mol)',
        'nO': 'CalculateNumOxygen(mol)', 'nN': 'CalculateNumNitrogen(mol)'}
    vals = []
    for item in items:
        val = eval(funcl[item])
        vals.append(val)
    return dict(zip(items, vals))


@classmethod
def assemble(cls):
    """Assemble a single document using the blueprint"""
    document = {}
    for field_name, maker in cls._instructions.items():
        with maker.target(document):
            document[field_name] = maker()
    return document


@classmethod
def remove_compute_resource(cls, options=None):
    """Removes a computeresource from an org"""
    cls.command_sub = 'remove-compute-resource'
    return cls.execute(cls._construct_command(options))


def homogeneous_to_cartesian_vectors(homogeneous_vector):
    """Convert an homogeneous vector to cartesian vector"""
    return homogeneous_vector[:-1]


@staticmethod
def get_configure_command(config_options=None):
    """
        Get the command to configure the package.

        Notes
        -----
        Configuring happens through python 2
        https://github.com/petsc/petsc/blob/master/configure

        Parameters
        ----------
        config_options : dict
            Configuration options to use with `./configure`.
            The configuration options will be converted to `--key=val` during
            runtime

        Returns
        -------
        config_str : str
            The configuration command
        """
    options = ''
    if config_options is not None:
        for key, val in config_options.items():
            if val is not None:
                options += f' --{key}={val}'
            else:
                options += f' --{key}'
    config_str = f'python2 ./configure{options}'
    return config_str


def primary_spherical(rho, phi):
    """Zernike primary Spherical."""
    return 6 * rho ** 4 - 6 * rho ** 2 + 1


def delete_object_tagging(Bucket=None, Key=None, VersionId=None):
    """
    Removes the tag-set from an existing object.
    See also: AWS API Documentation

    :example: response = client.delete_object_tagging(
        Bucket='string',
        Key='string',
        VersionId='string'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED]

    :type Key: string
    :param Key: [REQUIRED]

    :type VersionId: string
    :param VersionId: The versionId of the object that the tag-set will be removed from.

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

    :returns:
    (dict) --
    VersionId (string) -- The versionId of the object the tag-set was removed from.

    """
    pass


def generate_group_id(namespace):
    """Generates the ID for a resource group wrapper resource around the
    resource with the given namespace.

    :type namespace: str
    :rtype: str
    """
    return namespace.rsplit('-', 1)[0]


@classmethod
def POST(cls, *n, **kw):
    """
        Perform a POST request using `RESTClient.request()`
        """
    return cls.IMPL.POST(*n, **kw)


def is_equal_or_child_uri(parentUri, childUri):
    """Return True, if childUri is a child of parentUri or maps to the same resource.

    Similar to <util.is_child_uri>_ ,  but this method also returns True, if parent
    equals child. ('/a/b' is considered identical with '/a/b/').
    """
    return parentUri and childUri and (childUri.rstrip('/') + '/').startswith(
        parentUri.rstrip('/') + '/')


@classmethod
def from_dict(cls, dct):
    """Instantiate an agent using the specified dictionary.

        TAG: USER
        """
    return cls(**dct)


def geo_coordinates(longitude=0, latitude=0):
    """
    transform geographical coordinates given as longitude [-180..+180]
    and latitude [-90..+90] in a string with absolute indications and
    'N', 'S', 'E', 'W'

    input:
    - longitude, decimal degrees, float
    - latitude, decimal degrees, float

    output:
    - string in format '27.34N 14.82E'

    """
    if latitude >= 0:
        lat_dir = 'N'
        lat_val = str(round(latitude, 2))
    else:
        lat_dir = 'S'
        lat_val = str(round(-latitude, 2))
    if longitude >= 0:
        lon_dir = 'E'
        lon_val = str(round(longitude, 2))
    else:
        lon_dir = 'W'
        lon_val = str(round(-longitude, 2))
    coord = lat_val + '' + lat_dir + ' ' + lon_val + '' + lon_dir
    return coord


def invalidate(key=None):
    """ Invalidate the given key, or all key/values if no key is passed.
        """


def split_nonsyllabic_prob(string, onsets, codas):
    """
    Guesses split between onset and coda in list with no found syllabic segments

    Parameters
    ----------
    string : iterable
        the phones to search through
    onsets : iterable
        an iterable of possible onsets
    codas : iterable
        an iterable of possible codas

    Returns
    -------
    int
        best guess for the index in the string where the onset ends and coda begins
    """
    if len(string) == 0:
        return None
    max_prob = -10000
    best = None
    for i in range(len(string) + 1):
        prob = 0
        ons = tuple(string[:i])
        cod = tuple(string[i:])
        if ons not in onsets:
            prob += onsets[None]
        else:
            prob += onsets[ons]
        if cod not in codas:
            prob += codas[None]
        else:
            prob += codas[cod]
        if prob > max_prob:
            max_prob = prob
            best = i
    return best


def parse_xml_string(xml_string):
    """Parses a xml string with minidom
        """


def are_equal_regardless_of_order(seq1, seq2):
    """
    Do `seq1` and `seq2` contain the same elements, same number of times?

    Disregards order of elements.

    Currently will fail for items that have problems with comparing.
    """
    from python_toolbox import nifty_collections
    return nifty_collections.Bag(seq1) == nifty_collections.Bag(seq2)


@staticmethod
def validate_wunit(w):
    """
        @param w widget mapping
        """
    err = []
    try:
        v = w['symbol'].get()
        if len(v) < 1 or len(v) > 2:
            stat = False
            err.append(('symbol', 'char length is not valid'))
            w['symbol'].config(bg='red')
        else:
            w['symbol'].config(bg='white')
    except:
        err.append(('symbol', 'exception orruced'))
    for name in ['z', 'w', 'stoich', 'disp']:
        e = w[name].validate()
        if e:
            err.append((name, e))
    return err if err else None


def build_tf_to_pytorch_map(model, config):
    """ A map of modules from TF to PyTorch.
        This time I use a map to keep the PyTorch model as identical to the original PyTorch model as possible.
    """
    tf_to_pt_map = {}
    if hasattr(model, 'transformer'):
        tf_to_pt_map.update({
            'transformer/adaptive_softmax/cutoff_0/cluster_W': model.crit.
            cluster_weight,
            'transformer/adaptive_softmax/cutoff_0/cluster_b': model.crit.
            cluster_bias})
        for i, (out_l, proj_l, tie_proj) in enumerate(zip(model.crit.
            out_layers, model.crit.out_projs, config.tie_projs)):
            layer_str = 'transformer/adaptive_softmax/cutoff_%d/' % i
            if config.tie_weight:
                tf_to_pt_map.update({(layer_str + 'b'): out_l.bias})
            else:
                raise NotImplementedError
                tf_to_pt_map.update({(layer_str + 'lookup_table'): out_l.
                    weight, (layer_str + 'b'): out_l.bias})
            if not tie_proj:
                tf_to_pt_map.update({(layer_str + 'proj'): proj_l})
        model = model.transformer
    for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers,
        model.word_emb.emb_projs)):
        layer_str = 'transformer/adaptive_embed/cutoff_%d/' % i
        tf_to_pt_map.update({(layer_str + 'lookup_table'): embed_l.weight,
            (layer_str + 'proj_W'): proj_l})
    for i, b in enumerate(model.layers):
        layer_str = 'transformer/layer_%d/' % i
        tf_to_pt_map.update({(layer_str + 'rel_attn/LayerNorm/gamma'): b.
            dec_attn.layer_norm.weight, (layer_str +
            'rel_attn/LayerNorm/beta'): b.dec_attn.layer_norm.bias, (
            layer_str + 'rel_attn/o/kernel'): b.dec_attn.o_net.weight, (
            layer_str + 'rel_attn/qkv/kernel'): b.dec_attn.qkv_net.weight,
            (layer_str + 'rel_attn/r/kernel'): b.dec_attn.r_net.weight, (
            layer_str + 'ff/LayerNorm/gamma'): b.pos_ff.layer_norm.weight,
            (layer_str + 'ff/LayerNorm/beta'): b.pos_ff.layer_norm.bias, (
            layer_str + 'ff/layer_1/kernel'): b.pos_ff.CoreNet[0].weight, (
            layer_str + 'ff/layer_1/bias'): b.pos_ff.CoreNet[0].bias, (
            layer_str + 'ff/layer_2/kernel'): b.pos_ff.CoreNet[3].weight, (
            layer_str + 'ff/layer_2/bias'): b.pos_ff.CoreNet[3].bias})
    if config.untie_r:
        r_r_list = []
        r_w_list = []
        for b in model.layers:
            r_r_list.append(b.dec_attn.r_r_bias)
            r_w_list.append(b.dec_attn.r_w_bias)
    else:
        r_r_list = [model.r_r_bias]
        r_w_list = [model.r_w_bias]
    tf_to_pt_map.update({'transformer/r_r_bias': r_r_list,
        'transformer/r_w_bias': r_w_list})
    return tf_to_pt_map


def hour_minute(v):
    """Convert 7.5 (hours) to (7, 30) i.e. 7 hours and 30 minutes."""
    h = int(v)
    m = int((v - h) * 60)
    return h, m


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

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

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


def download_files(client, source, destination, relative_directory):
    """ Download files from the remote directory.

    This method downloads one file, an entire directory or a set of
    files (specified by shell glob pattern) to a given directory in
    in the local filesystem. Additional parameters are there to
    refine the process.

    The source parameter refers to the remote file(s) to be
    transfered to the local filesystem and is expected to be a
    path-like object, unless it's a shell glob pattern in which case
    a string is expected. The path must be relative and is by
    default relative to the root directory. It can be
    altered with the relative_directory parameter which itself must
    be path-like object refering to an absolute directory.

    The destination parameter refers to the remote directory in
    which the file(s) must be transfered to. It must be a path-like
    object and must be absolute.

    Long description.

    :param source: Foobar.
    :param destination: Foobar.
    :param chunk_size: Foobar.
    :type chunk_size: int
    :param process_chunk: Foobar.
    :param timeout: How many milliseconds to wait before giving up
    :type timeout: int
    """
    pass


def inverse(x):
    """ Inverse 0/1 variable

    Args:
        x: variable with float32 dtype

    Returns:
        inverse_x: variable with float32 dtype
    """
    inverse_x = -1.0 * x + 1.0
    return inverse_x


def delete_entity(session, entity):
    """
    Deletes an entity. Deleted entities are put in the "trash" and are no longer visible
    or returned by GET operations. Trashed entities can be restored from the trash by
    calling `undelete_entity`.

    :param session: ovation.session.Session
    :param entity: entity dict or ID
    :return: deleted entity Dict
    """
    try:
        id = entity['_id']
    except TypeError:
        id = entity
    return session.delete(session.path(entity_id=id))


def translateNoteTieToByte(n):
    """
    takes a note.Note object and returns a one-byte representation
    of its tie status.
    's' if start tie, 'e' if stop tie, 'c' if continue tie, and '' if no tie

    >>> n = note.Note('E')
    >>> search.translateNoteTieToByte(n)
    ''

    >>> n.tie = tie.Tie('start')
    >>> search.translateNoteTieToByte(n)
    's'

    >>> n.tie.type = 'continue'
    >>> search.translateNoteTieToByte(n)
    'c'

    >>> n.tie.type = 'stop'
    >>> search.translateNoteTieToByte(n)
    'e'
    """
    if n.tie is None:
        return ''
    elif n.tie.type == 'start':
        return 's'
    elif n.tie.type == 'continue':
        return 'c'
    elif n.tie.type == 'stop':
        return 'e'
    else:
        return ''


def getColHeaders():
    """Function to return the column headers for the *PyTrack* base format data representation.

    """
    return ['Timestamp', 'StimulusName', 'EventSource', 'GazeLeftx',
        'GazeRightx', 'GazeLefty', 'GazeRighty', 'PupilLeft', 'PupilRight',
        'FixationSeq', 'SaccadeSeq', 'Blink', 'GazeAOI']


def get_token_uri(APP_ID, scope):
    """
        Returns URL for getting tokens
        """
    uri = 'https://www.facebook.com/dialog/oauth?client_id=%s' % APP_ID
    uri += ('&scope=%s&redirect_uri=https://localhost&response_type=token' %
        scope)
    return uri


@staticmethod
def is_valid(control_instance, *args, **kwargs):
    """ Method to check if the new control value is correct.

        Parameters
        ----------
        control_instance: QComboBox (mandatory)
            the control widget we want to validate

        Returns
        -------
        out: bool
            always True since the control value is always valid
        """
    return True


def write_csv(column_headers, rows, output_uri):
    """Given a list of column headers and contents, write to a csv file

        column_headers - a list of strings defining the column names
        rows - a list of lists where an inner list index corresponds
            to the column header in column_headers
        output_uri - the location to save the output .csv file

        returns nothing"""
    pass


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


def add_signaling_arguments(parser):
    """
    Add signaling method arguments to an argparse.ArgumentParser.
    """
    parser.add_argument('--signaling-host', default='127.0.0.1', help=
        'Signaling host (websocket server host)')
    parser.add_argument('--signaling-port', default=1234, help=
        'Signaling port (websocket server port)')


def view_all():
    """Reset viewable area to show full keyframe range

    """
    pass


def get_numpy_include_path():
    """
    Gets the path to the numpy headers.
    """
    import builtins
    if hasattr(builtins, '__NUMPY_SETUP__'):
        del builtins.__NUMPY_SETUP__
    import imp
    import numpy
    imp.reload(numpy)
    try:
        numpy_include = numpy.get_include()
    except AttributeError:
        numpy_include = numpy.get_numpy_include()
    return numpy_include


def __is_sotpwords(token, stopwords):
    """This function filters out stopwords. If token is in stopwords list, return True; else return False
    """
    if token in stopwords:
        return True
    else:
        return False


def create(data):
    """Create and return an object to be added to the context.

        The data argument is a dictionary with values supplied by the
        form.

        If any user errors occur, they should be collected into a list
        and raised as a `WidgetsError`.

        """


def standardize_axes_names(data_dict):
    """For all dataframes in the given dictionary, sets the name of the index axes to "Patient_ID", because that's what they all are by that point, and sets the name of the column axes to "Name".

    Parameters:
    data_dict (dict): The dataframe dictionary of the dataset.

    Returns:
    dict: The dataframe dictionary, with the dataframe axes' names standardized. Keys are str of dataframe names, values are pandas DataFrames
    """
    for name in data_dict.keys():
        df = data_dict[name]
        df.index.name = 'Patient_ID'
        df.columns.name = 'Name'
        data_dict[name] = df
    return data_dict


@staticmethod
def _read(sock, chunk_len=2048):
    """
        Read all chunks from socket connection
        :param sock:
        :param chunk_len:
        :return:
        """
    result = sock.recv(chunk_len)
    if len(result) == chunk_len:
        while True:
            tmp = sock.recv(chunk_len)
            result += tmp
            if len(tmp) < chunk_len:
                break
    return result


def unliteral(lit_type):
    """
    Get base type from Literal type.
    """
    if hasattr(lit_type, '__unliteral__'):
        return lit_type.__unliteral__()
    return getattr(lit_type, 'literal_type', lit_type)


def scan3(alines):
    """deal with indents in text lines"""
    outer_indent = [0]
    for i, aline in enumerate(alines):
        if aline.type in ['ordered', 'unordered']:
            while outer_indent[-1] >= aline.outer_indent:
                outer_indent.pop()
            outer_indent.append(aline.outer_indent)
        elif aline.type == 'text':
            while outer_indent[-1] > aline.content_start:
                outer_indent.pop()
            aline.indent = outer_indent[-1]
    return alines


@staticmethod
def _get_root_parent_node(path, delimiter='/', rootpath=None):
    """Get path to the root parent of current leaf"""
    if rootpath:
        startpos = len(rootpath) + 1
    else:
        startpos = 0
    m = path.find(delimiter, startpos)
    return path[:m] if m >= 0 else None


def read(size=-1):
    """Read at most `size` bytes from the file

        If size is negative or omitted all data is read
        """


def is_rgb(in_col):
    """
	Check whether input is a valid RGB color.
	Return True if it is, otherwise False.
	"""
    if len(in_col) == 3 and type(in_col) == tuple:
        if 0 <= in_col[0] <= 255 and 0 <= in_col[1] <= 255 and 0 <= in_col[2
            ] <= 255:
            return True
        else:
            return False
    else:
        return False


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 similar_values(v1, v2, e=1e-06):
    """Return True if v1 and v2 are nearly the same."""
    if v1 == v2:
        return True
    return abs(v1 - v2) / max(abs(v1), abs(v2)) <= e


def list2dict(list_obj, value=None, dict_obj=None):
    """
    >>> list_obj = ["a", 2, "c"]
    >>> list2dict(list_obj, 10)
    {'a': {2: {'c': 10}}}
    """
    dict_obj = {} if dict_obj is None else dict_obj
    _dict_obj = dict_obj
    for e in list_obj[:-1]:
        if e not in _dict_obj:
            _dict_obj[e] = {}
        _dict_obj = _dict_obj[e]
    _dict_obj[list_obj[-1]] = value
    return dict_obj


def compile_target_uri(url: str, query_string: bytes) ->str:
    """Append GET query string to the page path, to get full URI."""
    if query_string:
        return '{}?{}'.format(url, query_string.decode('utf-8'))
    else:
        return url


def version_message(prog):
    """Program version message.

    Args:
        prog (State): program state.

    Returns:
        str: the message to print.
    """
    return '{} {}\n{}'.format(prog.name, prog.version, prog.copyright)


def paste_driver_button():
    """Paste the driver in the copy/paste buffer for the highlighted button

    """
    pass


def collection_enable():
    """Enable viewport drawing in the view layers

    """
    pass


def build_decode_cmd(src, dest, decoder):
    """ Build command to decode downloaded into JSON """
    decode_multiple = 'decode_multiple'
    decoder_module = decoder
    input_format = 'csv'
    decode_cmd = (
        '{decode_multiple} --filename {src} --format {input_format} {decoder_module} > {dest}'
        .format(decode_multiple=decode_multiple, decoder_module=
        decoder_module, src=src, input_format=input_format, dest=dest))
    return decode_cmd


def is_int(potential_int: str) ->bool:
    """
    Check if potential_int is a valid integer.

    Parameters
    ----------
    potential_int : str

    Returns
    -------
    is_int : bool

    Examples
    --------
    >>> is_int('123')
    True
    >>> is_int('1234567890123456789')
    True
    >>> is_int('0')
    True
    >>> is_int('-123')
    True
    >>> is_int('123.45')
    False
    >>> is_int('a')
    False
    >>> is_int('0x8')
    False
    """
    try:
        int(potential_int)
        return True
    except ValueError:
        return False


def _is_sunder(name):
    """Returns True if a _sunder_ name, False otherwise."""
    return name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1
        ] != '_' and len(name) > 2


@staticmethod
def _clean_task_environment(task_id=None, task_name=None, exc=None):
    """Cleans the environment for this task.

        Args:
            task_id: string of task id.
            task_name: string of task name.
            exc: The exception raised by the task, None if the task succeeded.
        """
    pass


@staticmethod
def _get_out(waterbody, datetime_time_step, dict_data_frame, r_out_c_no3,
    r_out_c_nh4, r_out_c_dph, r_out_c_pph, r_out_c_sed, r_s_m_no3,
    r_s_m_nh4, r_s_m_dph, r_s_m_pph, r_s_m_sed):
    """
        This function is the interface between the model and the data models of the simulator.
        It stores the outputs, and updated states in the data frame.
        """
    dict_data_frame[waterbody][datetime_time_step]['r_out_c_no3'] = r_out_c_no3
    dict_data_frame[waterbody][datetime_time_step]['r_out_c_nh4'] = r_out_c_nh4
    dict_data_frame[waterbody][datetime_time_step]['r_out_c_dph'] = r_out_c_dph
    dict_data_frame[waterbody][datetime_time_step]['r_out_c_pph'] = r_out_c_pph
    dict_data_frame[waterbody][datetime_time_step]['r_out_c_sed'] = r_out_c_sed
    dict_data_frame[waterbody][datetime_time_step]['r_s_m_no3'] = r_s_m_no3
    dict_data_frame[waterbody][datetime_time_step]['r_s_m_nh4'] = r_s_m_nh4
    dict_data_frame[waterbody][datetime_time_step]['r_s_m_dph'] = r_s_m_dph
    dict_data_frame[waterbody][datetime_time_step]['r_s_m_pph'] = r_s_m_pph
    dict_data_frame[waterbody][datetime_time_step]['r_s_m_sed'] = r_s_m_sed


def advConstruct(expression, *args, constants={}):
    """Returns a function computing the given expression. The variable names need to be listed as individual string arguments.
    Constants is an optional argument with the name and value of constants in the expression"""
    string = """def func({}):
    return {}""".format(', '.join(args),
        expression.replace('^', '**'))
    exec(string, constants)
    return constants['func']


def _get_setfilesuffix_methodname(altsuffix_name):
    """
        Return the name of the method name to set suffix to `altsuffix_name`
        e.g. `logfile()` for setting to `log`.
        """
    return altsuffix_name + 'file'


def rangecomplete(incomplete, complete):
    """
    >>> rangecomplete('2', '10')
    '12'
    """
    if len(complete) > len(incomplete):
        return complete[:len(complete) - len(incomplete)] + incomplete
    return incomplete


def dicarray_find_key_value(dica, key, value):
    """Find dics in dicarray with [key: value] pair."""
    dics_ = []
    for d_ in dica:
        if isinstance(d_, dict) and d_.get(key) == value:
            dics_.append(d_)
    return dics_


def _use_inline_crc_finalize(opt):
    """
    Return True if the init function can be inlined.
    """
    if opt.algorithm in set([opt.algo_bit_by_bit_fast, opt.algo_table_driven]
        ) and (opt.width is not None and opt.reflect_in is not None and opt
        .reflect_out is not None and opt.xor_out is not None):
        return True
    else:
        return False


def validate_boolean(datum, **kwargs):
    """
    Check that the data value is bool instance

    Parameters
    ----------
    datum: Any
        Data being validated
    kwargs: Any
        Unused kwargs
    """
    return isinstance(datum, bool)


@staticmethod
def parameters_list(num_particles, omega, phi_p, phi_g):
    """
        Create a list with PSO parameters in the correct order.

        :param num_particles: Number of particles for the PSO swarm.
        :param omega: The omega parameter (aka. inertia weight) for the PSO.
        :param phi_p: The phi_p parameter (aka. particle weight) for the PSO.
        :param phi_g: The phi_g parameter (aka. social weight) for the PSO.
        :return: List with PSO parameters.
        """
    return [num_particles, omega, phi_p, phi_g]


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 trunc(obj, max, left=0):
    """
    Convert `obj` to string, eliminate newlines and truncate the string to
    `max` characters. If there are more characters in the string add ``...`` to
    the string. With `left=True`, the string can be truncated at the beginning.

    @note: Does not catch exceptions when converting `obj` to string with
        `str`.

    >>> trunc('This is a long text.', 8)
    This ...
    >>> trunc('This is a long text.', 8, left)
    ...text.
    """
    s = str(obj)
    s = s.replace('\n', '|')
    if len(s) > max:
        if left:
            return '...' + s[len(s) - max + 3:]
        else:
            return s[:max - 3] + '...'
    else:
        return s


def delete_access_key(UserName=None, AccessKeyId=None):
    """
    Deletes the access key pair associated with the specified IAM user.
    If you do not specify a user name, IAM determines the user name implicitly based on the AWS access key ID signing the request. Because this action works for access keys under the AWS account, you can use this action to manage root credentials even if the AWS account has no associated users.
    See also: AWS API Documentation

    Examples
    The following command deletes one access key (access key ID and secret access key) assigned to the IAM user named Bob.
    Expected Output:

    :example: response = client.delete_access_key(
        UserName='string',
        AccessKeyId='string'
    )

    :type UserName: string
    :param UserName: The name of the user whose access key pair you want to delete.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type AccessKeyId: string
    :param AccessKeyId: [REQUIRED]
            The access key ID for the access key ID and secret access key you want to delete.
            This parameter allows (per its regex pattern ) a string of characters that can consist of any upper or lowercased letter or digit.

    :return: response = client.delete_access_key(
        AccessKeyId='AKIDPMS9RO4H3FEXAMPLE',
        UserName='Bob',
    )

    print(response)

    """
    pass


def provider_parser(subparser):
    """Configure provider parser for Rackspace"""
    subparser.add_argument('--auth-account', help=
        'specify account number for authentication')
    subparser.add_argument('--auth-username', help=
        'specify username for authentication. Only used if --auth-token is empty.'
        )
    subparser.add_argument('--auth-api-key', help=
        'specify api key for authentication. Only used if --auth-token is empty.'
        )
    subparser.add_argument('--auth-token', help=
        'specify token for authentication. If empty, the username and api key will be used to create a token.'
        )
    subparser.add_argument('--sleep-time', type=float, default=1, help=
        'number of seconds to wait between update requests.')


def getWorker(name):
    """Return the IWorkerStatus object for a given named worker."""


def _parse_gene(o):
    """Parse gene information from an Ensembl `overlap` query.

    :param o: A Python dict representing an entry from the response.
    :type o: dict

    :returns: A standardised dict of gene information.
    :rtype: dict

    """
    assert o['feature_type'] == 'gene'
    d = {'desc': o.get('description'), 'build': o.get('assembly_name'),
        'chrom': o.get('seq_region_name'), 'start': o.get('start'), 'end':
        o.get('end'), 'strand': o.get('strand'), 'biotype': o.get('biotype')}
    return d


@staticmethod
def get_sip_flags(target_configuration):
    """ Return the list of module-specific flags to pass to SIP.
        target_configuration is the target configuration.
        """
    major = target_configuration.qtp_version >> 16 & 255
    minor = target_configuration.qtp_version >> 8 & 255
    patch = target_configuration.qtp_version & 255
    if (major, minor) >= (5, 13):
        patch = 0
    elif (major, minor) == (5, 12):
        if patch > 4:
            patch = 4
    version_tag = 'QtPurchasing_%d_%d_%d' % (major, minor, patch)
    return ['-t', version_tag]


def forwards_contents(f):
    """
    Return a string containing everything in the forwards() method of a
    migration.

    This string may not be safe to evaluate.
    """
    forwards_found = False
    forwards_lines = []
    for line in f:
        if 'def backwards(self, orm):' in line:
            break
        if forwards_found:
            forwards_lines.append(line)
        elif 'def forwards(self, orm):' in line:
            forwards_found = True
    return ''.join(forwards_lines)


def parse_type_encoding(encoding):
    """Takes a type encoding string and outputs a list of the separated type codes.
    Currently does not handle unions or bitfields and strips out any field width
    specifiers or type specifiers from the encoding.  For Python 3.2+, encoding is
    assumed to be a bytes object and not unicode.

    Examples:
    parse_type_encoding('^v16@0:8') --> ['^v', '@', ':']
    parse_type_encoding('{CGSize=dd}40@0:8{CGSize=dd}16Q32') --> ['{CGSize=dd}', '@', ':', '{CGSize=dd}', 'Q']
    """
    type_encodings = []
    brace_count = 0
    bracket_count = 0
    typecode = b''
    for c in encoding:
        if isinstance(c, int):
            c = bytes([c])
        if c == b'{':
            if typecode and typecode[-1:
                ] != b'^' and brace_count == 0 and bracket_count == 0:
                type_encodings.append(typecode)
                typecode = b''
            typecode += c
            brace_count += 1
        elif c == b'}':
            typecode += c
            brace_count -= 1
            assert brace_count >= 0
        elif c == b'[':
            if typecode and typecode[-1:
                ] != b'^' and brace_count == 0 and bracket_count == 0:
                type_encodings.append(typecode)
                typecode = b''
            typecode += c
            bracket_count += 1
        elif c == b']':
            typecode += c
            bracket_count -= 1
            assert bracket_count >= 0
        elif brace_count or bracket_count:
            typecode += c
        elif c in b'0123456789':
            pass
        elif c in b'rnNoORV':
            pass
        elif c in b'^cislqCISLQfdBv*@#:b?':
            if typecode and typecode[-1:] == b'^':
                typecode += c
            else:
                if typecode:
                    type_encodings.append(typecode)
                typecode = c
    if typecode:
        type_encodings.append(typecode)
    return type_encodings


def last(y):
    """ Returns the last column from 2d matrix """
    return y[:, (y.shape[1] - 1)]


def dtime(sdat, tstart=None, tend=None):
    """Time increment dt.

    Compute dt as a function of time.

    Args:
        sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
        tstart (float): time at which the computation should start. Use the
            beginning of the time series data if set to None.
        tend (float): time at which the computation should end. Use the
            end of the time series data if set to None.
    Returns:
        tuple of :class:`numpy.array`: dt and time arrays.
    """
    tseries = sdat.tseries_between(tstart, tend)
    time = tseries['t'].values
    return time[1:] - time[:-1], time[:-1]


def deliver(mlist, msg, msgdata):
    """Deliver a message to a mailing list's recipients.

        Ordinarily the mailing list is consulted for delivery specifics,
        however the message metadata dictionary can contain additional
        directions to control delivery.  Specifics are left to the
        implementation, but there are a few common keys:

        * envelope_sender - the email address of the RFC 2821 envelope sender;
        * decorated - a flag indicating whether the message has been decorated
            with headers and footers yet;
        * recipients - the set of all recipients who should receive this
            message, as a set of email addresses;

        :param mlist: The mailing list being delivered to.
        :type mlist: `IMailingList`
        :param msg: The original message being delivered.
        :type msg: `Message`
        :param msgdata: Additional message metadata for this delivery.
        :type msgdata: dictionary
        :return: delivery failures as defined by `smtplib.SMTP.sendmail`
        :rtype: dictionary
        """