def get_stats():
    """
        returns a dictionary, with str keys representing the names of stats
        to be monitored, and numeric values.
        """


def line_search_return(line):
    """get the source/facet in the return statement
        TODO: return multiple return values not just one
    """
    l = line.split()
    if 'return' in l:
        i = l.index('return')
        if len(l) > i + 2:
            return l[i + 1]
    else:
        return None


def vcs_versioning(version_info):
    """ Use the information from the vcs, and format it nicely.

        >>> vcs_versioning({'vcs_info': {'dirt': ' M flowtool_versioning/dropins/version.py\\n', 'prefix_tag_distances': {'flowtool-versioning-0.7.33': 53, 'flowtool-versioning-0.7.32': 134, 'flowtool-versioning-0.7.34': 37}, 'tag_version': {'normalized': '0.7.34', 'version': '0.7.34', 'release': (0, 7, 34)}, 'latest_tag': 'flowtool-versioning-0.7.34', 'latest_tag_version': '0.7.34', 'latest_tag_commit': 'b25974fb03e02f491ace23d2718a847a6d01853d', 'commit': 'a06e7d03436457883e2bce2ebe7968886943e2bb', 'prefix': 'flowtool-versioning-'}, 'version': '0.7.34+37.git:b25974fb.dirty'})
        '0.7.34+37.git:b25974fb.dirty'
    """
    vcs_info = version_info['vcs_info']
    if not 'latest_tag' in vcs_info:
        return
    tag = vcs_info['latest_tag']
    distance = vcs_info['prefix_tag_distances'][tag]
    vcs_version = vcs_info['latest_tag_version']
    if distance:
        commit = vcs_info['latest_tag_commit'][:8]
        vcs_version += '+%s.git:%s' % (distance, commit)
    if vcs_info['dirt']:
        vcs_version += '.dirty'
    return vcs_version


def is_weekday(d_or_dt):
    """Check if a datetime is weekday.
    """
    return d_or_dt.isoweekday() not in [6, 7]


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

        :param SfInviteGroupDetails val:
        :rtype: EventDetails
        """
    return cls('sf_invite_group_details', val)


def p_with_head(p):
    """with_head : WITH ID AS ID"""
    p[0] = ['WITH', p[2], p[4]]


def int_to_string(x):
    """Convert integer x into a string of bytes, as per X9.62."""
    assert x >= 0
    if x == 0:
        return bytearray([0])
    result = bytearray()
    while x > 0:
        q, r = divmod(x, 256)
        result = bytearray([r]) + result
        x = q
    return result


def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

        This function is called in a class definition.

        The arguments are one or more interfaces or interface
        specifications (IDeclaration objects).

        The given interfaces (including the interfaces in the
        specifications) are used to create the class's direct-object
        interface specification.  An error will be raised if the module
        class has an direct interface specification.  In other words, it is
        an error to call this function more than once in a class
        definition.

        Note that the given interfaces have nothing to do with the
        interfaces implemented by instances of the class.

        This function is provided for convenience. It provides a more
        convenient way to call directlyProvides for a class. For example::

          classProvides(I1)

        is equivalent to calling::

          directlyProvides(theclass, I1)

        after the class has been created.
        """


@classmethod
def clean_resources(cls, resources, request=None, **kwargs):
    """ Clean resources before models management.

        If models management requires resources, such as database calls or
        external services communication, one may possible to clean resources
        before it.
        It is also possible to validate user permissions to do operation. Use
        form validation if validation does not require user access and Resource
        validation (this method) if it requires to access user object.

        Parameters
        ----------
        resources : list
            List of dictionaries - serialized objects.

        Returns
        -------
        resources : list
            List of cleaned resources

        Raises
        ------
        django.forms.ValidationError in case of validation errors

        """
    return resources


def empty():
    """
    An empty generator.
    """
    if False:
        yield None


def filter_paragraphs_without_ref_tags(segment):
    """Check to see if we have at least 10 words and no refs"""
    words = 0
    refs = 0
    for t in segment.tokens():
        words += t.type == 'word'
        refs += t.type in ('ref_open', 'ref_close', 'ref_singleton')
    return words > 10 and refs == 0


def group_make():
    """Make group from selected nodes

    """
    pass


def log_whodid(obj, user):
    """
    Stores the given user as creator or editor of the given object
    """
    if hasattr(obj, 'created_by') and obj.created_by is None:
        obj.created_by = user
    if hasattr(obj, 'lastmodified_by'):
        obj.lastmodified_by = user


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 all_(role):
    """
    A matcher that always returns ``True``.

    :rtype: bool
    """
    return True


def set_token(token):
    """Set the token key to access the database.

    Args:
        token (str): The token.
    """
    global _query_token
    _query_token = token


def outcome_machine_learner(xdata, ydata, all_a, none_a, ml_model,
    continuous, print_results=True):
    """Function to fit machine learning predictions. Used by TMLE to generate predicted probabilities of outcome
    (i.e. Pr(Y=1 | A=1, L) and Pr(Y=1 | A=0, L)). Future update will include continuous Y functionality (i.e. E(Y))
    """
    try:
        fm = ml_model.fit(X=xdata, y=ydata)
    except TypeError:
        raise TypeError(
            "Currently custom_model must have the 'fit' function with arguments 'X', 'y'. This covers both sklearn and supylearner. If there is a predictive model you would like to use, please open an issue at https://github.com/pzivich/zepid and I can work on adding support"
            )
    if print_results and hasattr(fm, 'summarize'):
        fm.summarize()
    if continuous:
        if hasattr(fm, 'predict'):
            qa1 = fm.predict(all_a)
            qa0 = fm.predict(none_a)
            return qa1, qa0
        else:
            raise ValueError(
                "Currently custom_model must have 'predict' or 'predict_proba' attribute"
                )
    elif hasattr(fm, 'predict_proba'):
        qa1 = fm.predict_proba(all_a)
        qa0 = fm.predict_proba(none_a)
        if qa1.ndim == 1 and qa0.ndim == 1:
            return qa1, qa0
        else:
            return qa1[:, (1)], qa0[:, (1)]
    elif hasattr(fm, 'predict'):
        qa1 = fm.predict(all_a)
        qa0 = fm.predict(none_a)
        return qa1, qa0
    else:
        raise ValueError(
            "Currently custom_model must have 'predict' or 'predict_proba' attribute"
            )


def white_characters(language_id: str) ->str:
    """
    Characters that count as white space if they are the only characters in a
    line.
    """
    assert language_id is not None
    assert language_id.islower()
    return '(),:;[]{}'


def Fourier_mass(t, L, D):
    """Calculates mass transfer Fourier number or `Fo` for a specified time
    `t`, characteristic length `L`, and diffusion coefficient `D`.

    .. math::
        Fo = \\frac{D t}{L^2}

    Parameters
    ----------
    t : float
        time [s]
    L : float
        Characteristic length [m]
    D : float
        Diffusivity of a species, [m^2/s]

    Returns
    -------
    Fo : float
        Fourier number (mass) []

    Notes
    -----
    .. math::
        Fo = \\frac{\\text{Diffusive transport rate}}{\\text{Storage rate}}

    Examples
    --------
    >>> Fourier_mass(t=1.5, L=2, D=1E-9)
    3.7500000000000005e-10

    References
    ----------
    .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
       Eighth Edition. McGraw-Hill Professional, 2007.
    """
    return t * D / L ** 2


def slow_parent_set():
    """Set the object’s slow parent

    """
    pass


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


def perceel_adapter(obj, request=None):
    """
    Adapter for rendering
    :class:`oe_geoutils.data.models.Perceel` to json.

    Add the adapter to `jsonpublish`
    from jsonpublish import register_adapter
    register_adapter(Perceel, perceel_adapter)

    Add the adapter to your :class:`pyramid.renderers.JSON` json_renderer
    from pyramid.renderers import JSON
    json_renderer = JSON()
    json_renderer.add_adapter(Perceel, perceel_adapter)
    """
    perceel = {'id': obj.id, 'type': obj.type, 'provincie': {'niscode': obj
        .provincie_niscode, 'naam': obj.provincie_naam}, 'gemeente': {
        'niscode': obj.gemeente_niscode, 'naam': obj.gemeente_naam, 'id':
        obj.gemeente_crab_id}, 'deelgemeente': {'niscode': obj.
        deelgemeente_niscode, 'naam': obj.deelgemeente_naam}}
    if obj.capakey and len(obj.capakey) > 0:
        perceel.update({'perceel': {'afdeling': obj.afdeling, 'sectie': obj
            .sectie, 'perceel': obj.perceel, 'capakey': obj.capakey}})
    return perceel


def smart_setter(obj):
    """Returns a smart setter for `obj`.

    If `obj` is a mutable mapping, it returns the ``.__setitem__()`` method
    bound to the object `obj`, otherwise it returns a partial of ``setattr``
    on `obj`.

    .. versionadded:: 1.8.2

    """
    from xotl.tools.future.functools import partial
    from xotl.tools.future.collections import MutableMapping
    if isinstance(obj, MutableMapping):
        return obj.__setitem__
    else:
        return partial(setattr, obj)


def vertex_color_add():
    """Add vertex color layer

    """
    pass


def psi_Na_Cl_PO4_HFM89(T, P):
    """c-a-a': sodium chloride phosphate [HFM89]."""
    psi = 0.11
    valid = T == 298.15
    return psi, valid


def set_load_balancer_policies_for_backend_server(LoadBalancerName=None,
    InstancePort=None, PolicyNames=None):
    """
    Replaces the set of policies associated with the specified port on which the EC2 instance is listening with a new set of policies. At this time, only the back-end server authentication policy type can be applied to the instance ports; this policy type is composed of multiple public key policies.
    Each time you use SetLoadBalancerPoliciesForBackendServer to enable the policies, use the PolicyNames parameter to list the policies that you want to enable.
    You can use  DescribeLoadBalancers or  DescribeLoadBalancerPolicies to verify that the policy is associated with the EC2 instance.
    For more information about enabling back-end instance authentication, see Configure Back-end Instance Authentication in the Classic Load Balancer Guide . For more information about Proxy Protocol, see Configure Proxy Protocol Support in the Classic Load Balancer Guide .
    See also: AWS API Documentation

    Examples
    This example replaces the policies that are currently associated with the specified port.
    Expected Output:

    :example: response = client.set_load_balancer_policies_for_backend_server(
        LoadBalancerName='string',
        InstancePort=123,
        PolicyNames=[
            'string',
        ]
    )

    :type LoadBalancerName: string
    :param LoadBalancerName: [REQUIRED]
            The name of the load balancer.

    :type InstancePort: integer
    :param InstancePort: [REQUIRED]
            The port number associated with the EC2 instance.

    :type PolicyNames: list
    :param PolicyNames: [REQUIRED]
            The names of the policies. If the list is empty, then all current polices are removed from the EC2 instance.
            (string) --

    :rtype: dict
    :return: {}

    """
    pass


