def find_insert_marker(filenames):
    """Searches for the insert marker and returns (filename, lineno).
    Defaults to the first file and last line if not found.
    """
    marker = 'FAVA-INSERT-MARKER'
    for filename in filenames:
        with open(filename, 'r') as file:
            for lineno, linetext in enumerate(file):
                if marker in linetext:
                    return filename, lineno
    return filenames[0], len(open(filenames[0]).readlines()) + 1


def pmcfg(cfg):
    """
    prints out the core config file to the prompt with a nice stagger Look for
    readability

    Args:
        cfg: dict of dict in a hierarchy of  {section, {items, values}}
    """
    for sec in cfg.keys():
        print(repr(sec))
        for item in cfg[sec].keys():
            print('\t' + item)
            obj = cfg[sec][item]
            for att in ['type', 'options', 'default', 'description']:
                value = getattr(obj, att)
                print('\t\t' + att)
                if type(value) == list:
                    out = ', '.join(value)
                else:
                    out = value
                print('\t\t\t' + repr(out))


def carmichael_of_ppower(pp):
    """Carmichael function of the given power of the given prime.
  """
    p, a = pp
    if p == 2 and a > 2:
        return 2 ** (a - 2)
    else:
        return (p - 1) * p ** (a - 1)


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

        :param PaperEnabledUsersGroupRemovalDetails val:
        :rtype: EventDetails
        """
    return cls('paper_enabled_users_group_removal_details', val)


def cut_suffix(value, suffix):
    """Removes the tailing `suffix` if exists, else return `value`
    unchanged.

    """
    from xotl.tools.future.codecs import safe_decode, safe_encode
    if isinstance(value, str) and isinstance(suffix, bytes):
        suffix = safe_decode(suffix)
    elif isinstance(value, bytes) and isinstance(suffix, str):
        suffix = safe_encode(suffix)
    if len(suffix) > 0 and value.endswith(suffix):
        return value[:-len(suffix)]
    else:
        return value


def has_x11():
    """Is Qt build against X11 server.
    """
    try:
        from AnyQt.QtX11Extras import QX11Info
        return True
    except ImportError:
        return False


@classmethod
def transition_up(cls, inputs, name='transition_up', **kwargs):
    """ An upsampling interconnect layer between two dense blocks

        Parameters
        ----------
        inputs : tf.Tensor
            input tensor
        name : str
            scope name

        Returns
        -------
        tf.Tensor
        """
    kwargs = cls.fill_params('body/transition_up', **kwargs)
    filters = kwargs.pop('filters', cls.num_channels(inputs, kwargs.get(
        'data_format')))
    return cls.upsample(inputs, filters=filters, name=name, **kwargs)


def set_num_parts(df, max_num_parts):
    """Set number of partitions.

    :param max_num_parts maximum number of partitions
    """
    if df.rdd.getNumPartitions() > max_num_parts:
        df = df.repartition(max_num_parts)
    return df


def add():
    """Add a new time marker

    """
    pass


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


def standardize(x):
    """
    Standardizes a Series or DataFrame.
    """
    return (x - x.mean()) / x.std()


def show(args):
    """execute subcommand show"""
    kwargs = vars(args)
    kwargs['channel'] = kwargs.get('channel', 0)
    if args.backend == 'mpl':
        from liesl.show.mpl import show
    elif args.backend == 'ascii':
        from liesl.show.textplot import show
    del kwargs['backend']
    del kwargs['subcommand']
    arguments = dict()
    for k, v in kwargs.items():
        if v is not None:
            arguments[k] = v
    return show(**arguments)


def concat_filter_strings(filter_strings, operator='&'):
    """
    Helper function to combine ami filter strings

    Parameters
    ----------
    filter_strings: ``list``
        The valid filter strings to combine

    operator: ``str``
        The operator to place between the filter strings. This can either be
        ``&`` or ``|``, for ``and`` or ``or`` respectively.
    """
    if len(filter_strings) == 0:
        raise ValueError('filter_strings must have at least one element')
    elif len(filter_strings) == 1:
        return filter_strings[0]
    else:
        sep = ')' + operator + '('
        return '(' + sep.join(filter_strings) + ')'


@classmethod
def dictionaries(cls):
    """
        Produces a list of dictionaries instead of model instances, at the
        cursor level.
        """
    if cls.__query__ is None:
        cls.select()
    return cls.execute(fetch=True, mode='dictionaries')


def list_event_subscriptions(resourceArn=None, nextToken=None, maxResults=None
    ):
    """
    Lists all the event subscriptions for the assessment template that is specified by the ARN of the assessment template. For more information, see  SubscribeToEvent and  UnsubscribeFromEvent .
    See also: AWS API Documentation

    Examples
    Lists all the event subscriptions for the assessment template that is specified by the ARN of the assessment template.
    Expected Output:

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

    :type resourceArn: string
    :param resourceArn: The ARN of the assessment template for which you want to list the existing event subscriptions.

    :type nextToken: string
    :param nextToken: You can use this parameter when paginating results. Set the value of this parameter to null on your first call to the ListEventSubscriptions action. Subsequent calls to the action fill nextToken in the request with the value of NextToken from the previous response to continue listing data.

    :type maxResults: integer
    :param maxResults: You can use this parameter to indicate the maximum number of items you want in the response. The default value is 10. The maximum value is 500.

    :rtype: dict
    :return: {
        'subscriptions': [
            {
                'resourceArn': 'string',
                'topicArn': 'string',
                'eventSubscriptions': [
                    {
                        'event': 'ASSESSMENT_RUN_STARTED'|'ASSESSMENT_RUN_COMPLETED'|'ASSESSMENT_RUN_STATE_CHANGED'|'FINDING_REPORTED'|'OTHER',
                        'subscribedAt': datetime(2015, 1, 1)
                    },
                ]
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


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

        :param TeamMergeRequestReminderType val:
        :rtype: EventType
        """
    return cls('team_merge_request_reminder', val)


def Serialize(item):
    """
    Serializes an item into a bytearray
    """
    pass


def nb_clear_outputs(nb):
    """Clear the output cells from a Jupyter notebook."""
    for cell in nb.cells:
        if 'outputs' in cell:
            cell['outputs'] = []


def upload_to_gdrive(drive, dl_location, filename, folder_id):
    """Upload file to Google drive.
    Make sure to include the following variables wherever you call upload_to_gdrive():
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication
    drive = GoogleDrive(gauth)
    Keyword arguments:
    drive -- GoogleDrive authorize object
    dl_location -- location of file to be uploaded
    filename -- filename of file to be uploaded
    folder_id -- folder id of Google Drive folder to upload to (gotten from URL)
    """
    f = drive.CreateFile({'title': filename, 'mimeType': 'text/csv',
        'parents': [{'kind': 'drive#fileLink', 'id': folder_id}]})
    f.SetContentFile(dl_location + filename)
    f.Upload()


@staticmethod
def validate_input_with_pre_defined_options(user_input, valid_options):
    """
        Method to check where use input in a valid option
        @params user_input: Input from user
        @params valid_options: Array of valid options
        @return Boolean: True, if input is valid else false
        """
    if user_input:
        user_input = user_input.lower()
        return user_input in valid_options
    return False


def format_list(resources):
    """
    Format comma-separated list of IDs from Django queryset.
    """
    return ', '.join(map(str, sorted(resources.values_list('id', flat=True))))


@classmethod
def fromdata(cls, data, header=None, valid=True, verify=True, **kwargs):
    """Construct frame from data and header.

        Note that since DADA files are generally very large, one would normally
        map the file, and then set pieces of it by assigning to slices of the
        frame.  See `~baseband.dada.base.DADAFileWriter.memmap_frame`.

        Parameters
        ----------
        data : `~numpy.ndarray`
            Array holding complex or real data to be encoded.
        header : `~baseband.dada.DADAHeader` or None
            If not given, will attempt to generate one using the keywords.
        valid : bool, optional
            Whether the data are valid (default: `True`). Note that this
            information cannot be written to disk.
        verify : bool, optional
            Whether or not to do basic assertions that check the integrity.
            Default: `True`.
        **kwargs
            If ``header`` is not given, these are used to initialize one.
        """
    if header is None:
        header = cls._header_class.fromvalues(verify=verify, **kwargs)
    payload = cls._payload_class.fromdata(data, header=header)
    return cls(header, payload, valid=valid, verify=verify)


def _set_smiles(compounds, id_, content):
    """Short description.

    Parameters
    ----------
    Compounds : dict
    id_ : str
    content : str
    """
    compounds[id_]['smiles'] = content


@classmethod
def from_json(cls, data, json_schema_class=None):
    """ JSON deserialization method that retrieves edge instance from its json representation

        If specific json schema is provided, it is utilized, and if not, a class specific is used
        """
    schema = (cls.json_schema if json_schema_class is None else
        json_schema_class())
    return schema.load(data)


def write_read_list(readset, bipartition, sample_components,
    numeric_sample_ids, output_file):
    """
	Write a list of reads that has been used for phasing to given file object.
	readset -- core.ReadSet object with reads to be written
	bipartition -- bipartition of reads, i.e. iterable with one entry from {0,1} for each read in readset
	sample_components -- a dictionary that maps each sample to its connected components

			Each component in turn is a dict that maps each variant position to a
			component, where a component is identified by the position of its
			left-most variant

	numeric_sample_ids -- core.NumericSampleIds object mapping sample names to numeric ids as stored in each read
	output_file -- file object to write to
	"""
    assert len(readset) == len(bipartition)
    numeric_id_to_name = numeric_sample_ids.inverse_mapping()
    for read, haplotype in zip(readset, bipartition):
        sample = numeric_id_to_name[read.sample_id]
        components = sample_components[sample]
        phaseset = components[read[0].position] + 1
        print(read.name, read.source_id, sample, phaseset, haplotype, len(
            read), read[0].position + 1, read[-1].position + 1, file=
            output_file)


def crypto_config_from_kwargs(fallback, **kwargs):
    """Pull all encryption-specific parameters from the request and use them to build a crypto config.

    :returns: crypto config and updated kwargs
    :rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict
    """
    try:
        crypto_config = kwargs.pop('crypto_config')
    except KeyError:
        try:
            fallback_kwargs = {'table_name': kwargs['TableName']}
        except KeyError:
            fallback_kwargs = {}
        crypto_config = fallback(**fallback_kwargs)
    return crypto_config, kwargs


def read_file(filename):
    """
    Read the entire contents of file.

    :param filename: Path to the file.
    :type filename: str

    :return: File contents
    :rtype: str
    """
    with open(filename, 'r') as file_obj:
        contents = file_obj.read()
    return contents


def enable(context):
    """ Enable workgroup action"""


def getAllAroundBRHL(possibleGenesD, rHitsL):
    """Given a matrix of reciprocal hit dictionaries in rHitsL, and a dict
of possible hits, return a list of all around best reciprocal hits. In
the form of a list of lists, where each sublist is one set of
orthologs."""
    aabrhHardCoreL = []
    genesL = list(possibleGenesD.keys())
    genesL.sort()
    for gene in genesL:
        hitsT = possibleGenesD[gene]
        isOrth = True
        for hit1Index in range(len(hitsT)):
            hit1 = hitsT[hit1Index]
            for hit2Index in range(hit1Index + 1, len(hitsT)):
                hit2 = hitsT[hit2Index]
                sp1sp2Dict = rHitsL[hit1Index + 1][hit2Index + 1]
                match = sp1sp2Dict.get(hit1)
                if match != hit2:
                    isOrth = False
                    break
            if not isOrth:
                break
        if isOrth:
            aabrhHardCoreL.append((gene,) + hitsT)
    return aabrhHardCoreL


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

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


def start_dependent_task(cls):
    """ Start this task and return its instance

		:return: WTask
		"""
    task = cls()
    task.start()
    return task


def select_same_group(group: str=''):
    """Select object in the same group

    :param group: Group, Name of the group to select
    :type group: str
    """
    pass


@classmethod
def from_network_info(cls, network_info):
    """Returns a list of IpPayload object based on the passed
        network_info.
        """
    ips = []
    if network_info is not None:
        for vif in network_info:
            for ip in vif.fixed_ips():
                ips.append(cls(label=vif['network']['label'], mac=vif[
                    'address'], meta=vif['meta'], port_uuid=vif['id'],
                    version=ip['version'], address=ip['address'],
                    device_name=vif['devname']))
    return ips


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 crisp(tr):
    """
    Calculates the crisp number achieved from type reduced IT2FS.

    Parameters
    ----------

    tr:
        Tuple (l, r)

        Type reduced IT2FS

    Returns
    -------
    float

    Returns the crisp number achieved from type reduced IT2FS.

    Examples
    --------

    >>> tr1 = (0.1, 0.3)
    >>> print(crisp(tr1))
    """
    return (tr[0] + tr[1]) / 2


def add_complements(marker_exp):
    """Adds columns representing gene complement to a gene expression matrix.

    Gene complements are represented simplistically: gene expression values for
    a given gene X are multiplied by -1 and become a new column, labeled X_negation.
    "High" expression values of X become "low" values of X_negation, and vice versa,
    where discrete expression corresponds to a "high" value, and discrete
    non-expression to a "low" value.

    marker_exp should have cell row labels, gene column labels, gene expression
    float values.

    :param marker_exp: gene expression DataFrame whose rows are cell
        identifiers, columns are gene identifiers, and values are float values
        representing gene expression.

    :returns: A DataFrame of same format as marker_exp, but with a new column
              added for each existing column label, representing the column
              label gene's complement.

    :rtype: pandas.DataFrame
    """
    for gene in marker_exp.columns:
        marker_exp[gene + '_negation'] = -marker_exp[gene]
    """
    for gene in marker_exp.columns:
        marker_exp[gene + '_c'] = max(marker_exp[gene]) - marker_exp[gene]
    """
    return marker_exp


@classmethod
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
    """
        Return the rational (numerator / denominator) value at *value_offset*
        in *stream_rdr* as a floating-point number. Only supports single
        values at present.
        """
    if value_count == 1:
        numerator = stream_rdr.read_long(value_offset)
        denominator = stream_rdr.read_long(value_offset, 4)
        return numerator / denominator
    else:
        return 'Multi-value Rational NOT IMPLEMENTED'


def _handle_string(val):
    """
    Replaces Comments: and any newline found.

    Input is a cell of type 'string'.
    """
    return val.replace('Comments: ', '').replace('\r\n', ' ')


def enable_domain_auto_renew(DomainName=None):
    """
    This operation configures Amazon Route 53 to automatically renew the specified domain before the domain registration expires. The cost of renewing your domain registration is billed to your AWS account.
    The period during which you can renew a domain name varies by TLD. For a list of TLDs and their renewal policies, see "Renewal, restoration, and deletion times" on the website for our registrar partner, Gandi. Route 53 requires that you renew before the end of the renewal period that is listed on the Gandi website so we can complete processing before the deadline.
    See also: AWS API Documentation

    :example: response = client.enable_domain_auto_renew(
        DomainName='string'
    )

    :type DomainName: string
    :param DomainName: [REQUIRED]
            The name of the domain that you want to enable automatic renewal for.

    :rtype: dict
    :return: {}

    """
    pass


def pytest_saltfactories_handle_key_auth_event(factories_manager, master_id,
    minion_id, keystate, payload):
    """
    This hook is called for every auth event on the masters
    """
    salt_key_cli = factories_manager.get_salt_key_cli(master_id)
    if keystate == 'pend':
        ret = salt_key_cli.run('--yes', '--accept', minion_id)
        assert ret.exitcode == 0


def clear():
    """Clear all indexes.
        """


def default_jwt_headers_callback(default_headers):
    """
    By default header typically consists of two parts: the type of the token,
    which is JWT, and the signing algorithm being used, such as HMAC SHA256
    or RSA. But we don't set the default header here we set it as empty which
    further by default set while encoding the token
    :return: default we set None here
    """
    return None


def evalcontextfunction(f):
    """This decorator can be used to mark a function or method as an eval
    context callable.  This is similar to the :func:`contextfunction`
    but instead of passing the context, an evaluation context object is
    passed.  For more information about the eval context, see
    :ref:`eval-context`.

    .. versionadded:: 2.4
    """
    f.evalcontextfunction = True
    return f


def getUserNames():
    """Get a sequence of names of the users which reside in the user folder.
        """


def getDesc(value):
    """
        Get the description for a given enumeration value.
        """


@staticmethod
def configuration_key_prefix():
    """Return "detector"."""
    return 'detector'


def advancedhelp():
    """Return help message for advanced commands."""
    message = 'a [verb]        : Analyze the current problem\n'
    message += 'ac [verb]       : Analyze from the Current position\n'
    message += (
        'all [verb]      : analyze all the problems in the current level\n')
    message += 'append pos      : append a position to book\n'
    message += 'ba [label]      : add current position to bookmark\n'
    message += 'bl              : list bookmark\n'
    message += 'bp pos          : add a specified position bookmark\n'
    message += 'br label        : read bookmark\n'
    message += 'check pos [verb]: check a specified position\n'
    message += 'config          : show and edit configuration\n'
    message += 'create [numbers]: create new problems and append to book\n'
    message += 'giveup [sec]    : reanalyze giveup positions\n'
    message += 'html            : see image in web browzer as html\n'
    message += 'jpg             : draw jpeg image\n'
    message += 'jm              : draw jpeg image with mark\n'
    message += 'import          : import file2\n'
    message += 'initial         : go back to initial position\n'
    message += 'reanalyze       : reanalyze whole book\n'
    message += 'solve pos [verb]: solve a specified position\n'
    message += (
        'sp              : Solve Partially with naked or hidden single\n')
    message += 'u               : show URL of the current position'
    return message


def avoid_string_duplication(list_str):
    """Individualize repated string items."""
    new_list = list()
    for item in list_str:
        new_item = item
        while new_item in new_list:
            new_item += '#'
        new_list.append(new_item)
    return new_list


@classmethod
def is_overlapping_cds(cls, first, second):
    """
        :param first: first ORF to check for overlap
        :param second: second ORF to check for overlap
        :rtype bool
        """
    if first == second or cls.overlap((first.thick_start, first.thick_end),
        (second.thick_start, second.thick_end)) < 0:
        return False
    return True


def select_less():
    """Deselect spline points at the boundary of each selection region

    """
    pass


@classmethod
def __allow__(cls, name: str) ->bool:
    """Tell if the given name is an allowed python prop name.

        Parameters
        ----------
        name : str
            The name to check.

        Returns
        -------
        bool
            ``True`` if the name is allowed, ie defined as a prop, or starting with ``aria_``
            or ``data_``.  ``False`` otherwise.

        """
    return name in cls.__types__ or name.startswith('data_'
        ) or name.startswith('aria_')


def p_trait_modifiers_list(p):
    """trait_modifiers_list : trait_modifiers_list trait_modifier
                            | empty"""
    if len(p) == 3:
        p[0] = p[1] + [p[2]]
    else:
        p[0] = []


def material_slot_deselect():
    """Deselect by active material slot

    """
    pass


def get_response_message(message, data, final_length):
    """get the response message

    message -- previous received message
    data - new received messages
    """
    if message == b'':
        _s = data.split(b'#')
        final_length = int(_s[0].decode())
    message += data
    try:
        if len(message.decode()) == final_length + len(str(final_length)) + 1:
            return message, final_length, True
    except UnicodeDecodeError:
        pass
    return message, final_length, False


def _cos(attrs, inputs, proto_obj):
    """Elementwise cosine of input array."""
    return 'cos', attrs, inputs


def transition(value, maximum, start, end):
    """ Transition between two values.

    :param value: Current iteration.
    :param maximum: Maximum number of iterations.
    :param start: Start value.
    :param end: End value.
    :returns: Transitional value.
    """
    return round(start + (end - start) * value / maximum, 2)


@classmethod
def execute_managed_notebook(cls, nb_man, kernel_name, **kwargs):
    """An abstract method where implementation will be defined in a subclass."""
    raise NotImplementedError(
        "'execute_managed_notebook' is not implemented for this engine")


def tofloat(a):
    """  parse string list/tuple to float list """
    b = []
    for i in a:
        b.append(float(i))
    return b


def return_tag_action(row, action_dict):
    """
    Default action function for tables. This function returns the tag for the row of data. Used by the **TABLE_RETURN_TAG** action.

    :param List row: the data associated with the selected row
    :param Dict action_dict: the dictionary of values associated with the action - ignored in this function

    :return: The tag for the selected row of the table.
    """
    return row.tag


def fmt(docstr):
    """Format a docstring for use as documentation in sample config."""
    docstr = docstr.replace('\n', ' ')
    docstr = docstr.strip()
    return docstr


def check_pool_create_libvirt(conn, poolname, logger):
    """Check the result of create storage pool inside libvirt """
    pool_names = conn.listStoragePools()
    logger.info('poolnames is: %s' % pool_names)
    try:
        pool_names.index(poolname)
    except ValueError:
        logger.info('check_pool_create %s storage pool pass' % poolname)
        return False
    return True


def AddSNConstant(*args, **kwargs):
    """ Stub Anduin function."""
    print('AddSNConstant', args, kwargs)


def mtf_ts_extractor(mtf, freqs):
    """Extract the T and S MTF from a PSF object.

    Parameters
    ----------
    mtf : `MTF`
        MTF object
    freqs : iterable
        set of frequencies to extract

    Returns
    -------
    tan : `numpy.ndarray`
        array of tangential MTF values
    sag : `numpy.ndarray`
        array of sagittal MTF values

    """
    tan = mtf.exact_tan(freqs)
    sag = mtf.exact_sag(freqs)
    return tan, sag


@classmethod
def find_one(cls, filters=None, order=()):
    """
        Find a single document in database.
        """
    try:
        doc = next(cls.find(filters, limit=1, order=order))
    except StopIteration:
        doc = None
    return doc


@classmethod
def get_ad_service_interface_for_provider(cls, provider_name):
    """
        Staticmethod, returns the interface class for a given ad service
        provider name

        @param provider_name: str, one of enum
            parselmouth.constants.ParselmouthProviders
        @return: descendant of
            parselmouth.adapters.abstract_interface.AbstractInterface
        """
    client_interface = cls.ProviderInterfaceMap.get(provider_name)
    if not client_interface:
        raise ValueError('There is no interface defined for provider: %s' %
            provider_name)
    return client_interface


def strip_headers(headers):
    """
    Strips the headers attached to the instance of any header beginning
    with a colon that ``hyper`` doesn't understand. This method logs at
    warning level about the deleted headers, for discoverability.
    """
    for name in list(headers.keys()):
        if name.startswith(b':'):
            del headers[name]


def cuda_error():
    """Returns None or an exception if the CUDA driver fails to initialize.
    """
    return None


@staticmethod
def get_body_of_object(obj):
    """
        Will load a S3 object and download it content
        :param obj: S3 Object
        :return: str it body data
        """
    if not obj:
        raise ValueError('S3 object cannot be None')
    object_body = obj.get()
    body_stream = object_body['Body']
    data = body_stream.read()
    return data


@classmethod
def get_site_names(cls):
    """
        Get list of names of observatories for use with
        `~astropy.coordinates.EarthLocation.of_site`.

        .. note::
            When this function is called, it will first attempt to
            download site information from the astropy data server.  If it
            cannot (i.e., an internet connection is not available), it will fall
            back on the list included with astropy (which is a limited and dated
            set of sites).  If you think a site should be added, issue a pull
            request to the
            `astropy-data repository <https://github.com/astropy/astropy-data>`_ .

        Returns
        -------
        names : list of str
            List of valid observatory names

        See Also
        --------
        of_site : Gets the actual location object for one of the sites names
                  this returns.
        """
    return cls._get_site_registry().names


def redirect_instance_extid(instance_type, rt):
    """generate the ext intance id of a redirection VPN instance"""
    return 'redirect-to-%s-%s' % (instance_type, rt.replace(':', '_'))


def _import_pil():
    """Import scikit-image, with slightly modified `ImportError` message"""
    try:
        import PIL
    except ImportError:
        raise ImportError('PIL/Pillow is required to use this function.')
    return PIL


def start(st_reg_number):
    """Checks the number valiaty for the Bahia state"""
    weights_second_digit = range(len(st_reg_number) - 1, 1, -1)
    weights_first_digit = range(len(st_reg_number), 1, -1)
    second_digits = st_reg_number[-1:]
    number_state_registration = st_reg_number[0:len(st_reg_number) - 2]
    digits_state_registration = st_reg_number[-2:]
    sum_second_digit = 0
    sum_first_digit = 0
    if len(st_reg_number) != 8 and len(st_reg_number) != 9:
        return False
    if st_reg_number[-8] in ['0', '1', '2', '3', '4', '5', '8']:
        for i in weights_second_digit:
            sum_second_digit = sum_second_digit + i * int(st_reg_number[-i - 1]
                )
        second_digits_check = 10 - sum_second_digit % 10
        if sum_second_digit % 10 == 0 or sum_second_digit % 11 == 1:
            second_digits_check = '0'
        if str(second_digits_check) != second_digits:
            return False
        digit_two = number_state_registration + str(second_digits_check)
        for i in weights_first_digit:
            sum_first_digit = sum_first_digit + i * int(digit_two[-i + 1])
        first_digits_check = 10 - sum_first_digit % 10
        if sum_first_digit % 10 == 0 or sum_first_digit % 10 == 1:
            first_digits_check = '0'
        digits_calculated = str(first_digits_check) + str(second_digits_check)
        return digits_calculated == digits_state_registration
    elif st_reg_number[-8] in ['6', '7', '9']:
        for i in weights_second_digit:
            sum_second_digit = sum_second_digit + i * int(st_reg_number[-i - 1]
                )
        second_digits_check = 11 - sum_second_digit % 11
        if sum_second_digit % 11 == 0 or sum_second_digit % 11 == 1:
            second_digits_check = '0'
        if str(second_digits_check) != second_digits:
            return False
        digit_two = number_state_registration + str(second_digits_check)
        for i in weights_first_digit:
            sum_first_digit = sum_first_digit + i * int(digit_two[-i + 1])
        first_digits_check = 11 - sum_first_digit % 11
        if sum_first_digit % 11 == 0 or sum_first_digit % 11 == 1:
            first_digits_check = '0'
        digits_calculated = str(first_digits_check) + str(second_digits_check)
        return digits_calculated == digits_state_registration


def set_name_ds(name_ds):
    """Set the dataset name in regression; return generic name if user
    provides no explicit name."

    Parameters
    ----------

    name_ds     : string
                  User provided dataset name.

    Returns
    -------

    name_ds     : string

    """
    if not name_ds:
        name_ds = 'unknown'
    return name_ds


def get_supported_type():
    """Get a list of the data types that are supported by yggdrasil.

    Returns:
        list: The names of data types supported by yggdrasil.

    """
    from yggdrasil.metaschema.datatypes import get_registered_types
    return list(get_registered_types().keys())


def get_graph_solution(x):
    """Get graph solution from binary string.

    Args:
        x (numpy.ndarray) : binary string as numpy array.

    Returns:
        numpy.ndarray: graph solution as binary numpy array.
    """
    return 1 - x


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 monet_escape(data):
    """
    returns an escaped string
    """
    data = str(data).replace('\\', '\\\\')
    data = data.replace("'", "\\'")
    return "'%s'" % str(data)


def convertAttributeProto(onnx_arg):
    """
    Convert an ONNX AttributeProto into an appropriate Python object
    for the type.

    NB: Tensor attribute gets returned as the straight proto.
    """
    if onnx_arg.HasField('f'):
        return onnx_arg.f
    elif onnx_arg.HasField('i'):
        return onnx_arg.i
    elif onnx_arg.HasField('s'):
        return onnx_arg.s
    elif onnx_arg.HasField('t'):
        return onnx_arg.t
    elif len(onnx_arg.floats):
        return list(onnx_arg.floats)
    elif len(onnx_arg.ints):
        return list(onnx_arg.ints)
    elif len(onnx_arg.strings):
        return list(onnx_arg.strings)
    else:
        raise ValueError('Unsupported ONNX attribute: {}'.format(onnx_arg))


def create_table(bucketname):
    """ Returns query for behold table in Athena. """
    query_string = f"""CREATE EXTERNAL TABLE behold (
            eventversion STRING,
            useridentity STRUCT<
                        type:STRING,
                        principalid:STRING,
                        arn:STRING,
                        accountid:STRING,
                        invokedby:STRING,
                        accesskeyid:STRING,
                        userName:STRING,
            sessioncontext:STRUCT<
            attributes:STRUCT<
                        mfaauthenticated:STRING,
                        creationdate:STRING>,
            sessionissuer:STRUCT<
                        type:STRING,
                        principalId:STRING,
                        arn:STRING,
                        accountId:STRING,
                        userName:STRING>>>,
            eventtime STRING,
            eventsource STRING,
            eventname STRING,
            awsregion STRING,
            sourceipaddress STRING,
            useragent STRING,
            errorcode STRING,
            errormessage STRING,
            requestparameters STRING,
            responseelements STRING,
            additionaleventdata STRING,
            requestid STRING,
            eventid STRING,
            resources ARRAY<STRUCT<
                        ARN:STRING,
                        accountId:STRING,
                        type:STRING>>,
            eventtype STRING,
            apiversion STRING,
            readonly STRING,
            recipientaccountid STRING,
            serviceeventdetails STRING,
            sharedeventid STRING,
            vpcendpointid STRING
            )
            PARTITIONED BY (account string, region string, year string, month string)
            ROW FORMAT SERDE 'com.amazon.emr.hive.serde.CloudTrailSerde'
            STORED AS INPUTFORMAT 'com.amazon.emr.cloudtrail.CloudTrailInputFormat'
            OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
            LOCATION 's3://{bucketname}/AWSLogs/';
            """
    return query_string, 'setup/create_table'


def indent(n: int) ->str:
    """Return `n` indents."""
    return '  ' * n


def update_Qi(Qval, reward, alpha):
    """ update q-value of selected action, given reward and alpha
    """
    return Qval + alpha * (reward - Qval)


def requires_grad(m, set_val):
    """If `set_val` is not set return `requires_grad` of first param, else set `requires_grad` on all params to `set_val`"""
    params = list(m.parameters())
    if not params:
        return None
    if set_val is None:
        return params[0].requires_grad
    for p in params:
        p.requires_grad = set_val


@classmethod
def check(cls, control_instance):
    """ Check if a controller widget controller control is filled correctly.

        Parameters
        ----------
        cls: ControllerControlWidget (mandatory)
            a ControllerControlWidget control
        control_instance: QFrame (mandatory)
            the control widget we want to validate
        """
    pass


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

        :param TrustedNonTeamMemberLogInfo val:
        :rtype: ContextLogInfo
        """
    return cls('trusted_non_team_member', val)


def __call__(language):
    """Return a parent folder into which a new translation can be added"""


def configs_to_dict(configs):
    """
    Converts a config parser object into a dictionary.

    :param configs:
        The config parser instance to convert into a dictionary.
    :return:
        A dictionary representation of the config parser.
    """
    out = {}
    for section in configs.sections():
        out[section] = dict(configs.items(section))
    return out


def propertyIds():
    """Return a list of property ids.
        """


def last(iterable):
    """
    Get the last item in the iterable.
    Warning, this can be slow due to iter step by step to last one.
    """
    item = None
    for item in iterable:
        pass
    return item


def allowed_roles():
    """Private method which return a list of roles that that user
        can have.
        """


@staticmethod
def status(value):
    """Return the palette for a STATUS cell."""
    return 'status_' + value


def list_platform_versions(Filters=None, MaxRecords=None, NextToken=None):
    """
    Lists the available platforms.
    See also: AWS API Documentation

    :example: response = client.list_platform_versions(
        Filters=[
            {
                'Type': 'string',
                'Operator': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxRecords=123,
        NextToken='string'
    )

    :type Filters: list
    :param Filters: List only the platforms where the platform member value relates to one of the supplied values.
            (dict) --Specify criteria to restrict the results when listing custom platforms.
            The filter is evaluated as the expression:
            Type Operator Values[i]
            Type (string) --The custom platform attribute to which the filter values are applied.
            Valid Values: PlatformName | PlatformVersion | PlatformStatus | PlatformOwner
            Operator (string) --The operator to apply to the Type with each of the Values .
            Valid Values: = (equal to) | != (not equal to) | ```` (less than) | = (less than or equal to) | ```` (greater than) | = (greater than or equal to) | contains | begins_with | ends_with
            Values (list) --The list of values applied to the custom platform attribute.
            (string) --

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of platform values returned in one call.

    :type NextToken: string
    :param NextToken: The starting index into the remaining list of platforms. Use the NextToken value from a previous ListPlatformVersion call.

    :rtype: dict
    :return: {
        'PlatformSummaryList': [
            {
                'PlatformArn': 'string',
                'PlatformOwner': 'string',
                'PlatformStatus': 'Creating'|'Failed'|'Ready'|'Deleting'|'Deleted',
                'PlatformCategory': 'string',
                'OperatingSystemName': 'string',
                'OperatingSystemVersion': 'string',
                'SupportedTierList': [
                    'string',
                ],
                'SupportedAddonList': [
                    'string',
                ]
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def datetime_format(value):
    """Validate the correct format of a datetime string and deserialize."""
    from msrest.serialization import Deserializer
    from msrest.exceptions import DeserializationError
    try:
        datetime_obj = Deserializer.deserialize_iso(value)
    except DeserializationError:
        message = 'Argument {} is not a valid ISO-8601 datetime format'
        raise ValueError(message.format(value))
    return datetime_obj


def arcsin(attrs, inputs, proto_obj):
    """Elementwise inverse sin of input array."""
    return 'arcsin', attrs, inputs


def exp_string(expansion):
    """Return the string to be expanded"""
    if isinstance(expansion, str):
        return expansion
    return expansion[0]


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

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


def interpolate(config):
    """Interpolate the parsed config, but do not output anything."""
    for section in config.sections():
        options = config.options(section)
        for option in options:
            config.get(section, option)


def metadata_listdir(name):
    """List of metadata names in the directory (like ``os.listdir()``)"""


@staticmethod
def _parse_dn(dn):
    """Parses the pod, node, and slot from a
           distinguished name of the node.

           :param dn: str - distinguished name

           :returns: pod, node, slot strings
        """
    name = dn.split('/')
    pod = str(name[1].split('-')[1])
    node = str(name[2].split('-')[1])
    slot = str(name[5].split('-')[1])
    return pod, node, slot


def _generate_class_definition(name):
    """ Generates class definition for humlist, humtuple, humstr classes.
	"""
    class_definition = (
        """
class hum{name}({name}):
	''' Class, that is the same to {name} type, but with normal indexes.
	revision: 3
	'''
"""
        .format(name=name))
    class_definition += """
	def __getitem__(self, keys):
		''' Is launched when "a[0]".
		'''
		keys = change_indexes_1_to_0(keys)
		return self.__class__.__base__.__getitem__(self, keys)
"""
    class_definition += """
	def __setitem__(self, keys, value):
		''' Set self[key] to value. If A = [1,2,3], than A[1] = 5 will change A to: [5,2,3]
		'''
		keys = change_indexes_1_to_0(keys)
		self.__class__.__base__.__setitem__(self, keys, value) # keys - итерируемый объект: (slice(1,2,1), ) или (1, )
"""
    class_definition += """
	def __delitem__(self, keys):
		''' Delete self[key]. If A = [1,2,3], than A[1] = 5 will change A so: [5,2,3]'''
		keys = change_indexes_1_to_0(keys)
		self.__class__.__base__.__delitem__(self, keys)
"""
    class_definition += """
	def get(self, keys):
		'''Get method for sequences.
		Returns value of element on position (keys). If such element is absent - returns None.
		Used in: humlist, humtuple, humstr.
		rev. 1
		'''
		try:
			value = self.__getitem__(keys)
		except (IndexError, KeyError):
			value = None
		return value
"""
    class_definition += """
	def index(self, value, *positions):
		'''Index method for sequences.
		Returns index of element with specified value (optional in positions).
		rev. 1
		'''

		length = len(positions)

		if length >= 3:
			raise TypeError('index() takes at most 3 arguments ({0} given)'.format(length+1))
		elif length == 2:
			start = positions[0] - 1
			end = positions[1]
			return self.__class__.__base__.index(self, value, start, end) + 1
		elif length == 1:
			start = positions[0] - 1
			return self.__class__.__base__.index(self, value, start) + 1
		else:  # если нет вообще позиций
			return self.__class__.__base__.index(self, value) + 1
"""
    class_definition += (
        """
	def {method}(self, *args):
		''' Method for creating hum{name}. Is launched when:
		a = humlist(1, 2)
		'''

		classname = 'hum{name}'  # because immutable objects's instances don't have self.__class__ before creation
		length = len(args)

		if length > 1:
			if classname == 'humstr':
				result = ''
				for some in args:
					result += str(some)
				{retn}{name}.{method}(self, result)  # retn can be "return ", can be absent
			else:
				{retn}{name}.{method}(self, args)

		elif length == 1:
			if args[0].__class__ == tuple:
				{retn}{name}.{method}(self, args[0])  # tuple
			else:
				if classname == 'humstr':
					{retn}{name}.{method}(self, args[0])  # one element
				else:
					{retn}{name}.{method}(self, args)  # tuple with one element

		else:  # length == 0
			{retn}{name}.{method}(self)"""
        .format(name=name, method='__init__' if name == 'list' else
        '__new__', retn='' if name == 'list' else 'return '))
    insert_definition = """
	def insert(self, position, value):
		position = changeIndexes(position)
		list.insert(self, position, value)
"""
    find_definition = """
	def find(self, value):
		result = str.find(self, value)
		if result != -1:
			return result + 1
		else:
			return result

"""
    rindex_definition = """
	def rindex(self, value, *positions):
		length = len(positions)

		if length >= 3:
			raise TypeError('index() takes at most 3 arguments ({0} given)'.format(length+1))
		elif length == 2:
			start = positions[0] - 1
			end = positions[1]
			return self.__class__.__base__.rindex(self, value, start, end) + 1
		elif length == 1:
			start = positions[0] - 1
			return self.__class__.__base__.index(self, value, start) + 1
		else:  # если нет вообще позиций
			return self.__class__.__base__.index(self, value) + 1
"""
    """format_definition = ""\"
	def format(self, *args, **kwargs):
		if args:
			return str.format(self, '', *args, **kwargs)
		else:
			return str.format(self, *args, **kwargs)
""\""""
    if name == 'list':
        class_definition += insert_definition
    elif name == 'tuple':
        pass
    elif name == 'str':
        class_definition += find_definition
        class_definition += rindex_definition
    return class_definition


def auto_type(string):
    """
    Try and convert a string to an integer or float
    """
    try:
        return int(string)
    except:
        try:
            return float(string)
        except:
            return string


def create_cube(bm: 'bmesh.types.BMesh', size: float, matrix:
    'mathutils.Matrix', calc_uvs: bool) ->dict:
    """Creates a cube.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param size: size of the cube
    :type size: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def interval_noday_unpack(data, dl_unpack=dl_unpack, mktimetuple=mktimetuple):
    """
	Given a serialized interval without a day component, return the triple:

		(month, day(always zero), (seconds, microseconds))
	"""
    tim, month = dl_unpack(data)
    return month, 0, mktimetuple(tim)


def _check_falsy(value):
    """Return true if *value* is falsy."""
    return not bool(value)


def vertex_weight_paste(weight_group: int=-1):
    """Copy this group’s weight to other selected verts (disabled if vertex group is locked)

    :param weight_group: Weight Index, Index of source weight in active vertex group
    :type weight_group: int
    """
    pass


def toGraphicsObjectIfPossible(item):
    """Return the item as a QGraphicsObject if possible.

    This function is intended as a workaround for a problem with older
    versions of PyQt (< 4.9), where methods returning 'QGraphicsItem *'
    lose the type of the QGraphicsObject subclasses and instead return
    generic QGraphicsItem wrappers.
    """
    if item is None:
        return None
    obj = item.toGraphicsObject()
    return item if obj is None else obj


def get_default_cve_data(severity):
    """
    Return some default CVE metadata for the given severity
    :param severity: Severity
    :return: score, vectorString
    """
    vectorString = 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H'
    score = 9.0
    severity = severity.upper()
    attackComplexity = severity
    if severity == 'LOW':
        score = 2.0
        attackComplexity = 'HIGH'
        vectorString = 'CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N'
    elif severity in ['MODERATE', 'MODERATE']:
        score = 5.0
        severity = 'MEDIUM'
        vectorString = 'CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L'
    elif severity == 'HIGH':
        score = 7.5
        attackComplexity = 'LOW'
        vectorString = 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L'
    return score, severity, vectorString, attackComplexity


def get_release_tag_string(check_name, version_string):
    """
    Compose a string to use for release tags
    """
    if check_name:
        return f'{check_name}-{version_string}'
    else:
        return version_string


def find(value, node):
    """Find node with val equal to value"""
    while node:
        if value < node.val:
            node = node.left
        elif value > node.val:
            node = node.right
        else:
            return node


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


def get_closest_distance_info(source=None, targets=None, mode='close',
    res_mode='point', source_pivot='rp', target_pivot='rp'):
    """
    Returns the closest return based on a source and target and given modes
    :param source: str, base object to measure from
    :param targets: list<stt>, list of object types
    :param mode: str, what mode we are checking dat from (close or far)
    :param res_mode: str
        - object: return the [closest] target
        - point: retur the [closest] point
        - component: resturn the [closest] base component
        - pointOnSurface: [closest] point on the target shape(s)
        - pointOnSurfaceLoc: [closest] point on target shape(s) loc'd
        - shape: gets closest point on every shape, returns closest
    :param source_pivot: str
    :param target_pivot:str
    :return: tuple(res, distance)
    """
    fn_name = 'get_closest_distance_info'

    def get_from_targets(source_pos, targets, target_pivot, res_mode, mode):
        pass
    dist_modes_dict = {'close': ['closest', 'c', 'near'], 'far': [
        'furthest', 'long']}
    source = None


def properties_remove(data_path: str='', property: str=''):
    """Internal use (edit a property data_path)

    :param data_path: Property Edit, Property data_path edit
    :type data_path: str
    :param property: Property Name, Property name edit
    :type property: str
    """
    pass


def delete(message):
    """Remove the given message from the source."""


def has_x11():
    """Is Qt build against X11 server.
    """
    try:
        from AnyQt.QtX11Extras import QX11Info
        return True
    except ImportError:
        return False


def _find_end(tokens):
    """
    Find index of closing parenthesis. Based on function from Rhomboid at
    https://gist.github.com/Rhomboid/5994999.

    Parameters
    ----------
    tokens : list of str
        List of strings representing molecular formula.

    Return
    ------
    idx : int
        Index of closing parenthesis.
    """
    count = 0
    for idx, t in enumerate(tokens):
        if t == ')':
            count -= 1
            if count == 0:
                return idx
        elif t == '(':
            count += 1
    raise ValueError('Unmatched parentheses')


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


def stats_table_region_label_column_name():
    """
    Returns the name of the column that contains the region names for the table in stats files. The name is identical for all standard Freesurfer parcellation and segmentation stats files (aseg.stats, ?h.aparc.stats, ?h.aparc.a2009s.stats, and ?h.aparc.DKTatlas.stats), so the current version returns a fixed string.
    """
    return 'StructName'


@classmethod
def __instancehook__(cls, other):
    """Check if the other instance implements the interface."""
    for attribute in cls.__abstractmethods__:
        if not hasattr(other, attribute):
            return NotImplemented
    return True


def where(iterable, properties):
    """
     Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.

     params: iterable, properties
         iterable-> a list/generator of dictionaries
         properties-> key value pairs which need to be in a dictionary.

     Examples:
    >>> list(_.where(list_of_plays, {author: "Shakespeare", year: 1611}))
    >>> [{title: "Cymbeline", author: "Shakespeare", year: 1611}, {title: "The Tempest", author: "Shakespeare", year: 1611}]

    """
    items_to_be_checked = properties.items()
    for dictionary in iterable:
        if not isinstance(dictionary, dict):
            raise TypeError(
                '"array" should be a collection of dictionaries only')
        if items_to_be_checked <= dictionary.items():
            yield dictionary


def get_object_or_none(klass, *args, **kwargs):
    """
        Uses get() to return an object or None if the object does not exist.

        klass may be a Model, Manager, or QuerySet object. All other passed
        arguments and keyword arguments are used in the get() query.
    """
    from django.shortcuts import _get_queryset
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        return None


def trailing_whitespace(physical_line):
    """Trailing whitespace is superfluous.

    The warning returned varies on whether the line itself is blank, for easier
    filtering for those who want to indent their blank lines.

    Okay: spam(1)\\n#
    W291: spam(1) \\n#
    W293: class Foo(object):\\n    \\n    bang = 12
    """
    physical_line = physical_line.rstrip('\n')
    physical_line = physical_line.rstrip('\r')
    physical_line = physical_line.rstrip('\x0c')
    stripped = physical_line.rstrip(' \t\x0b')
    if physical_line != stripped:
        if stripped:
            return len(stripped), 'W291 trailing whitespace'
        else:
            return 0, 'W293 blank line contains whitespace'


def add_n(*args, **kwargs):
    """Adds all input arguments element-wise.

    .. math::
       add\\_n(a_1, a_2, ..., a_n) = a_1 + a_2 + ... + a_n

    ``add_n`` is potentially more efficient than calling ``add`` by `n` times.

    The storage type of ``add_n`` output depends on storage types of inputs

    - add_n(row_sparse, row_sparse, ..) = row_sparse
    - add_n(default, csr, default) = default
    - add_n(any input combinations longer than 4 (>4) with at least one default type) = default
    - otherwise, ``add_n`` falls all inputs back to default storage and generates default storage

    Defined in src/operator/tensor/elemwise_sum.cc:L155
    This function support variable length of positional input.

    Parameters
    ----------
    args : Symbol[]
        Positional input arguments

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

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


def p_get(item, key, default=None):
    """ 根据key读取item中的数据，支持字典、数组、对象等

    :param item: 原始数据
    :param key: 用于提取的key
    :param default: 提取失败的默认值
    """
    if isinstance(item, dict):
        return item.get(key, default)
    if isinstance(item, (list, tuple)) and isinstance(key, int):
        if len(item) <= key:
            raise IndexError('index out of range')
        return item[key]
    if hasattr(item, key):
        return getattr(item, key)
    return default


def locale_negotiator(request):
    """
    Locale negotiator.

    It sets best suited locale variable for given user:

    1. Check for presence and value of **request._LOCALE_** value
    2. Then tries the address url, if the first part has locale indicator.
    3. It checks cookies, for value set here
    4. Tries to best match accepted language for browser user is visiting
        website with
    5. Defaults to **localize.locales.default** configuration setting value

    :param pyramid.request.Request request: a request object
    :returns: locale name
    :rtype: str
    """
    available_languages = request.registry['config'].localize.locales.available
    locale = request.registry['config'].localize.locales.default
    route_elements = request.path.split('/')
    if hasattr(request, '_LOCALE_'
        ) and request._LOCALE_ in available_languages:
        locale = request._LOCALE_
    elif len(route_elements[1]) == 2 and route_elements[1
        ] in available_languages:
        locale = route_elements[1]
    elif request.cookies and '_LOCALE_' in request.cookies and request.cookies[
        '_LOCALE_'] in available_languages:
        locale = request.cookies['_LOCALE_']
    elif request.accept_language:
        locale = request.accept_language.best_match(available_languages)
    return locale


@staticmethod
def _calculate_text_coordinates(image_h: int, image_w: int) ->list:
    """
        Functionality to calculate text coordinates

        :param image_shape: tuple of shape (h, w, _)
        :return: list of coordinates to place text
        """
    total_w = 2 * image_w
    text_x_location = image_h + 70
    y_1 = int(total_w * 0.2)
    y_2 = int(total_w * 0.73)
    return [(y_1, text_x_location), (y_2, text_x_location)]


def unsetPermissionFromRole(permission_id, role_id):
    """Clear the setting of the permission to the role.
        """


def get_input(*args):
    """
    A mockable input() function.
    """
    return input(*args)


@staticmethod
def chunk(start_idx, end_idx, condition_func):
    """
        The method that actually creates groups of characters satisfying the test method
        and not satisfying it from the given range within the input string.

        :param start_idx: first char of the range to be chunked
        :param end_idx: last char
        :param condition_func: test method
        :type start_idx: int
        :type end_idx: int
        :type condition_func: callable
        :return: the chunk indices with True/False instead of the chunk markers
        :rtype: list of tuples containing each: a bool (matched/not the test method) and the indices
        """
    chunked = []
    start = start_idx
    length = 0
    prev_state = -1
    current_state = -1
    for i in range(start_idx, end_idx):
        current_state = condition_func(i)
        if prev_state == -1:
            prev_state = current_state
        if current_state == prev_state:
            length += 1
        else:
            chunked.append((prev_state, start, length))
            prev_state = current_state
            start += length
            length = 1
    if length != 0:
        if current_state == prev_state:
            if start + length < end_idx:
                length += 1
        chunked.append((prev_state, start, length))
    return chunked


def is_right_sensor(sensor, sensor_types):
    """
    Check if sensor in the list of sensor_types
    """
    for stype in sensor_types:
        if stype in sensor:
            return True
    return False


def ocean_bake(modifier: str='', free: bool=False):
    """Bake an image sequence of ocean data

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    :param free: Free, Free the bake, rather than generating it
    :type free: bool
    """
    pass


def is_unknown_citation(citation):
    """Checks if the citation got recognized as one of the known types.
    """
    knownTypes = ['BOOK', 'JOURNAL', 'DOI', 'ISBN', 'RECID']
    for citation_element in citation:
        if citation_element['type'] in knownTypes:
            return False
    return True


def make_R_install_option(opt, values, cmdline=False):
    """
    Make option list for install.packages, to specify in R environment.
    """
    txt = ''
    if values:
        if cmdline:
            txt = ' --%s="%s' % (opt, values[0])
        else:
            txt = '%s=c("%s' % (opt, values[0])
        for i in values[1:]:
            txt += ' %s' % i
        if cmdline:
            txt += '"'
        else:
            txt += '")'
    return txt


@classmethod
def _find(cls, paths):
    """Given a list of files or directories, try to detect python interpreters amongst them.

    Returns an iterator over PythonInterpreter objects.
    """
    return cls._identify_interpreters(filter=cls._matches_binary_name,
        paths=paths)


def smart_map(func, i, *args, **kwargs):
    """
    将单个对象或列表中的每个项传入给定的函数，并返回单个结果或列表结果，类似于 map 函数

    :param func: 传入到的函数
    :param i: 列表或单个对象
    :param args: func 函数所需的 args
    :param kwargs: func 函数所需的 kwargs
    :return: 若传入的为列表，则以列表返回每个结果，反之为单个结果
    """
    if isinstance(i, (list, tuple, set)):
        return list(map(lambda x: func(x, *args, **kwargs), i))
    else:
        return func(i, *args, **kwargs)


@classmethod
def get_dialect_cls(cls, url):
    """Given a URL, return the :class:`.Dialect` that will be used.

        This is a hook that allows an external plugin to provide functionality
        around an existing dialect, by allowing the plugin to be loaded
        from the url based on an entrypoint, and then the plugin returns
        the actual dialect to be used.

        By default this just returns the cls.

        .. versionadded:: 1.0.3

        """
    return cls


def cat(seq, dim):
    """Concat the sequence of tensors in the given dimension.

    Parameters
    ----------
    seq : list of Tensor
        The tensor sequence.
    dim : int
        The concat dim.

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


@classmethod
def patch(cls):
    """
        TODO: Improve docstring and refactor implementation in Hive
        """
    pass


def getTradeSummaryFormLocations(ws):
    """
    Find the Trade Summary Forms within the excel doc and save their location in tradeLoc
    trades.max_row
    :params:ws: The openpyxl Worksheet object to search
    """
    loc = list()
    for row in ws.iter_rows():
        val = row[0].value
        if val and len(val) > 3 and len(val) < 15:
            if 'short' in val.lower() or 'long' in val.lower():
                r = row[0].row
                loc.append(r)
    return loc


def calc_temp(Data_ref, Data):
    """
    Calculates the temperature of a data set relative to a reference.
    The reference is assumed to be at 300K.

    Parameters
    ----------
    Data_ref : DataObject
        Reference data set, assumed to be 300K
    Data : DataObject
        Data object to have the temperature calculated for

    Returns
    -------
    T : uncertainties.ufloat
        The temperature of the data set
    """
    T = 300 * (Data.A * Data_ref.Gamma / (Data_ref.A * Data.Gamma))
    Data.T = T
    return T


def zeta_none(T, P):
    """n-c-a: no interaction effect."""
    valid = T > 0
    zeta = 0
    return zeta, valid


def query(cls, query, maxresult=-1, catcherrors=True, normalize=True):
    """Run a prolog query and return a generator.
        If the query is a yes/no question, returns {} for yes, and nothing for no.
        Otherwise returns a generator of dicts with variables as keys.

        >>> prolog = Prolog()
        >>> prolog.assertz("father(michael,john)")
        >>> prolog.assertz("father(michael,gina)")
        >>> bool(list(prolog.query("father(michael,john)")))
        True
        >>> bool(list(prolog.query("father(michael,olivia)")))
        False
        >>> print sorted(prolog.query("father(michael,X)"))
        [{'X': 'gina'}, {'X': 'john'}]
        """
    return cls._QueryWrapper()(query, maxresult, catcherrors, normalize)


def seal_on_store(protocol):
    """
    Implicitly adds seal/cover instructions to the end of a run for containers
    that do not have a cover.   Cover type applied defaults first to
    "seal" if its within the capabilities of the container type, otherwise
    to "cover".

    Example Usage:

        .. code-block:: python

            def example_method(protocol, params):
            cont = params['container']
            p.transfer(cont.well("A1"), cont.well("A2"), "10:microliter")
            p.seal(cont)
            p.unseal(cont)
            p.cover(cont)
            p.uncover(cont)

    Autoprotocol Output:

        .. code-block:: json

            {
              "refs": {
                "plate": {
                  "new": "96-pcr",
                  "store": {
                    "where": "ambient"
                  }
                }
              },
              "instructions": [
                {
                  "groups": [
                    {
                      "transfer": [
                        {
                          "volume": "10.0:microliter",
                          "to": "plate/1",
                          "from": "plate/0"
                        }
                      ]
                    }
                  ],
                  "op": "pipette"
                },
                {
                  "object": "plate",
                  "type": "ultra-clear",
                  "op": "seal"
                },
                {
                  "object": "plate",
                  "op": "unseal"
                },
                {
                  "lid": "universal",
                  "object": "plate",
                  "op": "cover"
                },
                {
                  "object": "plate",
                  "op": "uncover"
                },
                {
                  "type": "ultra-clear",
                  "object": "plate",
                  "op": "seal"
                }
              ]
            }

    """
    for _, ref in protocol.refs.items():
        if 'store' in ref.opts.keys():
            if not (ref.container.is_covered() or ref.container.is_sealed()):
                default_method = (ref.container.container_type.
                    prioritize_seal_or_cover)
                sealable = 'seal' in ref.container.container_type.capabilities
                coverable = ('cover' in ref.container.container_type.
                    capabilities)
                if default_method == 'seal' and sealable:
                    protocol.seal(ref.container, ref.container.
                        container_type.seal_types[0])
                elif default_method == 'cover' and coverable:
                    protocol.cover(ref.container, ref.container.
                        container_type.cover_types[0])
                elif sealable:
                    protocol.seal(ref.container, ref.container.
                        container_type.seal_types[0])
                elif coverable:
                    protocol.cover(ref.container, ref.container.
                        container_type.cover_types[0])
                else:
                    continue


@classmethod
def from_lists(cls, start, end, edge, strict=False):
    """
		:param list[str] start: list of start nodes
		:param list[str] end: list[str] list of end nodes
		:param list[str] or list[NoneType] edge: list of edges
		:param bool strict:
		:type: .Graph.Graph
		"""
    graph = cls(strict=strict)
    for index, start_name, end_name, edge_name in zip(range(len(start)),
        start, end, edge):
        start_node = graph.add_node(name=start_name, if_node_exists='ignore')
        end_node = graph.add_node(name=end_name, if_node_exists='ignore')
        graph.connect(start=start_node, end=end_node, id=index, label=edge_name
            )
    return graph


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

        :param SfTeamInviteChangeRoleDetails val:
        :rtype: EventDetails
        """
    return cls('sf_team_invite_change_role_details', val)


@classmethod
def join_regex(cls, *regex):
    """Convert a list of wildcards to a regular expression."""
    return '|'.join(regex)


def distance_rectangle_point(rect, point):
    """
    Return the distance (fast) from a rectangle ``(x, y, width,height)``
    to a ``point``.

    >>> distance_rectangle_point(Rectangle(0, 0, 10, 10), (11, -1))
    2
    >>> distance_rectangle_point((0, 0, 10, 10), (11, -1))
    2
    >>> distance_rectangle_point((0, 0, 10, 10), (-1, 11))
    2
    """
    dx = dy = 0
    px, py = point
    rx, ry, rw, rh = tuple(rect)
    if px < rx:
        dx = rx - px
    elif px > rx + rw:
        dx = px - (rx + rw)
    if py < ry:
        dy = ry - py
    elif py > ry + rh:
        dy = py - (ry + rh)
    return abs(dx) + abs(dy)


def pad(data, blocksize=16):
    """
    Pads data to blocksize according to RFC 4303. Pad length field is included in output.
    """
    padlen = blocksize - len(data) % blocksize
    return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,)))


def urljoin(*args):
    """
    Joins given arguments into a url. Trailing but not leading slashes are
    stripped for each argument.
    """
    return '/'.join(map(lambda x: str(x).rstrip('/'), args))


@staticmethod
def is_a_command(command: str) ->bool:
    """Checks if a string is an "A" command.

        Args:
            command: a string. Examples: ""@2", ""D=A".

        Returns:
            A boolean. True, or False
        """
    first_char = command[0]
    if first_char == '@':
        return True
    return False


@staticmethod
def set_attributes(obj, **kwargs):
    """
        #TODO Move to utils?
        With the possibility to add attributes to an object which is not 'self'
        :param obj: object
        :param kwargs: Dictionary
        :return: sets attributes to object
        """
    for key, value in kwargs.items():
        setattr(obj, key, value)


def __call_(text):
    """
        scape the specifed text
        """


def get_any_key(x):
    """ Returns a key from a dictionary.

		# Arguments:

		x: dict. The dictionary to pull a key from.

		# Return value

		If x is empty, returns None; otherwise, this returns a key from the
		dictionary.
	"""
    if x:
        for k in x:
            return k
    else:
        return None


@classmethod
def set(cls, section, key, value):
    """
        Sets a key in the configuration (creating it if it does not exist), and persists
        the change to disk.
        """
    cls.__ensure_config()
    if not cls.__config.has_section(section):
        cls.__config.add_section(section)
    cls.__config.set(section, key, value)
    cls.__config.write(open(cls.path(), 'w'))


def getCurrentFolder():
    """If the context is the default page of a folder or is not itself a
           folder, the parent is returned, otherwise the object itself is
           returned.  This is useful for providing a context for methods
           which wish to act on what is considered the current folder in the
           ui.
        """


@staticmethod
def concat_url(endpoint, url):
    """Concatenate endpoint and final URL.

        E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
        "http://keystone/v2.0/tokens".

        :param endpoint: the base URL
        :param url: the final URL
        """
    return '%s/%s' % (endpoint.rstrip('/'), url.strip('/'))


def is_tuple_or_list(val):
    """
    Checks whether a variable is a list or a tuple
    :param val: The variable to check
    :return: True if the variable is a list or a tuple, otherwise False
    """
    return isinstance(val, (list, tuple))


def class_name(obj):
    """Fetch the class name of an object (class or instance).

    Another cosmetic shortcut.  The builtin way of getting an instance's class
    name is pretty disgusting (and long), accessing two hidden attributes in
    a row just feels wrong.

    :param any obj: The object you want the class name of
    :returns str: The class name

    """
    if isinstance(obj, type):
        return obj.__name__
    else:
        return obj.__class__.__name__


@classmethod
def clearOwner(cls, f0):
    """Return a copy of f0 with no owner specified, or None if f0 is None."""
    if (f0 is None or f0.dataset is None and f0.sizeGeq is None and f0.
        mtime is None and f0.notPaths == [] and f0.regex is None):
        return None
    else:
        return cls(None, f0.dataset, f0.sizeGeq, f0.mtime, f0.notPaths, f0.
            regex)


def add_item(item):
    """Add a persistent or non-persistent item associated with this
        model."""


def get_frame(generator):
    """Given a generator, returns its current frame."""
    if getattr(generator, 'gi_frame', None) is not None:
        return generator.gi_frame
    return None


def Fritzsche(SG, Tavg, L=None, D=None, P1=None, P2=None, Q=None, Ts=288.7,
    Ps=101325.0, Zavg=1, E=1):
    """Calculation function for dealing with flow of a compressible gas in a
    pipeline with the Fritzsche formula. Can calculate any of the following,
    given all other inputs:

    * Flow rate
    * Upstream pressure
    * Downstream pressure
    * Diameter of pipe
    * Length of pipe

    A variety of different constants and expressions have been presented
    for the Fritzsche formula. Here, the form as in [1]_
    is used but with all inputs in base SI units.

    .. math::
        Q = 93.500 \\frac{T_s}{P_s}\\left(\\frac{P_1^2 - P_2^2}
        {L\\cdot {SG}^{0.8587} \\cdot T_{avg}}\\right)^{0.538}D^{2.69}

    Parameters
    ----------
    SG : float
        Specific gravity of fluid with respect to air at the reference
        temperature and pressure `Ts` and `Ps`, [-]
    Tavg : float
        Average temperature of the fluid in the pipeline, [K]
    L : float, optional
        Length of pipe, [m]
    D : float, optional
        Diameter of pipe, [m]
    P1 : float, optional
        Inlet pressure to pipe, [Pa]
    P2 : float, optional
        Outlet pressure from pipe, [Pa]
    Q : float, optional
        Flow rate of gas through pipe, [m^3/s]
    Ts : float, optional
        Reference temperature for the specific gravity of the gas, [K]
    Ps : float, optional
        Reference pressure for the specific gravity of the gas, [Pa]
    Zavg : float, optional
        Average compressibility factor for gas, [-]
    E : float, optional
        Pipeline efficiency, a correction factor between 0 and 1

    Returns
    -------
    Q, P1, P2, D, or L : float
        The missing input which was solved for [base SI]

    Notes
    -----
    This model is also presented in [1]_ with a leading constant of 2.827,
    the same exponents as used here, units of mm  (diameter), kPa, km (length),
    and flow in m^3/hour.

    This model is shown in base SI units in [2]_, and with a leading constant
    of 94.2565, a diameter power of 2.6911, main group power of 0.5382
    and a specific gravity power of 0.858. The difference is very small.

    Examples
    --------
    >>> Fritzsche(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)
    39.421535157535565

    References
    ----------
    .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,
       FL: CRC Press, 2005.
    .. [2] Coelho, Paulo M., and Carlos Pinho. "Considerations about Equations
       for Steady State Flow in Natural Gas Pipelines." Journal of the
       Brazilian Society of Mechanical Sciences and Engineering 29, no. 3
       (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.
    """
    c5 = 93.50009798751128
    c2 = 0.8587
    c3 = 0.538
    c4 = 2.69
    if Q is None and None not in [L, D, P1, P2]:
        return c5 * E * (Ts / Ps) * ((P1 ** 2 - P2 ** 2) / (SG ** c2 * Tavg *
            L * Zavg)) ** c3 * D ** c4
    elif D is None and None not in [L, Q, P1, P2]:
        return (Ps * Q * (SG ** -c2 * (P1 ** 2 - P2 ** 2) / (L * Tavg *
            Zavg)) ** -c3 / (E * Ts * c5)) ** (1.0 / c4)
    elif P1 is None and None not in [L, Q, D, P2]:
        return (L * SG ** c2 * Tavg * Zavg * (D ** -c4 * Ps * Q / (E * Ts *
            c5)) ** (1.0 / c3) + P2 ** 2) ** 0.5
    elif P2 is None and None not in [L, Q, D, P1]:
        return (-L * SG ** c2 * Tavg * Zavg * (D ** -c4 * Ps * Q / (E * Ts *
            c5)) ** (1.0 / c3) + P1 ** 2) ** 0.5
    elif L is None and None not in [P2, Q, D, P1]:
        return SG ** -c2 * (D ** -c4 * Ps * Q / (E * Ts * c5)) ** (-1.0 / c3
            ) * (P1 ** 2 - P2 ** 2) / (Tavg * Zavg)
    else:
        raise Exception(
            'This function solves for either flow, upstream pressure, downstream pressure, diameter, or length; all other inputs must be provided.'
            )


def check_collision(board, shape, offset):
    """
    See if the matrix stored in the shape will intersect anything
    on the board based on the offset. Offset is an (x, y) coordinate.
    """
    off_x, off_y = offset
    for cy, row in enumerate(shape):
        for cx, cell in enumerate(row):
            if cell and board[cy + off_y][cx + off_x]:
                return True
    return False


@staticmethod
def _has_valid_extension(filename: str):
    """Check if a filename has a valid extension."""
    return filename.endswith('.pkl') or filename.endswith('.json')


@staticmethod
def _draw_rectangle(context, width, height):
    """Draw a rectangle

        Assertion: The current point is the center point of the rectangle

        :param context: Cairo context
        :param width: Width of the rectangle
        :param height: Height of the rectangle
        """
    c = context
    c.rel_move_to(-width / 2.0, -height / 2.0)
    c.rel_line_to(width, 0)
    c.rel_line_to(0, height)
    c.rel_line_to(-width, 0)
    c.close_path()


def _convert_squeeze(builder, node, graph, err):
    """
    convert to CoreML Squeeze Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L4903
    """
    axes = node.attrs.get('axes', None)
    builder.add_squeeze(name=node.name, input_name=node.inputs[0],
        output_name=node.outputs[0], axes=axes)


def check_alphabet(sequence):
    """Function that takes as input a sequence and it will check that there is at least a letter matching the alphabet
     in the sequence, returning true."""
    code = 'ATCG'
    for base in sequence:
        if base in code:
            return True
    return False


def resource_provider_url(environ, resource_provider):
    """Produce the URL for a resource provider.

    If SCRIPT_NAME is present, it is the mount point of the placement
    WSGI app.
    """
    prefix = environ.get('SCRIPT_NAME', '')
    return '%s/resource_providers/%s' % (prefix, resource_provider.uuid)


def ipow(a, b, n):
    """calculates (a**b) % n via binary exponentiation, yielding itermediate
       results as Rabin-Miller requires"""
    A = a = a % n
    yield A
    t = 1
    while t <= b:
        t <<= 1
    t >>= 2
    while t:
        A = A * A % n
        if t & b:
            A = A * a % n
        yield A
        t >>= 1


def _map(value, istart, istop, ostart, ostop):
    """
    Helper function that implements the Processing function map(). For more
    details see https://processing.org/reference/map_.html
    http://stackoverflow.com/questions/17134839/how-does-the-map-function-in-processing-work
    """
    return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))


def _float_metric_value(metric):
    """Gets the value of a float-value keras metric."""
    return metric.result().numpy().astype(float)


def texture_paint_toggle():
    """Toggle texture paint mode in 3D view

    """
    pass


def get_image_data(fieldname):
    """Returns the image data"""


def _yield_finished_futures(fs, waiter, ref_collect):
    """
    Iterate on the list *fs*, yielding finished futures one by one in
    reverse order.
    Before yielding a future, *waiter* is removed from its waiters
    and the future is removed from each set in the collection of sets
    *ref_collect*.

    The aim of this function is to avoid keeping stale references after
    the future is yielded and before the iterator resumes.
    """
    while fs:
        f = fs[-1]
        for futures_set in ref_collect:
            futures_set.remove(f)
        with f._condition:
            f._waiters.remove(waiter)
        del f
        yield fs.pop()


def stripped(jid):
    """ strip trailing part of a JID, the part after the / """
    try:
        return str(jid).split('/')[0]
    except:
        return str(jid)


def code_to_chars(code):
    """Convert each numeric code to its corresponding characters"""
    return '\x1b[' + str(code) + 'm'


def reload():
    """Update objects paths list with new data from the archive

    """
    pass


def any_generated(gen):
    """like `any` but returns False for empty generators
    >>> any_generated((v for v in (0,object())))
    True
    >>> any_generated((v for v in (0,False)))
    False
    >>> any_generated((v for v in ()))
    False
    """
    for v in gen:
        if bool(v):
            return True
    return False


def is_owner(obj, user):
    """ Check if user is owner of the slice """
    return obj and user in obj.owners


def consecutive(lst):
    """Return True if items in lst are consecutive numbers."""
    for i in range(1, len(lst)):
        if lst[i] - lst[i - 1] != 1:
            return False
    return True


def printList(l):
    """Print the contents of the list comma-separated"""
    if len(l) == 0:
        return ''
    elif len(l) == 1:
        return l[0]
    elif len(l) == 2:
        return ' and '.join(l)
    else:
        ret = ', '.join(l[:-1])
        ret += ', and '
        ret += l[-1]
        return ret


def disable():
    """Disable tracing of all DB queries. Reduce a lot size of profiles."""
    global _DISABLED
    _DISABLED = True


@classmethod
def deserialize(cls, entity, value):
    """Deserialize a value for this attribute from storage.

        This will be called by the blob when deserializing itself, override it
        to perform any necessary conversion or sanitation.

        :param entity: The entity this attribute is on
        :param value: The value to deserialize
        :returns: The deserialized value

        """
    return value


def close_version():
    """Close the public version.
        """


def on_disconnect():
    """ Called when the client connection lost."""
    print('connect lost')


@classmethod
def _getPipeline(cls, mode='master', transaction=False):
    """
        Create a pipeline object
        @TODO: support master/slave
        """
    conn = cls._getConnection(mode=mode)
    return conn.pipeline(transaction=transaction)


def convertBToMb(bytes):
    """converts Bytes to Megabytes"""
    bytes = float(bytes)
    megabytes = bytes / 1048576
    return megabytes


def remove_dir(target, toolkit=None):
    """
    clean dir: adb shell rm -rf <target>

    :param target: 目标路径
    :param toolkit:
    :return:
    """
    return toolkit.adb.run(['shell', 'rm', '-rf', target])


@classmethod
def add_font_data(cls, data):
    """Add font data to the font loader.

        This is a class method and affects all fonts loaded.  Data must be
        some byte string of data, for example, the contents of a TrueType font
        file.  Subclasses can override this method to add the font data into
        the font registry.

        There is no way to instantiate a font given the data directly, you
        must use :py:func:`pyglet.font.load` specifying the font name.
        """
    pass


def decrypt(stream, parameters):
    """
        Method to decrypt streams using a PDF security handler (NOT IMPLEMENTED YET)

        @param stream: A PDF stream
        @return: A tuple (status,statusContent), where statusContent is the decrypted PDF stream in case status = 0 or an error in case status = -1
    """
    if parameters is None or parameters == {}:
        return 0, stream
    elif '/Name' not in parameters or parameters['/Name'] is None:
        return 0, stream
    else:
        cryptFilterName = parameters['/Name'].getValue()
        if cryptFilterName == 'Identity':
            return 0, stream
        else:
            return -1, 'Decrypt not supported yet'


def write_double(encoder, datum, schema=None):
    """A double is written as 8 bytes.  The double is converted into a 64-bit
    integer using a method equivalent to Java's doubleToLongBits and then
    encoded in little-endian format.  """
    encoder.write_double(datum)


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

    """
    pass


def sanitize_field(value):
    """Clean field used in the payment request form

    :param string value:
    :return: A sanitized value

    Adyen suggest to remove all new-line, so we do.
    """
    if value is None:
        return value
    return str(value).replace('\n', ' ').replace('\r', ' ').strip()


def decode(response, request):
    """
        Create a credentials object from the given response.

        @type response: L{str}
        @param response: scheme specific response string

        @type request: L{twisted.web.http.Request}
        @param request: The request being processed (from which the response
            was taken).

        @raise twisted.cred.error.LoginFailed: If the response is invalid.

        @rtype: L{twisted.cred.credentials.ICredentials} provider
        @return: The credentials represented by the given response.
        """


def add_brackets_around_string(word: str):
    """Adds square brackets for single character strings and round the rest.
    """
    if len(word) == 1 or len(word) == 2 and word.startswith('\\'):
        return word
    return '(?:' + word + ')'


@classmethod
def init_bare(cls, objects, refs):
    """Create a new bare repository in memory.

        :param objects: Objects for the new repository,
            as iterable
        :param refs: Refs as dictionary, mapping names
            to object SHA1s
        """
    ret = cls()
    for obj in objects:
        ret.object_store.add_object(obj)
    for refname, sha in refs.items():
        ret.refs[refname] = sha
    ret._init_files(bare=True)
    return ret


@staticmethod
def _labels_by_step_newest(expanded_results):
    """
        Makes one channel per step, based on most recent channel entered.

        See also
        --------
            _expand_results
            _labels_by_step_oldest
            _labels_by_step_multiple
            labels_by_step

        Parameters
        ----------
        expanded_results : list of 3-tuples (int, int, frozenset)
            input events; the output of _expand_results (see details there)

        Returns
        -------
        list of 3-tuples (int, int, frozenset)
            events with ranges such that there is only one channel at any
            given step number, and that channel is the most recent entered
        """
    relabeled = []
    previous = expanded_results[0]
    for current in expanded_results[1:]:
        relabeled += [(previous[0], current[0], previous[2])]
        previous = current
    relabeled += [expanded_results[-1]]
    return relabeled


def int_to_roman(num: int) ->str:
    """
    @param1: num to be converted to roman
    @return: string roman value
    """
    numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V',
        'IV', 'I']
    result = ''
    for n, r in zip(numbers, romans):
        result += num // n * r
        num %= n
    return result


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


def items(sobject):
    """
    Extract the I{items} from a suds object.

    Much like the items() method works on I{dict}.

    @param sobject: A suds object
    @type sobject: L{Object}
    @return: A list of items contained in I{sobject}.
    @rtype: [(key, value),...]

    """
    for item in sobject:
        yield item


def batch_get_deployment_groups(applicationName=None, deploymentGroupNames=None
    ):
    """
    Gets information about one or more deployment groups.
    See also: AWS API Documentation

    :example: response = client.batch_get_deployment_groups(
        applicationName='string',
        deploymentGroupNames=[
            'string',
        ]
    )

    :type applicationName: string
    :param applicationName: [REQUIRED]
            The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.

    :type deploymentGroupNames: list
    :param deploymentGroupNames: [REQUIRED]
            The deployment groups' names.
            (string) --

    :rtype: dict
    :return: {
        'deploymentGroupsInfo': [
            {
                'applicationName': 'string',
                'deploymentGroupId': 'string',
                'deploymentGroupName': 'string',
                'deploymentConfigName': 'string',
                'ec2TagFilters': [
                    {
                        'Key': 'string',
                        'Value': 'string',
                        'Type': 'KEY_ONLY'|'VALUE_ONLY'|'KEY_AND_VALUE'
                    },
                ],
                'onPremisesInstanceTagFilters': [
                    {
                        'Key': 'string',
                        'Value': 'string',
                        'Type': 'KEY_ONLY'|'VALUE_ONLY'|'KEY_AND_VALUE'
                    },
                ],
                'autoScalingGroups': [
                    {
                        'name': 'string',
                        'hook': 'string'
                    },
                ],
                'serviceRoleArn': 'string',
                'targetRevision': {
                    'revisionType': 'S3'|'GitHub',
                    's3Location': {
                        'bucket': 'string',
                        'key': 'string',
                        'bundleType': 'tar'|'tgz'|'zip',
                        'version': 'string',
                        'eTag': 'string'
                    },
                    'gitHubLocation': {
                        'repository': 'string',
                        'commitId': 'string'
                    }
                },
                'triggerConfigurations': [
                    {
                        'triggerName': 'string',
                        'triggerTargetArn': 'string',
                        'triggerEvents': [
                            'DeploymentStart'|'DeploymentSuccess'|'DeploymentFailure'|'DeploymentStop'|'DeploymentRollback'|'DeploymentReady'|'InstanceStart'|'InstanceSuccess'|'InstanceFailure'|'InstanceReady',
                        ]
                    },
                ],
                'alarmConfiguration': {
                    'enabled': True|False,
                    'ignorePollAlarmFailure': True|False,
                    'alarms': [
                        {
                            'name': 'string'
                        },
                    ]
                },
                'autoRollbackConfiguration': {
                    'enabled': True|False,
                    'events': [
                        'DEPLOYMENT_FAILURE'|'DEPLOYMENT_STOP_ON_ALARM'|'DEPLOYMENT_STOP_ON_REQUEST',
                    ]
                },
                'deploymentStyle': {
                    'deploymentType': 'IN_PLACE'|'BLUE_GREEN',
                    'deploymentOption': 'WITH_TRAFFIC_CONTROL'|'WITHOUT_TRAFFIC_CONTROL'
                },
                'blueGreenDeploymentConfiguration': {
                    'terminateBlueInstancesOnDeploymentSuccess': {
                        'action': 'TERMINATE'|'KEEP_ALIVE',
                        'terminationWaitTimeInMinutes': 123
                    },
                    'deploymentReadyOption': {
                        'actionOnTimeout': 'CONTINUE_DEPLOYMENT'|'STOP_DEPLOYMENT',
                        'waitTimeInMinutes': 123
                    },
                    'greenFleetProvisioningOption': {
                        'action': 'DISCOVER_EXISTING'|'COPY_AUTO_SCALING_GROUP'
                    }
                },
                'loadBalancerInfo': {
                    'elbInfoList': [
                        {
                            'name': 'string'
                        },
                    ]
                },
                'lastSuccessfulDeployment': {
                    'deploymentId': 'string',
                    'status': 'Created'|'Queued'|'InProgress'|'Succeeded'|'Failed'|'Stopped'|'Ready',
                    'endTime': datetime(2015, 1, 1),
                    'createTime': datetime(2015, 1, 1)
                },
                'lastAttemptedDeployment': {
                    'deploymentId': 'string',
                    'status': 'Created'|'Queued'|'InProgress'|'Succeeded'|'Failed'|'Stopped'|'Ready',
                    'endTime': datetime(2015, 1, 1),
                    'createTime': datetime(2015, 1, 1)
                }
            },
        ],
        'errorMessage': 'string'
    }

    :returns:
    KEY_ONLY: Key only.
    VALUE_ONLY: Value only.
    KEY_AND_VALUE: Key and value.

    """
    pass


def beautiful_unit_string(unit):
    """Convert unit fractions to latex.

    Parameters
    ----------
    unit : str
        Value of unit for input, e.g. :code:`m^3/kg`.

    Returns
    -------
    unit : str
        Value of unit for output, e.g. :code:`$\\frac{m^3}{kg}$`.
    """
    if '/' in unit:
        numerator = unit.split('/')[0]
        denominator = unit.split('/')[1]
        unit = '$\\frac{' + numerator + '}{' + denominator + '}$'
    return unit


def funct_array_simple2(a):
    """
    used for testing
    take an array and compute 3*sqr(a+1)
    plus a random nap to simulate a random processing time
    """
    import time
    import random
    import numpy
    time.sleep(random.random())
    return 3.0 * numpy.sqrt(a)


def _neighbor_iterator(dist, radius_matrix, buffer_matrix, n, connection_matrix
    ):
    """An iterator function to work out neighbor shells.

    Parameters
    ----------
    dist : array
        Distance matrix for the atoms object.
    radius_matrix : array
        An NxN matrix of summed radii between each pair of atoms.
    buffer_matrix : array
        An NxN matrix of buffer values between each pair of atoms.
    n : int
        The current neighbor shell.
    connection_matrix : array
        The current connection matrix being built.

    Returns
    -------
    dist : array
        Modified distance matrix for the atoms object. Modified to avoid
        recounting neighbors.
    connection_matrix : array
        Modified current connection matrix. Contains results for current shell.
    unconnected : int
        The number of atom pairs that dont have a neighbor shell assigned.
    """
    res = dist - (radius_matrix + buffer_matrix) * (n + 1)
    res[res > 0.0] = 0.0
    res[res < 0.0] = n + 1.0
    dist += res * 10000.0
    connection_matrix += res
    unconnected = len(connection_matrix[connection_matrix == 0.0])
    return dist, connection_matrix, unconnected


def tle_fmt_float(num, width=10):
    """ Return a left-aligned signed float string, with no leading zero left of the decimal """
    digits = width - 2
    ret = '{:<.{DIGITS}f}'.format(num, DIGITS=digits)
    if ret.startswith('0.'):
        return ' ' + ret[1:]
    if ret.startswith('-0.'):
        return '-' + ret[2:]


def get_messages(request):
    """
    Returns the message storage on the request if it exists, otherwise returns
    an empty list.
    """
    if hasattr(request, '_messages'):
        return request._messages
    else:
        return []


def publish(requestor, service, nodeIdentifier, items):
    """
        Called when a publish request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to publish to.
        @type nodeIdentifier: C{unicode}
        @param items: The items to be published as elements.
        @type items: C{list} of C{Element<twisted.words.xish.domish.Element>}
        @return: deferred that fires on success.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


def undeflate(data):
    """Decompresses data for Content-Encoding: deflate.
    (the zlib compression is used.)
    """
    import zlib
    decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)
    return decompressobj.decompress(data) + decompressobj.flush()


@classmethod
def acceptedSymbol(cls, option, verbose=False):
    """Checks if option ticker symbol (root) corresponds to an accepted
        symbol."""
    if option.root.iloc[0] in cls.SYMBOLS:
        return True
    else:
        if verbose:
            print('Option root symbol not accepted')
        return False