def isAlphanum(c):
    """return true if the character is a letter, digit, underscore,
           dollar sign, or non-ASCII character.
    """
    return (c >= 'a' and c <= 'z' or c >= '0' and c <= '9' or c >= 'A' and
        c <= 'Z' or c == '_' or c == '$' or c == '\\' or c is not None and
        ord(c) > 126)


@classmethod
def command_class(cls, command: str):
    """
        Get command class with command name

        :param command: command name
        :return: command class
        """
    return cls.__command_classes.get(command)


def model_params(model_name):
    """ Map Generator and Discriminator model name to parameter coefficients.

    Args:
      model_name (string): The name of the model corresponding to the dataset.

    Returns:
      A binary tuple value.
    """
    params_dict = {'g-mnist': (1, 28), 'g-fmnist': (1, 28), 'd-mnist': (1,
        28), 'd-fmnist': (1, 28)}
    return params_dict[model_name]


@classmethod
def to_yaml(cls, representer, node):
    """Create a YAML representation of a DAGReference, carrying only the
        _data attribute over...

        As YAML expects scalar data to be str-like, a type cast is done. The
        subclasses that rely on certain argument types should take care that
        they can parse arguments that are str-like.
        """
    return representer.represent_scalar(cls.yaml_tag, str(node._data))


def sanitize_ctx(request, ctx):
    """Keep just the known context fields."""
    nb_path = ctx.pop('nb_path', None)
    if ctx:
        request.log.debug('Ignoring context fields: %s', ', '.join(ctx.keys()))
    return {'nb_path': nb_path}


def get_var_from_task_decorator(Cls, upstream_task_id='',
    upstream_return_key='', u_task=None):
    """wrapper for functions that require an fixed input, which is here provided
    by a previous task"""
    upstream_return = {upstream_return_key: 'test'}
    return_value = upstream_return[upstream_return_key]
    Cls.srmfile = return_value
    return Cls


def delete_syslog(module, array):
    """Delete Syslog Server"""
    changed = False
    noport_address = module.params['protocol'] + '://' + module.params[
        'address']
    if module.params['port']:
        full_address = noport_address + ':' + module.params['port']
    else:
        full_address = noport_address
    address_list = array.get(syslogserver=True)['syslogserver']
    if address_list:
        for address in range(0, len(address_list)):
            if address_list[address] == full_address:
                del address_list[address]
                try:
                    array.set(syslogserver=address_list)
                    changed = True
                    break
                except Exception:
                    module.fail_json(msg=
                        'Failed to remove syslog server: {0}'.format(
                        full_address))
    module.exit_json(changed=changed)


def key_exists(search_key, inputed_dict):
    """
    Given a search key which is dot notated
    return wether or not that key exists in a dictionary
    """
    num_levels = search_key.split('.')
    if len(num_levels) == 0:
        return False
    current_pointer = inputed_dict
    for updated_key in num_levels:
        if current_pointer is None:
            return False
        if updated_key == num_levels[-1]:
            return updated_key in current_pointer
        if updated_key in current_pointer:
            current_pointer = current_pointer[updated_key]
        else:
            return False


def remaining_bytes(char):
    """
    Calculate the remaining bytes of a UTF-8 sequence
    if given the first character.

    UTF-8 ONLY!
    """
    num = ord(char)
    remaining = -1
    while num > 127:
        remaining += 1
        num = (num << 1) % 256
    if remaining == 0 or remaining > 3:
        raise RuntimeError('Not valid UTF-8 leading byte: {}'.format(bin(
            ord(char))))
    assert remaining in (-1, 1, 2, 3)
    return remaining


def getObject(uid):
    """
        Return an object by its unique id

        :raises zope.intid.interfaces.ObjectMissingError: if
          there is no object with that id.
        """


def opened_closed(logevent):
    """
    Inspect a log line and groups it by connection being openend or closed.

    If neither, return False.
    """
    if 'connection accepted' in logevent.line_str:
        return 'opened'
    elif 'end connection' in logevent.line_str:
        return 'closed'
    else:
        return False


def _iter_and_close(file_obj, block_size, charset):
    """Yield file contents by block then close the file."""
    while True:
        try:
            block = file_obj.read(block_size)
            if block:
                if isinstance(block, bytes):
                    yield block
                else:
                    yield block.encode(charset)
            else:
                raise StopIteration
        except StopIteration:
            file_obj.close()
            break


def update_method(restApiId=None, resourceId=None, httpMethod=None,
    patchOperations=None):
    """
    Updates an existing  Method resource.
    See also: AWS API Documentation

    :example: response = client.update_method(
        restApiId='string',
        resourceId='string',
        httpMethod='string',
        patchOperations=[
            {
                'op': 'add'|'remove'|'replace'|'move'|'copy'|'test',
                'path': 'string',
                'value': 'string',
                'from': 'string'
            },
        ]
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The RestApi identifier for the Method resource.

    :type resourceId: string
    :param resourceId: [REQUIRED]
            The Resource identifier for the Method resource.

    :type httpMethod: string
    :param httpMethod: [REQUIRED]
            The HTTP verb of the Method resource.

    :type patchOperations: list
    :param patchOperations: A list of update operations to be applied to the specified resource and in the order specified in this list.
            (dict) -- A single patch operation to apply to the specified resource. Please refer to http://tools.ietf.org/html/rfc6902#section-4 for an explanation of how each operation is used.
            op (string) --An update operation to be performed with this PATCH request. The valid value can be 'add', 'remove', or 'replace'. Not all valid operations are supported for a given resource. Support of the operations depends on specific operational contexts. Attempts to apply an unsupported operation on a resource will return an error message.
            path (string) --The op operation's target, as identified by a JSON Pointer value that references a location within the targeted resource. For example, if the target resource has an updateable property of {'name':'value'} , the path for this property is /name . If the name property value is a JSON object (e.g., {'name': {'child/name': 'child-value'}} ), the path for the child/name property will be /name/child~1name . Any slash ('/') character appearing in path names must be escaped with '~1', as shown in the example above. Each op operation can have only one path associated with it.
            value (string) --The new target value of the update operation. When using AWS CLI to update a property of a JSON value, enclose the JSON object with a pair of single quotes in a Linux shell, e.g., '{'a': ...}'. In a Windows shell, see Using JSON for Parameters .
            from (string) --Not supported.

    :rtype: dict
    :return: {
        'httpMethod': 'string',
        'authorizationType': 'string',
        'authorizerId': 'string',
        'apiKeyRequired': True|False,
        'requestValidatorId': 'string',
        'operationName': 'string',
        'requestParameters': {
            'string': True|False
        },
        'requestModels': {
            'string': 'string'
        },
        'methodResponses': {
            'string': {
                'statusCode': 'string',
                'responseParameters': {
                    'string': True|False
                },
                'responseModels': {
                    'string': 'string'
                }
            }
        },
        'methodIntegration': {
            'type': 'HTTP'|'AWS'|'MOCK'|'HTTP_PROXY'|'AWS_PROXY',
            'httpMethod': 'string',
            'uri': 'string',
            'credentials': 'string',
            'requestParameters': {
                'string': 'string'
            },
            'requestTemplates': {
                'string': 'string'
            },
            'passthroughBehavior': 'string',
            'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT',
            'cacheNamespace': 'string',
            'cacheKeyParameters': [
                'string',
            ],
            'integrationResponses': {
                'string': {
                    'statusCode': 'string',
                    'selectionPattern': 'string',
                    'responseParameters': {
                        'string': 'string'
                    },
                    'responseTemplates': {
                        'string': 'string'
                    },
                    'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT'
                }
            }
        }
    }

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

    """
    pass


def try_import_tfdl():
    """Try to import tensorflow dlpack at runtime.

    Returns
    -------
    tensorflow dlpack module if found. Raise ImportError otherwise
    """
    try:
        return __import__('tensorflow.experimental.dlpack', fromlist=[''])
    except ImportError as e:
        raise ImportError('tensorflow >= 2.2.0 is required.')


def t_heredoc_END_HEREDOC(t):
    """(?<=\\n)[A-Za-z_][\\w_]*"""
    if t.value == t.lexer.heredoc_label:
        del t.lexer.heredoc_label
        t.lexer.pop_state()
    else:
        t.type = 'ENCAPSED_AND_WHITESPACE'
    return t


def listAttributes():
    """Return the attributes of this object as tuples (name, value).

        The order of the attributes returned is irrelevant.

        May return None to indicate that this kind of object cannot
        store attributes.
        """


def is_hard_clipped(read):
    """Function that checks the CIGAR string of the sam file and returns true if the read is hard-clipped"""
    match = 0
    for cigar in read.cigar:
        if cigar[0] == 5:
            match += 1
        else:
            pass
    if match > 0:
        return True
    else:
        return False


def sample_pts(pts, perc):
    """
  Non-random deterministic shitty sampler
  """
    i = 0
    foo = []
    while i <= 1.0 and int(i * (len(pts) - 1)) < len(pts):
        foo.append(pts[int(i * (len(pts) - 1))])
        i += perc
    return foo


def _vmomentsurfaceIntegrand(vz, vR, vT, R, z, df, sigmaR1, gamma, sigmaz1,
    n, m, o):
    """Internal function that is the integrand for the vmomentsurface mass integration"""
    return vR ** n * vT ** m * vz ** o * df(R, vR * sigmaR1, vT * sigmaR1 *
        gamma, z, vz * sigmaz1, use_physical=False)


def moveObjectsUp(ids, delta=1, subset_ids=None):
    """ Move specified sub-objects up by delta in container. """


def _get_index(i, lengths):
    """
    From an index, return the chromosome number and the loci number

    Parameters
    ----------
    i : integer
        index in the full matrix

    lengths : ndarray (n, )

    Returns
    -------
    tuple : (c, l)
        chromosome number, locus
    """
    length_cum = lengths.cumsum()
    c = (length_cum > i).argmax() + 1
    if c > 1:
        length = i - length_cum[c - 2]
    else:
        length = i
    if len(lengths) > 1 and length > lengths[c - 1]:
        raise ValueError("there's a problem")
    if c > len(lengths):
        raise ValueError("There's a problem")
    return c, length


def _set_ndarray_class(cls):
    """Set the symbolic class to be cls"""
    global _ndarray_cls
    _ndarray_cls = cls


def schedule_run(projectArn=None, appArn=None, devicePoolArn=None, name=
    None, test=None, configuration=None, executionConfiguration=None):
    """
    Schedules a run.
    See also: AWS API Documentation

    Examples
    The following example schedules a test run named MyRun.
    Expected Output:

    :example: response = client.schedule_run(
        projectArn='string',
        appArn='string',
        devicePoolArn='string',
        name='string',
        test={
            'type': 'BUILTIN_FUZZ'|'BUILTIN_EXPLORER'|'APPIUM_JAVA_JUNIT'|'APPIUM_JAVA_TESTNG'|'APPIUM_PYTHON'|'APPIUM_WEB_JAVA_JUNIT'|'APPIUM_WEB_JAVA_TESTNG'|'APPIUM_WEB_PYTHON'|'CALABASH'|'INSTRUMENTATION'|'UIAUTOMATION'|'UIAUTOMATOR'|'XCTEST'|'XCTEST_UI',
            'testPackageArn': 'string',
            'filter': 'string',
            'parameters': {
                'string': 'string'
            }
        },
        configuration={
            'extraDataPackageArn': 'string',
            'networkProfileArn': 'string',
            'locale': 'string',
            'location': {
                'latitude': 123.0,
                'longitude': 123.0
            },
            'radios': {
                'wifi': True|False,
                'bluetooth': True|False,
                'nfc': True|False,
                'gps': True|False
            },
            'auxiliaryApps': [
                'string',
            ],
            'billingMethod': 'METERED'|'UNMETERED'
        },
        executionConfiguration={
            'jobTimeoutMinutes': 123,
            'accountsCleanup': True|False,
            'appPackagesCleanup': True|False
        }
    )

    :type projectArn: string
    :param projectArn: [REQUIRED]
            The ARN of the project for the run to be scheduled.

    :type appArn: string
    :param appArn: The ARN of the app to schedule a run.

    :type devicePoolArn: string
    :param devicePoolArn: [REQUIRED]
            The ARN of the device pool for the run to be scheduled.

    :type name: string
    :param name: The name for the run to be scheduled.

    :type test: dict
    :param test: [REQUIRED]
            Information about the test for the run to be scheduled.
            type (string) -- [REQUIRED]The test's type.
            Must be one of the following values:
            BUILTIN_FUZZ: The built-in fuzz type.
            BUILTIN_EXPLORER: For Android, an app explorer that will traverse an Android app, interacting with it and capturing screenshots at the same time.
            APPIUM_JAVA_JUNIT: The Appium Java JUnit type.
            APPIUM_JAVA_TESTNG: The Appium Java TestNG type.
            APPIUM_PYTHON: The Appium Python type.
            APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps.
            APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps.
            APPIUM_WEB_PYTHON: The Appium Python type for Web apps.
            CALABASH: The Calabash type.
            INSTRUMENTATION: The Instrumentation type.
            UIAUTOMATION: The uiautomation type.
            UIAUTOMATOR: The uiautomator type.
            XCTEST: The XCode test type.
            XCTEST_UI: The XCode UI test type.
            testPackageArn (string) --The ARN of the uploaded test that will be run.
            filter (string) --The test's filter.
            parameters (dict) --The test's parameters, such as the following test framework parameters and fixture settings:
            For Calabash tests:
            profile: A cucumber profile, for example, 'my_profile_name'.
            tags: You can limit execution to features or scenarios that have (or don't have) certain tags, for example, '@smoke' or '@smoke,~@wip'.
            For Appium tests (all types):
            appium_version: The Appium version. Currently supported values are '1.4.16', '1.6.3', 'latest', and 'default'.
             latest  will run the latest Appium version supported by Device Farm (1.6.3).
            For  default , Device Farm will choose a compatible version of Appium for the device. The current behavior is to run 1.4.16 on Android devices and iOS 9 and earlier, 1.6.3 for iOS 10 and later.
            This behavior is subject to change.
            For Fuzz tests (Android only):
            event_count: The number of events, between 1 and 10000, that the UI fuzz test should perform.
            throttle: The time, in ms, between 0 and 1000, that the UI fuzz test should wait between events.
            seed: A seed to use for randomizing the UI fuzz test. Using the same seed value between tests ensures identical event sequences.
            For Explorer tests:
            username: A username to use if the Explorer encounters a login form. If not supplied, no username will be inserted.
            password: A password to use if the Explorer encounters a login form. If not supplied, no password will be inserted.
            For Instrumentation:
            filter: A test filter string. Examples:
            Running a single test case: 'com.android.abc.Test1'
            Running a single test: 'com.android.abc.Test1#smoke'
            Running multiple tests: 'com.android.abc.Test1,com.android.abc.Test2'
            For XCTest and XCTestUI:
            filter: A test filter string. Examples:
            Running a single test class: 'LoginTests'
            Running a multiple test classes: 'LoginTests,SmokeTests'
            Running a single test: 'LoginTests/testValid'
            Running multiple tests: 'LoginTests/testValid,LoginTests/testInvalid'
            For UIAutomator:
            filter: A test filter string. Examples:
            Running a single test case: 'com.android.abc.Test1'
            Running a single test: 'com.android.abc.Test1#smoke'
            Running multiple tests: 'com.android.abc.Test1,com.android.abc.Test2'

            (string) --
            (string) --

    :type configuration: dict
    :param configuration: Information about the settings for the run to be scheduled.
            extraDataPackageArn (string) --The ARN of the extra data for the run. The extra data is a .zip file that AWS Device Farm will extract to external data for Android or the app's sandbox for iOS.
            networkProfileArn (string) --Reserved for internal use.
            locale (string) --Information about the locale that is used for the run.
            location (dict) --Information about the location that is used for the run.
            latitude (float) -- [REQUIRED]The latitude.
            longitude (float) -- [REQUIRED]The longitude.
            radios (dict) --Information about the radio states for the run.
            wifi (boolean) --True if Wi-Fi is enabled at the beginning of the test; otherwise, false.
            bluetooth (boolean) --True if Bluetooth is enabled at the beginning of the test; otherwise, false.
            nfc (boolean) --True if NFC is enabled at the beginning of the test; otherwise, false.
            gps (boolean) --True if GPS is enabled at the beginning of the test; otherwise, false.
            auxiliaryApps (list) --A list of auxiliary apps for the run.
            (string) --
            billingMethod (string) --Specifies the billing method for a test run: metered or unmetered . If the parameter is not specified, the default value is metered .

    :type executionConfiguration: dict
    :param executionConfiguration: Specifies configuration information about a test run, such as the execution timeout (in minutes).
            jobTimeoutMinutes (integer) --The number of minutes a test run will execute before it times out.
            accountsCleanup (boolean) --True if account cleanup is enabled at the beginning of the test; otherwise, false.
            appPackagesCleanup (boolean) --True if app package cleanup is enabled at the beginning of the test; otherwise, false.

    :rtype: dict
    :return: {
        'run': {
            'arn': 'string',
            'name': 'string',
            'type': 'BUILTIN_FUZZ'|'BUILTIN_EXPLORER'|'APPIUM_JAVA_JUNIT'|'APPIUM_JAVA_TESTNG'|'APPIUM_PYTHON'|'APPIUM_WEB_JAVA_JUNIT'|'APPIUM_WEB_JAVA_TESTNG'|'APPIUM_WEB_PYTHON'|'CALABASH'|'INSTRUMENTATION'|'UIAUTOMATION'|'UIAUTOMATOR'|'XCTEST'|'XCTEST_UI',
            'platform': 'ANDROID'|'IOS',
            'created': datetime(2015, 1, 1),
            'status': 'PENDING'|'PENDING_CONCURRENCY'|'PENDING_DEVICE'|'PROCESSING'|'SCHEDULING'|'PREPARING'|'RUNNING'|'COMPLETED'|'STOPPING',
            'result': 'PENDING'|'PASSED'|'WARNED'|'FAILED'|'SKIPPED'|'ERRORED'|'STOPPED',
            'started': datetime(2015, 1, 1),
            'stopped': datetime(2015, 1, 1),
            'counters': {
                'total': 123,
                'passed': 123,
                'failed': 123,
                'warned': 123,
                'errored': 123,
                'stopped': 123,
                'skipped': 123
            },
            'message': 'string',
            'totalJobs': 123,
            'completedJobs': 123,
            'billingMethod': 'METERED'|'UNMETERED',
            'deviceMinutes': {
                'total': 123.0,
                'metered': 123.0,
                'unmetered': 123.0
            },
            'networkProfile': {
                'arn': 'string',
                'name': 'string',
                'description': 'string',
                'type': 'CURATED'|'PRIVATE',
                'uplinkBandwidthBits': 123,
                'downlinkBandwidthBits': 123,
                'uplinkDelayMs': 123,
                'downlinkDelayMs': 123,
                'uplinkJitterMs': 123,
                'downlinkJitterMs': 123,
                'uplinkLossPercent': 123,
                'downlinkLossPercent': 123
            }
        }
    }

    :returns:
    BUILTIN_FUZZ: The built-in fuzz type.
    BUILTIN_EXPLORER: For Android, an app explorer that will traverse an Android app, interacting with it and capturing screenshots at the same time.
    APPIUM_JAVA_JUNIT: The Appium Java JUnit type.
    APPIUM_JAVA_TESTNG: The Appium Java TestNG type.
    APPIUM_PYTHON: The Appium Python type.
    APPIUM_WEB_JAVA_JUNIT: The Appium Java JUnit type for Web apps.
    APPIUM_WEB_JAVA_TESTNG: The Appium Java TestNG type for Web apps.
    APPIUM_WEB_PYTHON: The Appium Python type for Web apps.
    CALABASH: The Calabash type.
    INSTRUMENTATION: The Instrumentation type.
    UIAUTOMATION: The uiautomation type.
    UIAUTOMATOR: The uiautomator type.
    XCTEST: The XCode test type.
    XCTEST_UI: The XCode UI test type.

    """
    pass


def PolsAccDeath(t):
    """Number of policies: Accidental death"""
    return 0


@classmethod
def default(cls):
    """
        Return a default Transformer with built-in transforms.
        """
    return cls(column_renamings={}, required_columns=[], column_filters=[])


def parse_settings(track_data, track_settings, line):
    """Loop through and parse the settings used in the rip."""
    for setting, reg in track_settings.items():
        result = reg.match(line)
        if result:
            track_data[setting] = result.group(1)


def escape_chars(text, chars):
    """Helper function to escape uncomfortable characters."""
    text = str(text)
    chars = list(set(chars))
    if '\\' in chars:
        chars.remove('\\')
        chars.insert(0, '\\')
    for ch in chars:
        text = text.replace(ch, '\\' + ch)
    return text


def to_json(value):
    """
    Converts given data structure to JSON form.
    Examples:

    >>> to_json([1,2,3])
    '[1, 2, 3]'
    >>> to_json({'b':2})
    '{"b": 2}'
    >>> to_json(2)
    '2'
    >>> to_json({1: {'a': [1,2,3]}})
    '{"1": {"a": [1, 2, 3]}}'
    """
    from json import dumps
    return dumps(value)


def p_definition(t):
    """definition : constant_def
                  | type_def
                  | program_def"""


@classmethod
def get_name(cls):
    """API name of the tag."""
    if not hasattr(cls, 'NAME'):
        raise NotImplementedError()
    return cls.NAME


def update_instance(instance, data: dict, properties=None):
    """Update instance properties by data from dict.

    Optionally update only properties noted in properties list.
    """
    for k, v in data.items():
        if properties and k not in properties:
            continue
        setattr(instance, k, v)


def check_type(value, tipo='boolean'):
    """
    Check if some value is on trues or falses, so
    if the value is in a set, give us the correct boolean

    """
    trues = {'true', 't', 'T', 'True', 'verdadero', '1', 's', 'S', 'Si',
        'si', 1, True}
    falses = {'falso', 'false', 'False', 'f', '0', 'n', 'N', 'No', 'no', '',
        0, False, None}
    if tipo == 'int':
        value = int(value)
    elif tipo == 'boolean':
        if value in trues:
            value = True
        elif value in falses:
            value = False
        else:
            value = False
    elif tipo in {'double', 'float', 'real'}:
        value = float(value)
    return value


def check_foreign_keys(conn):
    """Check for foreign key errors.

    Return an iterator of rows with errors.
    """
    cur = conn.cursor()
    cur.execute('PRAGMA foreign_key_check')
    yield from cur


@classmethod
def get(cls, endpoint):
    """
        Retrieves latest rate limit information for the given endpoint.
        Args:
            endpoint (str): Endpoint

        Returns:
            RateLimit: Rate limit object

        """
    return cls._limits.get(endpoint)


def raise_sys_exit():
    """Called inside interactive console to return to player_function"""
    raise SystemExit


def provider_parser(subparser):
    """Configure provider parser for Infoblox"""
    subparser.add_argument('--auth-user', help=
        'specify the user to access the Infoblox WAPI')
    subparser.add_argument('--auth-psw', help=
        'specify the password to access the Infoblox WAPI')
    subparser.add_argument('--ib-view', default='default', help=
        'specify DNS View to manage at the Infoblox')
    subparser.add_argument('--ib-host', help=
        'specify Infoblox Host exposing the WAPI')


@staticmethod
def _is_fetched(file_info):
    """Determine if file info specifies a file that is fetched."""
    return 'fetched' in file_info and file_info['fetched']


@staticmethod
def value_language(data):
    """Returns a string """
    tags = data.get('tags', None)
    if tags:
        info = tags.get('language', None)
        return info, info or 'null'
    return None, 'null'


def _line_exists(wavelengths, y, z, x0, xRes, fluxMin):
    """For a group of lines finds if the there is some change in flux greater
    than some minimum at the same redshift with different initial wavelengths

    **Parameters**

    :wavelengths: (N) ndarray

        array of initial wavelengths to check

    :y: (N) ndarray

        flux array to check

    :x0: float

        wavelength of the first value in y

    :xRes: float

        difference in wavelength between consecutive cells in flux array

    :fluxMin: float

        maximum flux to count as a line existing.

    **Returns**

    :flag: boolean

        value indicating whether all lines exist. True if all lines exist
    """
    for wl in wavelengths:
        redWl = (z + 1) * wl
        indexRedWl = (redWl - x0) / xRes
        if indexRedWl > len(y):
            return False
        if y[int(indexRedWl)] > fluxMin:
            return False
    return True


def theta_B4O5OH4_SO4_FW86(T, P):
    """a-a': tetraborate sulfate [FW86]."""
    theta = 0.12
    valid = T == 298.15
    return theta, valid


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


def olecf_header_pad_size(node=None, parent=None, attr_index=None, rawdata=
    None, new_value=None, **kwargs):
    """Size getter for the getting the byte size of the header padding."""
    if new_value is None:
        if 'sector_shift' in kwargs:
            return max(0, (1 << kwargs['sector_shift']) - 512)
        try:
            return max(0, (1 << parent.header.sector_shift) - 512)
        except AttributeError:
            return 0


def secs_to_datetime(secs: int):
    """
    Creates a datetime time object from a seconds from midnight

    Args:
        secs: seconds from midnight
    Returns:
        dt: datetime.time object representing time
    """
    import datetime
    dt = (datetime.datetime.min + datetime.timedelta(seconds=secs)).time()
    return dt


@classmethod
def _snake_case(cls, text):
    """
        Transform text to snake cale (Based on SCREAMING_SNAKE_CASE)

        :param text:
        :return:
        """
    if text.islower():
        return text
    return cls._screaming_snake_case(text).lower()


def parse_child_of_class(parent, child_class, optional=True):
    """
    Find and parse a single instance of the specified class.

    :param parent: The parent Element object.
    :param child_class: The class of the child.
    :param optional: If False, raise an exception if no node is found.

    :raises: An Exception if no node is found and ``optional`` is ``False``.

    :returns: An object of child_class, or ``None`` if no object is found and ``optional`` is ``True``.

    """
    node = parent.find(child_class.TAG_NAME)
    if node == None and not optional:
        raise Exception('Node {0} does not contain required child node {1}.'
            .format(parent.tag, child_class.TAG_NAME))
    return child_class.parse(node)


def within_duration(events, time, limits):
    """Check whether event is within time limits.

    Parameters
    ----------
    events : ndarray (dtype='int')
        N x 3 matrix with start, peak, end samples
    time : ndarray (dtype='float')
        vector with time points
    limits : tuple of float
        low and high limit for spindle duration

    Returns
    -------
    ndarray (dtype='int')
        N x 3 matrix with start , peak, end samples

    """
    min_dur = time[events[:, (2)] - 1] - time[events[:, (0)]] >= limits[0]
    max_dur = time[events[:, (2)] - 1] - time[events[:, (0)]] <= limits[1]
    return events[(min_dur & max_dur), :]


def swagger_escape(s):
    """
    / and ~ are special characters in JSON Pointers,
    and need to be escaped when used literally (for example, in path names).

    https://swagger.io/docs/specification/using-ref/#escape
    """
    return s.replace('~', '~0').replace('/', '~1')


def _normalizeIndex(size, i):
    """Convert i to a non-negative index."""
    return i + (size if i < 0 else 0)


@staticmethod
def find_element(elements, field, value):
    """ Helper method to lookup an element in an array by field value. """
    for e in elements:
        if e[field] == value:
            return e
    assert False, 'element not found, {}={}'.format(field, value)


def _solarZenith(date, lat=-3.13, lon=-60.016667, lon0=-63.0, negative=
    False, dr=None):
    """
    Calculates the solar zenith angle at any given day

    needs validation and needs to work without lon0

    Parameters
    -----------
    date: datetime object
        the date and time for which the zenith angle has to be calculated
    lat: float
        latitude in degrees
    lon: float
        longitude in degrees
    lon0: float
        DEFINE IT BETTER

    dr is the julian day of the solstice. Default is to get from dictionary

    Returns
    --------
    zen_ang: float
        the zenith angle in degrees
    """
    from math import pi, sin, cos, acos, radians, degrees
    from calendar import isleap
    from datetime import timedelta
    if dr == None:
        from .constants import sumsolstice
        dr = sumsolstice[date.year].timetuple().tm_yday
    if isleap(date.year):
        da = 366
    else:
        da = 365
    tt = date.timetuple()
    j_day = tt.tm_yday
    gamma = 2.0 * pi / 365.0 * (j_day - 1.0)
    et = 1.0 / 60.0 * (229.18 * (7.5e-05 + 0.001868 * cos(gamma) - 0.032077 *
        sin(gamma) - 0.014615 * cos(2.0 * gamma) - 0.04089 * sin(2.0 * gamma)))
    y = (lon - lon0) / 15.0 * 60.0
    soma = y + 60.0 * et
    solar_date = date + timedelta(soma / (24.0 * 60.0))
    delta = 0.409 * cos(2.0 * pi * (j_day - dr) / da)
    Hsv = (solar_date.hour + solar_date.minute / 60.0 + solar_date.second /
        3600.0)
    h = 2.0 * pi / 24.0 * (Hsv - 12.0)
    zen_ang = degrees(acos(sin(radians(lat)) * sin(delta) + cos(radians(lat
        )) * cos(delta) * cos(h)))
    if negative:
        if solar_date.hour <= 12:
            return zen_ang
        else:
            return -zen_ang
    else:
        return zen_ang


@classmethod
def _is_transaction_to_be_applied(cls, transaction) ->bool:
    """ determine if the transaction would be applied, even if zero transactions are found
        :param transaction: the working transaction
        :returns: a boolean value to determine if the transaction needs to be filtered out or not

        """
    if (transaction.transaction_type.post_zeros == True or transaction.
        total_amount > 0):
        return True
    else:
        return False


def getAvailableLanguages():
    """Returns a list of available languages if we provide II18nRead"""


def formula_2016_01_01(foyer_fiscal, period, parameters):
    """
        Investissements outre-mer dans le logement social (déclaration n°2042 IOM)
        2016
        """
    fhkh = foyer_fiscal('fhkh', period)
    fhki = foyer_fiscal('fhki', period)
    fhqj = foyer_fiscal('fhqj', period)
    fhqk = foyer_fiscal('fhqk', period)
    fhqn = foyer_fiscal('fhqn', period)
    fhqs = foyer_fiscal('fhqs', period)
    fhqu = foyer_fiscal('fhqu', period)
    fhqw = foyer_fiscal('fhqw', period)
    fhqx = foyer_fiscal('fhqx', period)
    fhra = foyer_fiscal('fhra', period)
    fhrb = foyer_fiscal('fhrb', period)
    fhrc = foyer_fiscal('fhrc', period)
    fhrd = foyer_fiscal('fhrd', period)
    fhxa = foyer_fiscal('fhxa', period)
    fhxb = foyer_fiscal('fhxb', period)
    fhxc = foyer_fiscal('fhxc', period)
    fhxe = foyer_fiscal('fhxe', period)
    fhxf = foyer_fiscal('fhxf', period)
    fhxg = foyer_fiscal('fhxg', period)
    fhxh = foyer_fiscal('fhxh', period)
    fhxi = foyer_fiscal('fhxi', period)
    fhxk = foyer_fiscal('fhxk', period)
    fhxl = foyer_fiscal('fhxl', period)
    fhxm = foyer_fiscal('fhxm', period)
    fhxn = foyer_fiscal('fhxn', period)
    fhxo = foyer_fiscal('fhxo', period)
    fhxp = foyer_fiscal('fhxp', period)
    report_reduc_2011 = fhqn + fhqu + fhqk
    report_reduc_2012 = fhqj + fhqs + fhqw + fhqx
    report_reduc_2013 = fhra + fhrb + fhrc + fhrd
    report_reduc_2014 = fhxa + fhxb + fhxc + fhxe
    report_reduc_2015 = fhxf + fhxg + fhxh + fhxi + fhxk
    reduc_invest_2016 = fhxl + fhxm + fhxn + fhxo + fhxp
    return (report_reduc_2011 + report_reduc_2012 + report_reduc_2013 +
        report_reduc_2014 + report_reduc_2015 + reduc_invest_2016)


def edit(id, enabled=None, condition=None):
    """Edits a before save and after retrieve modifier.

        None values leave the respective parameter unchanged.

        The respective modifier only gets called if it is enabled and
        the 'condition' evaluates to a True value.
        """


def get_fno(obj):
    """
    Try to get the best fileno of a obj:
        * If the obj is a integer, it return that integer.
        * If the obj has a fileno method, it return that function call.
    """
    if obj is None:
        return None
    elif isinstance(obj, int):
        return obj
    elif hasattr(obj, 'fileno') and callable(getattr(obj, 'fileno')):
        return obj.fileno()
    raise TypeError('Expected None, int or fileobject with fileno method')


def sentiments_to_list(doc_id, analyzed, single_document=False):
    """Converts sentiments response to flat lists with doc_id included

    :param doc_id: Will be inserted to each row as first element
    :param analyzed: Response json from anacode api for sentiment call
    :type analyzed: list
    :param single_document: Is analysis describing just one document
    :type single_document: bool
    :return: dict -- Dictionary with one key 'sentiments' pointing to flat list
     of sentiment probabilities
    """
    sen_list = []
    for order, sentiment in enumerate(analyzed):
        row = [doc_id, 0, sentiment['sentiment_value']]
        if single_document:
            row[1] += order
        else:
            row[0] += order
        sen_list.append(row)
    return {'sentiments': sen_list}


@staticmethod
def get_default_config():
    """Get default configuration."""
    return {}


def encode_entry(entry):
    """Convert from an entry to a JSON-representation."""
    return [entry.key, entry.settings, entry.constraints.to_json()]


def _xhj_gc_files_to_rmfiles(hsize, files):
    """Return the history files to remove to get under the file limit."""
    rmfiles = files[:-hsize] if len(files) > hsize else []
    return rmfiles


@classmethod
def drop_table_query(cls, container, aset_name):
    """Returns a SQL statement to drop the auxiliary table."""
    entitySetA, nameA, entitySetB, nameB, uniqueKeys = container.aux_table[
        aset_name]
    query = ['DROP TABLE ', container.mangled_names[aset_name,]]
    return ''.join(query)


@classmethod
def from_dict(cls, d, strict=True):
    """
        Create a PassTheSalt object from a dictionary.

        Args:
            d (dict): the input dictionary.
            strict (bool): if set to False then no exception will be raised when
                unknown dictionary keys are present.

        Returns:
            PassTheSalt: a new PassTheSalt object.
        """
    pts = super().from_dict(d, strict=strict)
    for label, secret in pts.secrets.items():
        secret.add_context(label, pts)
    return pts


def parse_yaml(yml):
    """
    Parse a load YAML file per momo format: looking for 'name' and 'contents'
    """
    name = None
    contents = None
    for d in yml:
        if 'name' in d:
            name = d['name']
        if 'contents' in d:
            contents = d['contents']
    return name, contents


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.cognitive.IdentifyFaces'


@classmethod
def get_name(cls):
    """ Returns the name of the evaluation hook.
        """
    return 'text'


def modify_utilities(time, reward, rulenames, rules, model_parameters):
    """
    Update rules with newly calculated utilites for rules whose firing led to reward.
    """
    for rulename in rulenames:
        for t in rulenames[rulename]:
            utility_time = time - t
            rules[rulename]['utility'] = round(rules[rulename]['utility'] +
                model_parameters['utility_alpha'] * (reward - utility_time -
                rules[rulename]['utility']), 4)


def def_grads(prims):
    """ Define gradients of primitives """
    prims('normal').def_grad_zero()
    prims('uniform').def_grad_zero()


def compute_diffs(df_dict, df_str, gridclimname1, gridclimname2, prefix1,
    prefix2='meanmonth', comp_dict=None):
    """
    Compute difference between monthly means (e.g,. Temp) for two different gridded datasets (e.g., Liv, WRF)
    """
    if isinstance(comp_dict, type(None)):
        comp_dict = {}
    for each1 in prefix1:
        for each2 in prefix2:
            diffs = df_dict['_'.join([each2, each1, gridclimname1])] - df_dict[
                '_'.join([each2, each1, gridclimname2])]
            comp_dict['_'.join([str(each1), df_str])] = diffs
    return comp_dict


def to_list(possible_lst):
    """
    Coerce argument to a list by all means.

    Lists are returned unchanged, strings return a list with a single element,
    and otherwise an empty list is returned.
    """
    if isinstance(possible_lst, list):
        return possible_lst
    elif isinstance(possible_lst, str):
        return [possible_lst]
    else:
        return []


def parameters_ui(layout, params):
    """ Create the ui for the rig parameters.
    """
    r = layout.row()
    r.prop(params, 'make_rotations')
    r = layout.row()
    r.prop(params, 'tweak_extra_layers')
    r.active = params.tweak_extra_layers
    col = r.column(align=True)
    row = col.row(align=True)
    for i in range(8):
        row.prop(params, 'tweak_layers', index=i, toggle=True, text='')
    row = col.row(align=True)
    for i in range(16, 24):
        row.prop(params, 'tweak_layers', index=i, toggle=True, text='')
    col = r.column(align=True)
    row = col.row(align=True)
    for i in range(8, 16):
        row.prop(params, 'tweak_layers', index=i, toggle=True, text='')
    row = col.row(align=True)
    for i in range(24, 32):
        row.prop(params, 'tweak_layers', index=i, toggle=True, text='')


def noop(*args, **kwargs):
    """No-op function that does nothing and returns ``None``.

    This is useful for defining scoring callbacks that do not need a
    target extractor.
    """


def __iter__():
    """Iterate over revision numbers for this manifest."""


def ant_select_callback():
    """JS callback for the selection and de-selection of antennas

    Returns
    -------
    code : :obj:`str`
    """
    code = """
            /*ax: list containing glyph renderers
              bsel: batch selection group button
              nbatches: Number of batches available
              fsel: field_selector widget,
              csel: corr_select widget,
              ssel: spw_select widget,
              nfields: Number of available fields,
              ncorrs: Number of avaiblable corrs,
              nspws: Number of spectral windows,
            */
            let nplots = ax.length;
            if (cb_obj.active.includes(0))
                {
                    for(let i=0; i<nplots; i++){
                        ax[i].visible = true;
                    }
                    //activate all the checkboxes whose antennas are active
                    bsel.active = [...Array(nbatches).keys()]
                    csel.active = [...Array(ncorrs).keys()]
                    fsel.active = [...Array(nfields).keys()]
                    ssel.active = [...Array(nspws).keys()]

                }
            else{
                    for(let i=0; i<nplots; i++){
                       ax[i].visible = false;
                    }

                    bsel.active = []
                    csel.active = []
                    fsel.active = []
                    ssel.active = []
                }
            """
    return code


def rsa_crt_dmq1(private_exponent, q):
    """
    Compute the CRT private_exponent % (q - 1) value from the RSA
    private_exponent (d) and q.
    """
    return private_exponent % (q - 1)


def _fn(stateName):
    """ Returns the callable name OR if stateName is a string just return it """
    nextState = None
    if hasattr(stateName, '__call__'):
        nextState = stateName.__name__
    else:
        nextState = stateName
    return nextState


def p_columns(p):
    """columns : '(' list ')'"""
    p[0] = p[2]


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

        :returns: this backend does not support items resuming
        """
    return False


def receivedSubject(room, user, subject):
    """
        The room subject has been received.

        A subject is received when you join a room and when the subject is
        changed.

        @param room: The room the subject was accepted for.
        @type room: L{muc.Room}

        @param user: The user that set the subject.
        @type  user: L{muc.User}

        @param subject: The subject of the given room.
        @type subject: C{unicode}
        """


def _normalize_sequence(array, value, fname):
    """
    values = _normalize_sequence(array, value, fname)

    If `value` is a sequence, checks that it has an element for each dimension
    of `array`. Otherwise, returns a sequence that repeats `value` once for
    each dimension of array.

    Parameters
    ----------
    array : ndarray
    value : sequence or scalar
    fname : str
        Function name. Used in error messages

    Returns
    -------
    values : sequence
    """
    try:
        value = list(value)
    except TypeError:
        return [value for s in array.shape]
    if len(value) != array.ndim:
        raise ValueError(
            'mahotas.%s: argument is sequence, but has wrong size (%s for an array of %s dimensions)'
             % (fname, len(value), array.ndim))
    return value


def json_response(request):
    """Determine if the request's response should be JSON."""
    if request.query.get('format') == 'json':
        return True
    else:
        return request.content_type == 'application/json'


@staticmethod
def _singleton(it):
    """Test whether iterable contains one unique element.

        :param it: iterable

        :returns: bool, iterable contains one unique element
        """
    return len(set(it)) == 1


def percentage(x, pos):
    """
    Adds percentage sign to plot ticks.
    """
    return '%.0f%%' % x


def extract_dtype(descriptor, key):
    """
    Work around the fact that we currently report jsonschema data types.
    """
    reported = descriptor['data_keys'][key]['dtype']
    if reported == 'array':
        return float
    else:
        return reported


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

        :param UserLogInfo val:
        :rtype: ActorLogInfo
        """
    return cls('user', val)


def process_request(req):
    """Process the request.

        Return a `(template_name, data)` pair, where `data` is a
        dictionary of substitutions for the Jinja2 template (the
        template context, in Jinja2 terms).

        Optionally, the return value can also be a `(template_name,
        data, metadata)` triple, where `metadata` is a `dict` with
        hints for the template engine or the web front-end.

        Keys supported are:

          - `'content_type'`: the mimetype used for content delivery;
            "text/html" is assumed if the key is not present or the
            `metadata` was not specified

          - `'text'`: a boolean value indicating whether the Jinja2
            auto-escaping feature should be deactivated
            (``text=True``) or not (``text=False``); defaults to
            ``False``, suitable for generating HTML or XML content

          - `'fragment'`: a boolean value indicating whether the
            generated content will be used as part of another page
            (``fragment=True``) or as a stand-alone page
            (``fragment=False``), the default

          - `'domain'`: a string value indicating the translation
            domain to which the translated strings in the template
            belong to

        Note that if template processing should not occur, this method
        can simply send the response itself (see `Request` methods)
        and not return anything, as the `Request` methods raise a
        `RequestDone` exception.

        :Since 1.0: Clearsilver templates are no longer supported.

        :Since 1.1.2: the rendering `method` (xml, xhtml or text) may be
           returned as a fourth parameter in the tuple, but if not specified
           it will be inferred from the `content_type` when rendering the
           template.

        :Since 1.3.2: returns a pair, or a tuple in which the third
           element is a `dict` instead of a string like in the old
           API.  Note that the old API (`(template, data,
           content_type)` where `content_type` is a string or `None`)
           is still supported. When used, this means that `template`
           is a legacy Genshi template. This support for the old API
           will be removed in Trac 1.5.1, in which `metadata` will
           always be a `dict` or `None` when specified.

        """


def get_zscores(returns):
    """
    Returns the Z-scores of the input returns.

    Parameters
    ----------
    returns : Series or DataFrame, required
        Series or DataFrame of returns

    Returns
    -------
    Series or DataFrame
    """
    nonzero_returns = returns.where(returns != 0)
    z_scores = (nonzero_returns - nonzero_returns.mean()
        ) / nonzero_returns.std()
    return z_scores


@classmethod
def create_auth_token(cls, user_id):
    """Creates a new authorization token for a given user ID.

        :param user_id:
            User unique ID.
        :returns:
            A string with the authorization token.
        """
    return cls.token_model.create(user_id, 'auth').token


def remove_comments(manifest_stream):
    """
    Removes all '#'s and everything after a '#' on the same line.
    """
    for line in manifest_stream:
        yield line.split('#')[0]


@staticmethod
def any_events(events, count):
    """An evaluation function that returns ``True`` if at least one of
        *events* has been triggered."""
    return count > 0 or len(events) == 0


def parse_args(cli, args):
    """
    Parses command line arguments and executes the chosen subcommand.
    :param cli: Cli command line interface object
    :param args: list of command line arguments (e.g. sys.argv)
    """
    namespace = cli.parse_args(args)
    namespace.func(namespace)


def get_int(message, default):
    """
    transfer user input to int numbers. Continue asking unless valid input.
    If user omit the input and default is set to non-None, get default number
    instand.

    :para message: input message should to user
    :type: string

    :para default: default value

    :rtype: int
    """
    while True:
        response = input(message)
        if response == '':
            if default is None:
                print('Please input an integer value.')
                continue
            else:
                return default
        else:
            try:
                return int(response)
            except ValueError:
                print('Please input integer value.')


def link_viewer():
    """Link to viewer node

    """
    pass


def count(iterable):
    """
    Consumes all items in an iterable and returns a count.
    """
    n = 0
    for item in iterable:
        n += 1
    return n


def common_filters(marker=None, limit=None, sort_key=None, sort_dir=None,
    fields=None, detail=False):
    """Generate common filters for any list request.

    :param marker: entity ID from which to start returning entities.
    :param limit: maximum number of entities to return.
    :param sort_key: field to use for sorting.
    :param sort_dir: direction of sorting: 'asc' or 'desc'.
    :param fields: a list with a specified set of fields of the resource
                   to be returned.
    :param detail: Boolean, True to return detailed information. This parameter
                   can be used for resources which accept 'detail' as a URL
                   parameter.
    :returns: list of string filters.
    """
    filters = []
    if isinstance(limit, int) and limit > 0:
        filters.append('limit=%s' % limit)
    if marker is not None:
        filters.append('marker=%s' % marker)
    if sort_key is not None:
        filters.append('sort_key=%s' % sort_key)
    if sort_dir is not None:
        filters.append('sort_dir=%s' % sort_dir)
    if fields is not None:
        filters.append('fields=%s' % ','.join(fields))
    if detail:
        filters.append('detail=True')
    return filters


def feeder_callback(future):
    """Used to recognize asyncio task as AsyncioRunner feeder"""
    pass


def omit(*names):
    """Return a modified instance omitting given items."""


def prim_vec(prim_vec):
    """
    Check parameter *prim_vec*.

    :raises TypeError: Parameter prim_vec must be a list.
    :raises ValueError: Parameter prim_vec must be a list
      of length 1 for 1D lattices or length 2 fro 2D lattices.
    :raises TypeError: List elements must be tuples.
    :raises ValueError: List elements must be 1 or 2 tuples.
    :raises ValueError: Tuples must be of length 2.
    :raises ValueError: Tuples must containt real numbers.
    :raises ValueError: Norm of coor should be larger than 0.1.
    """
    if not isinstance(prim_vec, list):
        raise TypeError('\n\nParameter prim_vec must be a list.\n')
    if not len(prim_vec) == 1 and not len(prim_vec) == 2:
        raise ValueError(
            """

Parameter prim_vec must be a list.
of length 1 for 1D lattices or length 2 fro 2D lattices.
"""
            )
    if 1 > len(prim_vec) > 2:
        raise ValueError(
            '\n\nParameter prim_vec value must be a list of length 1 or 2.\n')
    for coor in prim_vec:
        if not isinstance(coor, tuple):
            raise TypeError('\n\nParameter prim_vec contain tuples\n')
        if len(coor) != 2:
            raise ValueError(
                '\n\nParameter prim_vec contain tuples of length 2.\n')
        if not isinstance(coor[0], (int, float)) or not isinstance(coor[1],
            (int, float)):
            raise ValueError('\n\ncoor must contain real numbers.\n')
        if coor[0] ** 2 + coor[1] ** 2 < 0.1:
            raise ValueError('\n\nNorm of coor should be larger than 0.1.\n')


def format_duration(time):
    """format duration, unit of input time should be 'second'."""
    fmt = ''
    if time < 1:
        fmt = '{:.3f} ms'.format(time * 1000)
    elif time >= 1 and time < 60:
        fmt = '{:.3f} sec'.format(time)
    elif time >= 60 and time < 3600:
        min = int(time / 60)
        sec = time - min * 60
        fmt = '{:d} min {:.3f} sec'.format(min, sec)
    elif time >= 3600 and time < 86400:
        hour = int(time / 3600)
        min = int((time - hour * 3600) / 60)
        sec = time - hour * 3600 - min * 60
        fmt = '{:d} hour {:d} min {:.3f} sec'.format(hour, min, sec)
    else:
        day = int(time / 86400)
        hour = int((time - day * 86400) / 3600)
        min = int((time - day * 86400 - hour * 3600) / 60)
        sec = time - day * 86400 - hour * 3600 - min * 60
        fmt = '{:d} day {:d} hour {:d} min {:.3f} sec'.format(day, hour,
            min, sec)
    return fmt


@classmethod
def _name(cls):
    """Helper to get the class name once it's been created"""
    return cls.__name__


def get_resource(path: str, mode: str='rb'):
    """Returns the contents of the given resource file path."""
    with open(path, mode=mode) as f:
        return f.read()


def smartAppend(table, name, value):
    """
    helper function for apppending in a dictionary
    """
    if name not in list(table.keys()):
        table[name] = []
    table[name].append(value)


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 process_management_config_section(config, management_config):
    """ Processes the management section from a configuration data dict.

    :param config: The config reference of the object that will hold the
    configuration data from the config_data.
    :param management_config: Management section from a config data dict.
    """
    if 'commands' in management_config:
        for command in management_config['commands']:
            config.management['commands'].append(command)


def get(name, default=None):
    """Return the form field with the given name

        If the desired firld has a prefix, then the given name should
        be the prefix, a dot, and the unprefixed name.  Otherwise, the
        given name is just the field name.

        Return the default if a field can't be found for the given name.
        """


def remove_tags_from_vault(accountId=None, vaultName=None, TagKeys=None):
    """
    This operation removes one or more tags from the set of tags attached to a vault. For more information about tags, see Tagging Amazon Glacier Resources . This operation is idempotent. The operation will be successful, even if there are no tags attached to the vault.
    See also: AWS API Documentation

    Examples
    The example removes two tags from the vault named examplevault.
    Expected Output:

    :example: response = client.remove_tags_from_vault(
        vaultName='string',
        TagKeys=[
            'string',
        ]
    )

    :type accountId: string
    :param accountId: The AccountId value is the AWS account ID of the account that owns the vault. You can either specify an AWS account ID or optionally a single '- ' (hyphen), in which case Amazon Glacier uses the AWS account ID associated with the credentials used to sign the request. If you use an account ID, do not include any hyphens ('-') in the ID.
            Note: this parameter is set to '-' bydefault if no value is not specified.

    :type vaultName: string
    :param vaultName: [REQUIRED]
            The name of the vault.

    :type TagKeys: list
    :param TagKeys: A list of tag keys. Each corresponding tag is removed from the vault.
            (string) --

    :return: response = client.remove_tags_from_vault(
        TagKeys=[
            'examplekey1',
            'examplekey2',
        ],
        accountId='-',
        vaultName='examplevault',
    )

    print(response)

    """
    pass


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

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


@staticmethod
def p_expression_group(p):
    """expression : '(' expression ')'"""
    p[0] = p[2]


@staticmethod
def p_calibration_handle_optional_list(p):
    """calibration_handle_optional_list : calibration_handle_optional
                                            | calibration_handle_optional calibration_handle_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def Rouse(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D = \\frac{24}{Re} + \\frac{3}{Re^{0.5}} + 0.34

    Parameters
    ----------
    Re : float
        Reynolds number of the sphere, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is Re <= 2E5

    Examples
    --------
    >>> Rouse(200.)
    0.6721320343559642

    References
    ----------
    .. [1] H. Rouse, Fluid Mechanics for Hydraulic Engineers, Dover,
       New York, N.Y., 1938
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    Cd = 24.0 / Re + 3 / Re ** 0.5 + 0.34
    return Cd


def sizeof_fmt(num, suffix='B', longsuffix=True, usespace=True, base=1024):
    """ Returns a string representation of the size ``num``.

    - Examples:
    >>> sizeof_fmt(1020)
    '1020 B'
    >>> sizeof_fmt(1024)
    '1 KiB'
    >>> sizeof_fmt(12011993)
    '11.5 MiB'
    >>> sizeof_fmt(123456789)
    '117.7 MiB'
    >>> sizeof_fmt(123456789911)
    '115 GiB'

    Options include:

    - No space before unit:
    >>> sizeof_fmt(123456789911, usespace=False)
    '115GiB'

    - French style, with short suffix, the "O" suffix for "octets", and a base 1000:
    >>> sizeof_fmt(123456789911, longsuffix=False, suffix='O', base=1000)
    '123.5 GO'

    - Reference: https://stackoverflow.com/a/1094933/5889533
    """
    num = float(num)
    base = float(base)
    suffixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
    if longsuffix:
        suffixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi']
    for unit in suffixes[:-1]:
        if abs(num) < base:
            return '{num:3.1f}{space}{unit}{suffix}'.format(num=num, space=
                ' ' if usespace else '', unit=unit, suffix=suffix).replace('.0'
                , '')
        num /= base
    return '{num:.1f}{space}{unit}{suffix}'.format(num=num, space=' ' if
        usespace else '', unit=suffixes[-1], suffix=suffix).replace('.0', '')


def cf_xy_coord_names(crs):
    """ Returns appropriate names for coordinates given CRS

    Parameters
    ----------
    crs : rasterio.crs.CRS
        Coordinate reference system

    Returns
    -------
    str : x_coord_name
        X coordinate name
    str : y_coord_name
        Y coordinate name

    Examples
    --------
    >>> cf_crs_attrs(CRS.from_epsg(4326))  # WGS84
    ('longitude', 'latitude')
    >>> cf_crs_attrs(CRS.from_epsg(32619))  # UTM19N
    ('x', 'y')
    """
    if crs.is_geographic:
        return 'longitude', 'latitude'
    elif crs.is_projected:
        return 'x', 'y'
    else:
        raise ValueError('CRS must either be geographic or projected')


def region_quadview():
    """Split selected area into camera, front, right & top views

    """
    pass


def get_rp_health_summary(isamAppliance, check_mode=False, force=False):
    """
    Retrieving a summary of Reverse Proxy health
    """
    return isamAppliance.invoke_get(
        'Retrieving a summary of Reverse Proxy health',
        '/wga/widgets/health.json')


def is_descending(input_list: list, step: int=-1) ->bool:
    """llogic.is_descending(input_list[, step])

    This function returns True if the input list is descending with a fixed
    step, otherwise it returns False. Usage:

    >>> alist = [3, 2, 1, 0]
    >>> llogic.is_descending(alist)
    True

    The final value can be other than zero:

    >>> alist = [12, 11, 10]
    >>> llogic.is_descending(alist)
    True

    The list can also have negative elements:

    >>> alist = [2, 1, 0, -1, -2]
    >>> llogic.is_descending(alist)
    True

    It will return False if the list is not ascending:

    >>> alist = [6, 5, 9, 2]
    >>> llogic.is_descending(alist)
    False

    By default, the function uses steps of size 1 so the list below is not
    considered as ascending:

    >>> alist = [7, 5, 3, 1]
    >>> llogic.is_descending(alist)
    False

    But the user can set the step argument to any value less than one:

    >>> alist = [7, 5, 3, 1]
    >>> step = -2
    >>> llogic.is_descending(alist, step)
    True
    """
    if not isinstance(input_list, list):
        raise TypeError("'input_list' must be 'list'")
    if not isinstance(step, int):
        raise TypeError("'step' must be 'int'")
    if step > 1:
        raise ValueError("'step' must be < 0")
    aux_list = list(range(max(input_list), min(input_list) - 1, step))
    return input_list == aux_list


def sort_alpha(branch, tags):
    """Sort tags lexicographically, in place.

    :param branch: Branch
    :param tags: List of tuples with tag name and revision id.
    """
    tags.sort()


def zsnap_storage_node(session, cloud_name, sn_id, return_type=None, **kwargs):
    """
    Create Storage Node ZSnap

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type cloud_name: str
    :param cloud_name: Cloud Name: i.e: zadaraqa9

    :type sn_id: str
    :param sn_id: Storage Node ID

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/clouds/{0}/nodes/{1}/zsnap.json'.format(cloud_name, sn_id)
    return session.post_api(path=path, return_type=return_type, **kwargs)


def create_backend_from_checkpoint(checkpoint_params, restore=None, weights
    =None, processes=-1):
    """
    Create a Backend implementation object based on NetworkParameters.

    Parameters
    ----------
    checkpoint_params : any
        the checkpoint to load
    restore : str
        path to a file to restore if a network is created
    weights : str
        path to a file to copy weights
    processes : int
        number of processes to use for all nets created by this backend.
        A negative number uses the default params as suggestest by the backend.

    Returns
    -------
        A net backend implementation object

    """
    from calamari_ocr.ocr.backends.tensorflow_backend.tensorflow_backend import TensorflowBackend
    return TensorflowBackend(checkpoint_params, processes=processes)


def reverseMnIds(nMax):
    """Returns reverse indexes according to stacked coefficients of orders m up to nMax.

    Parameters
    ----------
    nMax : (int)
        Maximum degree of coefficients reverse indexes to be returned. n >= 0

    Returns
    -------
    rev_ids : (int), array_like
        0, 3, 2, 1, 8, 7, 6, 5, 4, ...
    """
    m_ids = list(range(nMax * (nMax + 2) + 1))
    for o in range(nMax + 1):
        id_start = o ** 2
        id_end = id_start + o * 2 + 1
        m_ids[id_start:id_end] = reversed(m_ids[id_start:id_end])
    return m_ids


@staticmethod
def _get_parameter_format_specifier(parameter):
    """
        Returns the appropriate format specifier for a parameter type.

        :param dict[str,str] parameter: The parameter metadata.

        :rtype: str
        """
    lookup = {'bigint': '%s::bigint', 'integer': '%s::int', 'bit':
        '%s::bit(4)', 'smallint': '%s::smallint', 'money': '%s::money',
        'numeric': '%s::numeric', 'real': '%s::real', 'character':
        '%s::char', 'character varying': '%s::varchar',
        'timestamp without time zone': '%s::timestamp',
        'time without time zone': '%s::timestamp', 'boolean': '%s::bool',
        'date': '%s::date', 'bytea': '%s::bytea', 'text': '%s::text'}
    if parameter['data_type'] in lookup:
        return lookup[parameter['data_type']]
    raise Exception('Unexpected data type {0!s}.'.format(parameter[
        'data_type']))


def select_more():
    """Select keys linked to boundary selected keys of each particle

    """
    pass


def toZone(z):
    """Return a DateTime with the value as the current object,
        represented in the indicated timezone."""


def fail(why):
    """fail() is called to indicate that the download has failed. 'why'
        is a Failure object indicating what went wrong. No further methods
        will be invoked on the IDownloadTarget after fail()."""


@staticmethod
def __trailing_backslash(path):
    """Removes blackslash from variables that contains paths."""
    if not path:
        return path
    if path[-1] != '/':
        return path
    return path[:-1]


@staticmethod
def _fix_column_widths(writer, df, sheet_name):
    """
        Find an appropriate width for each column for a given sheet.

        Parameters
        ----------
        writer : pandas.ExcelWriter
            The object which holds the handle to the Excel spreadsheet file.
        df : pandas.DataFrame
            The data frame of the data we're writing to disk.
        sheet_name : str
            The name of the current sheet.

        Notes
        -----
        Lifted more or less verbatim from https://stackoverflow.com/a/40535454.

        """
    for idx, col in enumerate(df.columns):
        series = df[col]
        max_len = max((series.astype(str).map(len).max(), len(str(series.
            name)))) + 2
        writer.sheets[sheet_name].set_column(idx, idx, max_len)


def state_move_up():
    """Move boid state up in the list

    """
    pass


def get_fields_from_model(model_class):
    """Returns all fields, including inherited fields but ignoring M2M fields."""
    return model_class._meta.fields


def get_saml_provider(SAMLProviderArn=None):
    """
    Returns the SAML provider metadocument that was uploaded when the IAM SAML provider resource object was created or updated.
    See also: AWS API Documentation

    :example: response = client.get_saml_provider(
        SAMLProviderArn='string'
    )

    :type SAMLProviderArn: string
    :param SAMLProviderArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the SAML provider resource object in IAM to get information about.
            For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    :rtype: dict
    :return: {
        'SAMLMetadataDocument': 'string',
        'CreateDate': datetime(2015, 1, 1),
        'ValidUntil': datetime(2015, 1, 1)
    }

    """
    pass


def get_uniprot_id_from_mapping(data, full_entry=False, uniprot_id=None):
    """
    Gets a list of UniProt IDs from a '"xrefs/id/"' mapping.

    :param data: Requests object from the Ensembl-UniProt Mapping
    :param full_entry: (boolean) if True gets dictionary instead of just
        the UniProt IDs
    :param uniprot_id: if not None means that we want the data for a specific
        UniProt ID
    :return: list of UniProt IDs
    """
    uniprots = []
    for entry in data:
        if 'dbname' in entry and 'primary_id' in entry:
            if uniprot_id is not None and entry['primary_id'] == uniprot_id:
                if full_entry:
                    uniprots = [entry]
                else:
                    uniprots = [entry['primary_id']]
                break
            elif entry['dbname'] == 'Uniprot/SWISSPROT':
                if entry['primary_id'] not in uniprots:
                    if full_entry:
                        uniprots.append(entry)
                    else:
                        uniprots.append(entry['primary_id'])
            elif entry['dbname'] == 'Uniprot/SPTREMBL':
                if entry['primary_id'] not in uniprots:
                    if full_entry:
                        uniprots.append(entry)
                    else:
                        uniprots.append(entry['primary_id'])
    return uniprots


def get_encryption_key():
    """Return a Deferred that fires with a 16-byte AES key. This key will
        be used to encrypt the data. The key will also be hashed to derive
        the StorageIndex.

        Uploadables that want to achieve convergence should hash their file
        contents and the serialized_encoding_parameters to form the key
        (which of course requires a full pass over the data). Uploadables can
        use the upload.ConvergentUploadMixin class to achieve this
        automatically.

        Uploadables that do not care about convergence (or do not wish to
        make multiple passes over the data) can simply return a
        strongly-random 16 byte string.

        get_encryption_key() may be called multiple times: the IUploadable is
        required to return the same value each time.
        """


@staticmethod
def find_subtree(lines: list, init: int) ->tuple:
    """Find limits of a self-consistent subtree to be used by _construct_tree()."""
    n_lines = len(lines)
    start = init
    end = init + 1
    open_brackets = 1
    while open_brackets > 0 and end < n_lines:
        if lines[end].endswith('{'):
            open_brackets += 1
        elif lines[end].endswith('}'):
            open_brackets -= 1
        end += 1
    return start, end


def create_proj_geom(intype, *args):
    """Create a projection geometry.

This method can be called in a number of ways:

``create_proj_geom('parallel', detector_spacing, det_count, angles)``:

:param detector_spacing: Distance between two adjacent detector pixels.
:type detector_spacing: :class:`float`
:param det_count: Number of detector pixels.
:type det_count: :class:`int`
:param angles: Array of angles in radians.
:type angles: :class:`numpy.ndarray`
:returns: A parallel projection geometry.

``create_proj_geom('fanflat', det_width, det_count, angles, source_origin, origin_det)``:

:param det_width: Size of a detector pixel.
:type det_width: :class:`float`
:param det_count: Number of detector pixels.
:type det_count: :class:`int`
:param angles: Array of angles in radians.
:type angles: :class:`numpy.ndarray`
:param source_origin: Position of the source.
:param origin_det: Position of the detector
:returns: A fan-beam projection geometry.

``create_proj_geom('fanflat_vec', det_count, V)``:

:param det_count: Number of detector pixels.
:type det_count: :class:`int`
:param V: Vector array.
:type V: :class:`numpy.ndarray`
:returns: A fan-beam projection geometry.

``create_proj_geom('parallel3d', detector_spacing_x, detector_spacing_y, det_row_count, det_col_count, angles)``:

:param detector_spacing_*: Distance between two adjacent detector pixels.
:type detector_spacing_*: :class:`float`
:param det_row_count: Number of detector pixel rows.
:type det_row_count: :class:`int`
:param det_col_count: Number of detector pixel columns.
:type det_col_count: :class:`int`
:param angles: Array of angles in radians.
:type angles: :class:`numpy.ndarray`
:returns: A parallel projection geometry.

``create_proj_geom('cone', detector_spacing_x, detector_spacing_y, det_row_count, det_col_count, angles, source_origin, origin_det)``:

:param detector_spacing_*: Distance between two adjacent detector pixels.
:type detector_spacing_*: :class:`float`
:param det_row_count: Number of detector pixel rows.
:type det_row_count: :class:`int`
:param det_col_count: Number of detector pixel columns.
:type det_col_count: :class:`int`
:param angles: Array of angles in radians.
:type angles: :class:`numpy.ndarray`
:param source_origin: Distance between point source and origin.
:type source_origin: :class:`float`
:param origin_det: Distance between the detector and origin.
:type origin_det: :class:`float`
:returns: A cone-beam projection geometry.

``create_proj_geom('cone_vec', det_row_count, det_col_count, V)``:

:param det_row_count: Number of detector pixel rows.
:type det_row_count: :class:`int`
:param det_col_count: Number of detector pixel columns.
:type det_col_count: :class:`int`
:param V: Vector array.
:type V: :class:`numpy.ndarray`
:returns: A cone-beam projection geometry.

``create_proj_geom('parallel3d_vec', det_row_count, det_col_count, V)``:

:param det_row_count: Number of detector pixel rows.
:type det_row_count: :class:`int`
:param det_col_count: Number of detector pixel columns.
:type det_col_count: :class:`int`
:param V: Vector array.
:type V: :class:`numpy.ndarray`
:returns: A parallel projection geometry.

``create_proj_geom('sparse_matrix', det_width, det_count, angles, matrix_id)``:

:param det_width: Size of a detector pixel.
:type det_width: :class:`float`
:param det_count: Number of detector pixels.
:type det_count: :class:`int`
:param angles: Array of angles in radians.
:type angles: :class:`numpy.ndarray`
:param matrix_id: ID of the sparse matrix.
:type matrix_id: :class:`int`
:returns: A projection geometry based on a sparse matrix.

"""
    if intype == 'parallel':
        if len(args) < 3:
            raise Exception(
                'not enough variables: astra_create_proj_geom(parallel, detector_spacing, det_count, angles)'
                )
        return {'type': 'parallel', 'DetectorWidth': args[0],
            'DetectorCount': args[1], 'ProjectionAngles': args[2]}
    elif intype == 'fanflat':
        if len(args) < 5:
            raise Exception(
                'not enough variables: astra_create_proj_geom(fanflat, det_width, det_count, angles, source_origin, origin_det)'
                )
        return {'type': 'fanflat', 'DetectorWidth': args[0],
            'DetectorCount': args[1], 'ProjectionAngles': args[2],
            'DistanceOriginSource': args[3], 'DistanceOriginDetector': args[4]}
    elif intype == 'fanflat_vec':
        if len(args) < 2:
            raise Exception(
                'not enough variables: astra_create_proj_geom(fanflat_vec, det_count, V)'
                )
        if not args[1].shape[1] == 6:
            raise Exception(
                'V should be a Nx6 matrix, with N the number of projections')
        return {'type': 'fanflat_vec', 'DetectorCount': args[0], 'Vectors':
            args[1]}
    elif intype == 'parallel3d':
        if len(args) < 5:
            raise Exception(
                'not enough variables: astra_create_proj_geom(parallel3d, detector_spacing_x, detector_spacing_y, det_row_count, det_col_count, angles)'
                )
        return {'type': 'parallel3d', 'DetectorSpacingX': args[0],
            'DetectorSpacingY': args[1], 'DetectorRowCount': args[2],
            'DetectorColCount': args[3], 'ProjectionAngles': args[4]}
    elif intype == 'cone':
        if len(args) < 7:
            raise Exception(
                'not enough variables: astra_create_proj_geom(cone, detector_spacing_x, detector_spacing_y, det_row_count, det_col_count, angles, source_origin, origin_det)'
                )
        return {'type': 'cone', 'DetectorSpacingX': args[0],
            'DetectorSpacingY': args[1], 'DetectorRowCount': args[2],
            'DetectorColCount': args[3], 'ProjectionAngles': args[4],
            'DistanceOriginSource': args[5], 'DistanceOriginDetector': args[6]}
    elif intype == 'cone_vec':
        if len(args) < 3:
            raise Exception(
                'not enough variables: astra_create_proj_geom(cone_vec, det_row_count, det_col_count, V)'
                )
        if not args[2].shape[1] == 12:
            raise Exception(
                'V should be a Nx12 matrix, with N the number of projections')
        return {'type': 'cone_vec', 'DetectorRowCount': args[0],
            'DetectorColCount': args[1], 'Vectors': args[2]}
    elif intype == 'parallel3d_vec':
        if len(args) < 3:
            raise Exception(
                'not enough variables: astra_create_proj_geom(parallel3d_vec, det_row_count, det_col_count, V)'
                )
        if not args[2].shape[1] == 12:
            raise Exception(
                'V should be a Nx12 matrix, with N the number of projections')
        return {'type': 'parallel3d_vec', 'DetectorRowCount': args[0],
            'DetectorColCount': args[1], 'Vectors': args[2]}
    elif intype == 'sparse_matrix':
        if len(args) < 4:
            raise Exception(
                'not enough variables: astra_create_proj_geom(sparse_matrix, det_width, det_count, angles, matrix_id)'
                )
        return {'type': 'sparse_matrix', 'DetectorWidth': args[0],
            'DetectorCount': args[1], 'ProjectionAngles': args[2],
            'MatrixID': args[3]}
    else:
        raise Exception('Error: unknown type ' + intype)


def _is_final(novel, part):
    """
    Tells if the part is the last one of the volume it belongs to
    """
    if part.volume != novel.volumes[-1]:
        return part == part.volume.parts[-1]
    total_pn_in_volume = part.volume.raw_volume.totalPartNumber
    if total_pn_in_volume:
        return part.num_in_volume == total_pn_in_volume
    else:
        return False


@classmethod
def set_current_date(cls, date):
    """set current simulation date
        :param date: string date, "2016-01-04"
        """
    cls.get_active()._set_current_date(date)


def a2q(name):
    """Inverse of `q2a`."""
    return name.replace('_', '-')


@classmethod
def from_api_data(cls, data):
    """Creates a new Content object from API data from ticketswitch.

        Args:
            data (dict): the part of the response from a ticketswitch API call
                that concerns some content..

        Returns:
            :class:`Content <pyticketswitch.content.Content>`: a new
            :class:`Content <pyticketswitch.content.Content>` object
            populated with the data from the api.

        """
    kwargs = {'name': data.get('name'), 'value': data.get('value'),
        'value_html': data.get('value_html')}
    return cls(**kwargs)


def primitive_nurbs_surface_cylinder_add(radius: float=1.0, view_align:
    bool=False, enter_editmode: bool=False, location: float=(0.0, 0.0, 0.0),
    rotation: float=(0.0, 0.0, 0.0), layers: bool=(False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False)):
    """Construct a Nurbs surface Cylinder

    :param radius: Radius
    :type radius: float
    :param view_align: Align to View, Align the new object to the view
    :type view_align: bool
    :param enter_editmode: Enter Editmode, Enter editmode when adding this object
    :type enter_editmode: bool
    :param location: Location, Location for the newly added object
    :type location: float
    :param rotation: Rotation, Rotation for the newly added object
    :type rotation: float
    :param layers: Layer
    :type layers: bool
    """
    pass


def wrap_string(s, max_len, delimiter='.', wrap='[...]', mode='end'):
    """Wrap a string into a given length

    Args:
        s (str): input string
        max_len (int): maximum string length
        delimiter (str, optional): character used for delimiting information categories
        wrap (str, optional): wrapping sequence used
        mode (str, optional): wrapping mode
    Returns:
        str: wrapped string
    """
    if len(s) <= max_len or mode is None:
        return s
    if mode == 'end':
        return s[:max_len - len(wrap)] + wrap
    elif mode == 'mid':
        final_part = s.rpartition(delimiter)[-1]
        wrapped_end = f'{wrap}.{final_part}'
        return s[:max_len - len(wrapped_end)] + wrapped_end
    else:
        raise ValueError('received an unexpected value of argument `mode`')


def _subsequence(s, c):
    """
    Takes as parameter list like object s and returns the length of the longest
    subsequence of s constituted only by consecutive character 'c's.
    Example: If the string passed as parameter is "001000111100", and c is '0',
    then the longest subsequence of only '0's has length 3.
    """
    bit = 0
    count = 0
    maxlen = 0
    for i in range(len(s)):
        bit = s[i]
        if bit == c:
            count = count + 1
            if count > maxlen:
                maxlen = count
        else:
            count = 0
    return maxlen


def calculate_co2_emissions(fuel_consumptions, fuel_carbon_content):
    """
    Calculates instantaneous CO2 emission vector [CO2g/s].

    :param fuel_consumptions:
        The instantaneous fuel consumption vector [g/s].
    :type fuel_consumptions: numpy.array

    :param fuel_carbon_content:
        Fuel carbon content [CO2g/g].
    :type fuel_carbon_content: float

    :return:
        CO2 instantaneous emissions vector [CO2g/s].
    :rtype: numpy.array
    """
    return fuel_consumptions * fuel_carbon_content


def isiterable(x):
    """Determine if object is iterable."""
    return isinstance(x, (list, tuple))


def twos_comp(val, bits):
    """
    Compute the 2's complement of int value val.

    :param val: Bytes to complement
    :param bits:
    :return: 2's complement of int value val
    """
    if val & 1 << bits - 1 != 0:
        val = val - (1 << bits)
    return val


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


def get(key):
    """Returns the current user credentials for the feature

        the value returned should be checked agains PERM_* flags.
        """


def get_permission_groups(username):
    """Return a list of names of the groups that the user with the
        specified name is a member of.
        """


def _check_mem(handle, bool_return=False):
    """Checks for 'memory block' bytes (Private)."""
    if handle.read(1) == b'*':
        return True
    elif not bool_return:
        raise ValueError('Expected LIF memory byte at ' + str(handle.tell()))
    else:
        return False


def map_obj_to_commands(want, have, module):
    """ Define ovs-vsctl command to meet desired state """
    commands = list()
    if module.params['state'] == 'absent':
        if 'key' in have.keys():
            templatized_command = (
                '%(ovs-vsctl)s -t %(timeout)s remove %(table)s %(record)s %(col)s %(key)s=%(value)s'
                )
            commands.append(templatized_command % module.params)
        elif module.params['key'] is None:
            templatized_command = (
                '%(ovs-vsctl)s -t %(timeout)s remove %(table)s %(record)s %(col)s'
                )
            commands.append(templatized_command % module.params)
    else:
        if want == have:
            return commands
        if module.params['key'] is None:
            templatized_command = (
                '%(ovs-vsctl)s -t %(timeout)s set %(table)s %(record)s %(col)s=%(value)s'
                )
            commands.append(templatized_command % module.params)
        else:
            templatized_command = (
                '%(ovs-vsctl)s -t %(timeout)s set %(table)s %(record)s %(col)s:%(key)s=%(value)s'
                )
            commands.append(templatized_command % module.params)
    return commands


def key_by_val(dictionary: dict, value: any) ->any:
    """
    A helper function for getting a key from a dictionary corresponding to a certain value.
    Does not check for value unicity.

    Args:
        dictionary (dict): The dictionary.
        value: The value.

    Returns:
        The key.

    Raises:
        ValueError: If the value could not be found in the dictionary.
    """
    for key, val in dictionary.items():
        if val == value:
            return key
    raise ValueError(
        f'Could not find value {value} in the dictionary\n{dictionary}')


def family_clone(dst, src):
    """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L66

    Positional arguments:
    dst -- nl_object class instance.
    src -- nl_object class instance.

    Returns:
    Integer.
    """
    raise NotImplementedError


def select_less():
    """Deselect keyframes on ends of selection islands

    """
    pass


def clean_dict(source, keys=[], values=[]):
    """Removes given keys and values from dictionary.

    :param dict source:
    :param iterable keys:
    :param iterable values:
    :return dict:
    """
    dict_data = {}
    for key, value in source.items():
        if key not in keys and value not in values:
            dict_data[key] = value
    return dict_data