def Func(arg_0, arg_1, arg_2):
        """
        Add a new order to a store.

        :param store_id: The store id.
        :type store_id: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "id": string*,
            "customer": object*
            {
                "'id": string*
            },
            "curency_code": string*,
            "order_total": number*,
            "lines": array*
            [
                {
                    "id": string*,
                    "product_id": string*,
                    "product_variant_id": string*,
                    "quantity": integer*,
                    "price": number*
                }
            ]
        }
        """
        arg_0.store_id = arg_1
        if 'id' not in arg_2:
            raise KeyError('The order must have an id')
        if 'customer' not in arg_2:
            raise KeyError('The order must have a customer')
        if 'id' not in arg_2['customer']:
            raise KeyError('The order customer must have an id')
        if 'currency_code' not in arg_2:
            raise KeyError('The order must have a currency_code')
        if not re.match(r"^[A-Z]{3}$", arg_2['currency_code']):
            raise ValueError('The currency_code must be a valid 3-letter ISO 4217 currency code')
        if 'order_total' not in arg_2:
            raise KeyError('The order must have an order_total')
        if 'lines' not in arg_2:
            raise KeyError('The order must have at least one order line')
        for arg_3 in arg_2['lines']:
            if 'id' not in arg_3:
                raise KeyError('Each order line must have an id')
            if 'product_id' not in arg_3:
                raise KeyError('Each order line must have a product_id')
            if 'product_variant_id' not in arg_3:
                raise KeyError('Each order line must have a product_variant_id')
            if 'quantity' not in arg_3:
                raise KeyError('Each order line must have a quantity')
            if 'price' not in arg_3:
                raise KeyError('Each order line must have a price')
        arg_4 = arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'orders'), arg_2=arg_2)
        if arg_4 is not None:
            arg_0.order_id = arg_4['id']
        else:
            arg_0.order_id = None
        return arg_4


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Update tags for a specific subscriber.

        The documentation lists only the tags request body parameter so it is
        being documented and error-checked as if it were required based on the
        description of the method.

        The data list needs to include a "status" key. This determines if the
        tag should be added or removed from the user:

        data = {
            'tags': [
                {'name': 'foo', 'status': 'active'},
                {'name': 'bar', 'status': 'inactive'}
            ]
        }

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param subscriber_hash: The MD5 hash of the lowercase version of the
          list member’s email address.
        :type subscriber_hash: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "tags": list*
        }
        """
        arg_2 = check_subscriber_hash(arg_2)
        arg_0.list_id = arg_1
        arg_0.subscriber_hash = arg_2
        if 'tags' not in arg_3:
            raise KeyError('The list member tags must have a tag')
        arg_4 = arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'members', arg_2, 'tags'), arg_3=arg_3)
        return arg_4


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Update a specific segment in a list.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param segment_id: The unique id for the segment.
        :type segment_id: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "name": string*
        }
        """
        arg_0.list_id = arg_1
        arg_0.segment_id = arg_2
        if 'name' not in arg_3:
            raise KeyError('The list segment must have a name')
        return arg_0._mc_client._patch(url=arg_0._build_path(arg_1, 'segments', arg_2), arg_3=arg_3)


def Func(arg_0, arg_1, arg_2):
        """
        Update a specific folder used to organize templates.

        :param folder_id: The unique id for the File Manager folder.
        :type folder_id: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "name": string*
        }
        """
        if 'name' not in arg_2:
            raise KeyError('The template folder must have a name')
        arg_0.folder_id = arg_1
        return arg_0._mc_client._patch(url=arg_0._build_path(arg_1), arg_2=arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Add a new member to the list.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "status": string*, (Must be one of 'subscribed', 'unsubscribed', 'cleaned',
                'pending', or 'transactional')
            "email_address": string*
        }
        """
        arg_0.list_id = arg_1
        if 'status' not in arg_2:
            raise KeyError('The list member must have a status')
        if arg_2['status'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:
            raise ValueError('The list member status must be one of "subscribed", "unsubscribed", "cleaned", '
                             '"pending", or "transactional"')
        if 'email_address' not in arg_2:
            raise KeyError('The list member must have an email_address')
        check_email(arg_2['email_address'])
        arg_3 = arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'members'), arg_2=arg_2)
        if arg_3 is not None:
            arg_0.subscriber_hash = arg_3['id']
        else:
            arg_0.subscriber_hash = None
        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Update information for a specific list member.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param subscriber_hash: The MD5 hash of the lowercase version of the
            list member’s email address.
        :type subscriber_hash: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        """
        arg_2 = check_subscriber_hash(arg_2)
        arg_0.list_id = arg_1
        arg_0.subscriber_hash = arg_2
        return arg_0._mc_client._patch(url=arg_0._build_path(arg_1, 'members', arg_2), arg_3=arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Add or update a list member.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param subscriber_hash: The MD5 hash of the lowercase version of the
            list member’s email address.
        :type subscriber_hash: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "email_address": string*,
            "status_if_new": string* (Must be one of 'subscribed',
                'unsubscribed', 'cleaned', 'pending', or 'transactional')
        }
        """
        arg_2 = check_subscriber_hash(arg_2)
        arg_0.list_id = arg_1
        arg_0.subscriber_hash = arg_2
        if 'email_address' not in arg_3:
            raise KeyError('The list member must have an email_address')
        check_email(arg_3['email_address'])
        if 'status_if_new' not in arg_3:
            raise KeyError('The list member must have a status_if_new')
        if arg_3['status_if_new'] not in ['subscribed', 'unsubscribed', 'cleaned', 'pending', 'transactional']:
            raise ValueError('The list member status_if_new must be one of "subscribed", "unsubscribed", "cleaned", '
                             '"pending", or "transactional"')
        return arg_0._mc_client._put(url=arg_0._build_path(arg_1, 'members', arg_2), arg_3=arg_3)


def Func(arg_0, arg_1, arg_2):
        """
        Delete a member from a list.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param subscriber_hash: The MD5 hash of the lowercase version of the
          list member’s email address.
        :type subscriber_hash: :py:class:`str`
        """
        arg_2 = check_subscriber_hash(arg_2)
        arg_0.list_id = arg_1
        arg_0.subscriber_hash = arg_2
        return arg_0._mc_client._Func(url=arg_0._build_path(arg_1, 'members', arg_2))


def Func(arg_0, arg_1, arg_2):
        """
        Delete permanently a member from a list.

        :param list_id: The unique id for the list.
        :type list_id: :py:class:`str`
        :param subscriber_hash: The MD5 hash of the lowercase version of the
          list member’s email address.
        :type subscriber_hash: :py:class:`str`
        """
        arg_2 = check_subscriber_hash(arg_2)
        arg_0.list_id = arg_1
        arg_0.subscriber_hash = arg_2
        return arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'members', arg_2, 'actions', 'delete-permanent'))


def Func(arg_0, arg_1, arg_2):
        """
        Pause an automated email.

        :param workflow_id: The unique id for the Automation workflow.
        :type workflow_id: :py:class:`str`
        :param email_id: The unique id for the Automation workflow email.
        :type email_id: :py:class:`str`
        """
        arg_0.workflow_id = arg_1
        arg_0.email_id = arg_2
        return arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'emails', arg_2, 'actions/Func'))


def Func(arg_0, arg_1, arg_2):
        """
        Start an automated email.

        :param workflow_id: The unique id for the Automation workflow.
        :type workflow_id: :py:class:`str`
        :param email_id: The unique id for the Automation workflow email.
        :type email_id: :py:class:`str`
        """
        arg_0.workflow_id = arg_1
        arg_0.email_id = arg_2
        return arg_0._mc_client._post(url=arg_0._build_path(arg_1, 'emails', arg_2, 'actions/Func'))


def Func(arg_0, arg_1, arg_2):
        """
        Removes an individual Automation workflow email.

        :param workflow_id: The unique id for the Automation workflow.
        :type workflow_id: :py:class:`str`
        :param email_id: The unique id for the Automation workflow email.
        :type email_id: :py:class:`str`
        """

        arg_0.workflow_id = arg_1
        arg_0.email_id = arg_2
        return arg_0._mc_client._Func(url=arg_0._build_path(arg_1, 'emails', arg_2))


def Func(arg_0, arg_1):
        """
        Create a new MailChimp campaign.

        The ValueError raised by an invalid type in data does not mention
        'absplit' as a potential value because the documentation indicates
        that the absplit type has been deprecated.

        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "recipients": object*
            {
                "list_id": string*
            },
            "settings": object*
            {
                "subject_line": string*,
                "from_name": string*,
                "reply_to": string*
            },
            "variate_settings": object* (Required if type is "variate")
            {
                "winner_criteria": string* (Must be one of "opens", "clicks", "total_revenue", or "manual")
            },
            "rss_opts": object* (Required if type is "rss")
            {
                "feed_url": string*,
                "frequency": string* (Must be one of "daily", "weekly", or "monthly")
            },
            "type": string* (Must be one of "regular", "plaintext", "rss", "variate", or "absplit")
        }
        """
        if 'recipients' not in arg_1:
            raise KeyError('The campaign must have recipients')
        if 'list_id' not in arg_1['recipients']:
            raise KeyError('The campaign recipients must have a list_id')
        if 'settings' not in arg_1:
            raise KeyError('The campaign must have settings')
        if 'subject_line' not in arg_1['settings']:
            raise KeyError('The campaign settings must have a subject_line')
        if 'from_name' not in arg_1['settings']:
            raise KeyError('The campaign settings must have a from_name')
        if 'reply_to' not in arg_1['settings']:
            raise KeyError('The campaign settings must have a reply_to')
        check_email(arg_1['settings']['reply_to'])
        if 'type' not in arg_1:
            raise KeyError('The campaign must have a type')
        if not arg_1['type'] in ['regular', 'plaintext', 'rss', 'variate', 'abspilt']:
            raise ValueError('The campaign type must be one of "regular", "plaintext", "rss", or "variate"')
        if arg_1['type'] == 'variate':
            if 'variate_settings' not in arg_1:
                raise KeyError('The variate campaign must have variate_settings')
            if 'winner_criteria' not in arg_1['variate_settings']:
                raise KeyError('The campaign variate_settings must have a winner_criteria')
            if arg_1['variate_settings']['winner_criteria'] not in ['opens', 'clicks', 'total_revenue', 'manual']:
                raise ValueError('The campaign variate_settings '
                                 'winner_criteria must be one of "opens", "clicks", "total_revenue", or "manual"')
        if arg_1['type'] == 'rss':
            if 'rss_opts' not in arg_1:
                raise KeyError('The rss campaign must have rss_opts')
            if 'feed_url' not in arg_1['rss_opts']:
                raise KeyError('The campaign rss_opts must have a feed_url')
            if not arg_1['rss_opts']['frequency'] in ['daily', 'weekly', 'monthly']:
                raise ValueError('The rss_opts frequency must be one of "daily", "weekly", or "monthly"')
        arg_2 = arg_0._mc_client._post(url=arg_0._build_path(), arg_1=arg_1)
        if arg_2 is not None:
            arg_0.campaign_id = arg_2['id']
        else:
            arg_0.campaign_id = None
        return arg_2


def Func(arg_0, arg_1, arg_2):
        """
        Update some or all of the settings for a specific campaign.

        :param campaign_id: The unique id for the campaign.
        :type campaign_id: :py:class:`str`
        :param data: The request body parameters
        :type data: :py:class:`dict`
        data = {
            "settings": object*
            {
                "subject_line": string*,
                "from_name": string*,
                "reply_to": string*
            },
        }
        """
        arg_0.campaign_id = arg_1
        if 'settings' not in arg_2:
            raise KeyError('The campaign must have settings')
        if 'subject_line' not in arg_2['settings']:
            raise KeyError('The campaign settings must have a subject_line')
        if 'from_name' not in arg_2['settings']:
            raise KeyError('The campaign settings must have a from_name')
        if 'reply_to' not in arg_2['settings']:
            raise KeyError('The campaign settings must have a reply_to')
        check_email(arg_2['settings']['reply_to'])
        return arg_0._mc_client._patch(url=arg_0._build_path(arg_1), arg_2=arg_2)


def Func(arg_0, arg_1):
        """
        Remove a campaign from your MailChimp account.

        :param campaign_id: The unique id for the campaign.
        :type campaign_id: :py:class:`str`
        """
        arg_0.campaign_id = arg_1
        return arg_0._mc_client._Func(url=arg_0._build_path(arg_1))


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Delete a cart.

        :param store_id: The store id.
        :type store_id: :py:class:`str`
        :param cart_id: The id for the cart.
        :type cart_id: :py:class:`str`
        :param line_id: The id for the line item of a cart.
        :type line_id: :py:class:`str`
        """
        arg_0.store_id = arg_1
        arg_0.cart_id = arg_2
        arg_0.line_id = arg_3
        return arg_0._mc_client._Func(url=arg_0._build_path(arg_1, 'carts', arg_2, 'lines', arg_3))


def Func(arg_0, arg_1=False, **arg_2):
        """
        Get a summary of batch requests that have been made.

        :param get_Func: Should the query get Func results
        :type get_Func: :py:class:`bool`
        :param queryparams: The query string parameters
        queryparams['fields'] = []
        queryparams['exclude_fields'] = []
        queryparams['count'] = integer
        queryparams['offset'] = integer
        """
        arg_0.batch_id = None
        arg_0.operation_status = None
        if arg_1:
            return arg_0._iterate(url=arg_0._build_path(), **arg_2)
        else:
            return arg_0._mc_client._get(url=arg_0._build_path(), **arg_2)


def Func(arg_0, arg_1, **arg_2):
        """
        Get the status of a batch request.

        :param batch_id: The unique id for the batch operation.
        :type batch_id: :py:class:`str`
        :param queryparams: The query string parameters
        queryparams['fields'] = []
        queryparams['exclude_fields'] = []
        """
        arg_0.batch_id = arg_1
        arg_0.operation_status = None
        return arg_0._mc_client._Func(url=arg_0._build_path(arg_1), **arg_2)


def Func(arg_0):
    """
    Policies returned from boto3 are massive, ugly, and difficult to read.
    This method flattens and reformats the policy.

    :param policy: Result from invoking describe_load_balancer_policies(...)
    :return: Returns a tuple containing policy_name and the reformatted policy dict.
    """
    arg_1 = arg_0['PolicyName']
    arg_2 = {}
    arg_2['type'] = arg_0['PolicyTypeName']
    arg_3 = arg_0['PolicyAttributeDescriptions']

    if arg_2['type'] != 'SSLNegotiationPolicyType':
        return arg_1, arg_2

    arg_4 = dict()
    for arg_5 in arg_3:
        arg_4[arg_5['AttributeName']] = arg_5['AttributeValue']

    arg_2['protocols'] = dict()
    arg_2['protocols']['sslv2'] = bool(arg_4.get('Protocol-SSLv2'))
    arg_2['protocols']['sslv3'] = bool(arg_4.get('Protocol-SSLv3'))
    arg_2['protocols']['tlsv1'] = bool(arg_4.get('Protocol-TLSv1'))
    arg_2['protocols']['tlsv1_1'] = bool(arg_4.get('Protocol-TLSv1.1'))
    arg_2['protocols']['tlsv1_2'] = bool(arg_4.get('Protocol-TLSv1.2'))
    arg_2['server_defined_cipher_order'] = bool(arg_4.get('Server-Defined-Cipher-Order'))
    arg_2['reference_security_policy'] = arg_4.get('Reference-Security-Policy', None)

    arg_6 = [
        'Server-Defined-Cipher-Order',
        'Protocol-SSLv2',
        'Protocol-SSLv3',
        'Protocol-TLSv1',
        'Protocol-TLSv1.1',
        'Protocol-TLSv1.2',
        'Reference-Security-Policy'
    ]

    arg_7 = []
    for arg_8 in arg_4:
        if arg_4[arg_8] == 'true' and arg_8 not in arg_6:
            arg_7.append(arg_8)

    arg_7.sort()
    arg_2['supported_ciphers'] = arg_7

    return arg_1, arg_2


def Func(arg_0, arg_1, arg_2=True):
        """
        Retrieve key from Cache.

        :param key: key to look up in cache.
        :type key: ``object``

        :param delete_if_expired: remove value from cache if it is expired.
                                  Default is True.
        :type delete_if_expired: ``bool``

        :returns: value from cache or None
        :rtype: varies or None
        """
        arg_0._update_cache_stats(arg_1, None)

        if arg_1 in arg_0._CACHE:
            (arg_3, arg_4) = arg_0._CACHE[arg_1]
            if arg_3 > arg_0._now():
                arg_0._update_cache_stats(arg_1, 'hit')
                return arg_4
            else:
                if arg_2:
                    arg_0.delete(arg_1)
                    arg_0._update_cache_stats(arg_1, 'expired')
                    return None

        arg_0._update_cache_stats(arg_1, 'miss')
        return None


def Func(arg_0, arg_1=None):
        """Get access details in cache."""
        if arg_1 in arg_0._CACHE_STATS:
            return arg_0._CACHE_STATS['access_stats'][arg_1]
        else:
            return arg_0._CACHE_STATS['access_stats']


def Func(arg_0, **arg_1):
    """Gets the VPC Flow Logs for a VPC"""
    arg_2 = describe_flow_logs(Filters=[{"Name": "resource-id", "Values": [arg_0["id"]]}], **arg_1)

    arg_3 = []
    for arg_4 in arg_2:
        arg_3.append(arg_4["FlowLogId"])

    return arg_3


def Func(arg_0, **arg_1):
    """Gets the Classic Link details about a VPC"""
    arg_2 = {}

    try:
        arg_3 = describe_vpc_classic_link(VpcIds=[arg_0["id"]], **arg_1)[0]
        arg_2["Enabled"] = arg_3["ClassicLinkEnabled"]

        # Check for DNS as well:
        arg_4 = describe_vpc_classic_link_dns_support(VpcIds=[arg_0["id"]], **arg_1)[0]
        arg_2["DnsEnabled"] = arg_4["ClassicLinkDnsSupported"]
    except ClientError as e:
        # This is not supported for all regions.
        if 'UnsupportedOperation' not in str(e):
            raise e

    return arg_2


def Func(arg_0, **arg_1):
    """Gets the VPC Route Tables"""
    arg_2 = describe_route_tables(Filters=[{"Name": "vpc-id", "Values": [arg_0["id"]]}], **arg_1)

    arg_3 = []
    for arg_4 in arg_2:
        arg_3.append(arg_4["RouteTableId"])

    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None,
                arg_5=None):
    """
    Private GCP client builder.

    :param project: Google Cloud project string.
    :type project: ``str``

    :param mod_name: Module name to load.  Should be found in sys.path.
    :type mod_name: ``str``

    :param pkg_name: package name that mod_name is part of.  Default is 'google.cloud' .
    :type pkg_name: ``str``

    :param key_file: Default is None.
    :type key_file: ``str`` or None

    :param http_auth: httplib2 authorized client. Default is None.
    :type http_auth: :class: `HTTPLib2`

    :param user_agent: User Agent string to use in requests. Default is None.
    :type http_auth: ``str`` or None

    :return: GCP client
    :rtype: ``object``
    """
    arg_6 = None
    if arg_4 is None:
        arg_4 = _googleauth(arg_3=arg_3, arg_5=arg_5)
    try:
        # Using a relative path, so we prefix with a dot (.)
        arg_7 = importlib.import_module('.' + arg_1,
                                                package=arg_2)
        arg_6 = arg_7.Client(use_GAX=USE_GAX, arg_0=arg_0,
                                      http=arg_4)
    except ImportError as ie:
        arg_8 = 'Unable to import %s.%s' % (arg_2, arg_1)
        raise ImportError(arg_8)
    except TypeError:
        # Not all clients use gRPC
        arg_6 = arg_7.Client(arg_0=arg_0, http=arg_4)
    if arg_5 and hasattr(arg_6, 'user_agent'):
        arg_6.user_agent = arg_5
    return arg_6


def Func(arg_0=None, arg_1=[], arg_2=None):
    """
    Google http_auth helper.

    If key_file is not specified, default credentials will be used.

    If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES

    :param key_file: path to key file to use. Default is None
    :type key_file: ``str``

    :param scopes: scopes to set.  Default is DEFAUL_SCOPES
    :type scopes: ``list``

    :param user_agent: User Agent string to use in requests. Default is None.
    :type http_auth: ``str`` or None

    :return: HTTPLib2 authorized client.
    :rtype: :class: `HTTPLib2`
    """
    if arg_0:
        if not arg_1:
            arg_1 = DEFAULT_SCOPES
        arg_3 = ServiceAccountCredentials.from_json_keyfile_name(arg_0,
                                                                 arg_1=arg_1)
    else:
        arg_3 = GoogleCredentials.get_application_default()
    arg_4 = Http()
    if arg_2:
        arg_4 = set_user_agent(arg_4, arg_2)
    arg_5 = arg_3.authorize(arg_4)
    return arg_5


def Func(arg_0, arg_1, arg_2):
    """
    Google build client helper.

    :param service: service to build client for
    :type service: ``str``

    :param api_version: API version to use.
    :type api_version: ``str``

    :param http_auth: Initialized HTTP client to use.
    :type http_auth: ``object``

    :return: google-python-api client initialized to use 'service'
    :rtype: ``object``
    """
    arg_3 = build(arg_0, arg_1, http=arg_2)
    return arg_3


def Func(arg_0, arg_1=None):
    """
    Call decorated function for each item in project list.

    Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions.

    If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively.
    If item in list is of type string_types, we assume it is the project string. Default credentials
    will be used by the underlying client library.

    :param projects: list of project strings or list of dictionaries
                     Example: {'project':..., 'keyfile':...}. Required.
    :type projects: ``list`` of ``str`` or ``list`` of ``dict``

    :param key_file: path on disk to keyfile, for use with all projects
    :type key_file: ``str``

    :returns: tuple containing a list of function output and an exceptions map
    :rtype: ``tuple of ``list``, ``dict``
    """

    def decorator(arg_2):
        @wraps(arg_2)
        def decorated_function(*arg_3, **arg_4):
            arg_5 = []
            arg_6 = {}
            for arg_7 in arg_0:
                if isinstance(arg_7, string_types):
                    arg_4['project'] = arg_7
                    if arg_1:
                        arg_4['key_file'] = arg_1
                elif isinstance(arg_7, dict):
                    arg_4['project'] = arg_7['project']
                    arg_4['key_file'] = arg_7['key_file']
                arg_8, arg_9 = arg_2(*arg_3, **arg_4)
                arg_5.extend(arg_8)
                arg_6.update(arg_9)
            return (arg_5, arg_6)

        return decorated_function

    return decorator


def Func(arg_0):
    """Helper to get creds out of kwargs."""
    arg_1 = {
        'key_file': arg_0.pop('key_file', None),
        'http_auth': arg_0.pop('http_auth', None),
        'project': arg_0.get('project', None),
        'user_agent': arg_0.pop('user_agent', None),
        'api_version': arg_0.pop('api_version', 'v1')
    }
    return (arg_1, arg_0)


def Func(arg_0, arg_1, arg_2=None):
    """
    Manipulate connection keywords.

    Modifieds keywords based on connection type.

    There is an assumption here that the client has
    already been created and that these keywords are being
    passed into methods for interacting with various services.

    Current modifications:
    - if conn_type is not cloud and module is 'compute',
      then rewrite project as name.
    - if conn_type is cloud and module is 'storage',
      then remove 'project' from dict.

    :param conn_type: E.g. 'cloud' or 'general'
    :type conn_type: ``str``

    :param kwargs: Dictionary of keywords sent in by user.
    :type kwargs: ``dict``

    :param module_name: Name of specific module that will be loaded.
                        Default is None.
    :type conn_type: ``str`` or None

    :returns kwargs with client and module specific changes
    :rtype: ``dict``
    """
    if arg_0 != 'cloud' and arg_2 != 'compute':
        if 'project' in arg_1:
            arg_1['name'] = 'projects/%s' % arg_1.pop('project')
    if arg_0 == 'cloud' and arg_2 == 'storage':
        if 'project' in arg_1:
            del arg_1['project']
    return arg_1


def Func(arg_0=None, arg_1='name', **arg_2):
    """General aggregated list function for the GCE service."""
    arg_3 = []
    arg_4 = arg_0.aggregatedList(**arg_2)

    while arg_4 is not None:
        arg_5 = arg_4.execute()
        for arg_6, arg_7 in arg_5['items'].items():
            if arg_1 in arg_7:
                arg_3.extend(arg_7[arg_1])

        arg_4 = arg_0.aggregatedList_next(previous_request=arg_4,
                                          previous_response=arg_5)
    return arg_3


def Func(arg_0=None, **arg_1):
    """General list function for the GCE service."""
    arg_2 = []
    arg_3 = arg_0.list(**arg_1)

    while arg_3 is not None:
        arg_4 = arg_3.execute()
        for arg_5 in arg_4.get('items', []):
            arg_2.append(arg_5)
        arg_3 = arg_0.list_next(previous_request=arg_3, previous_response=arg_4)
    return arg_2


def Func(arg_0=None, arg_1=None, **arg_2):
    """General list function for Google APIs."""
    arg_3 = []
    arg_4 = arg_0.list(**arg_2)

    while arg_4 is not None:
        arg_5 = arg_4.execute()
        if arg_1 and arg_1 in arg_5:
            arg_3.extend(arg_5[arg_1])
        else:
            arg_3.append(arg_5)
        # Not all list calls have a list_next
        if hasattr(arg_0, 'list_next'):
            arg_4 = arg_0.list_next(previous_request=arg_4,
                                    previous_response=arg_5)
        else:
            arg_4 = None
    return arg_3


def Func(arg_0=None):
    """Retrieve detailed cache information."""
    from cloudaux.gcp.decorators import _GCP_CACHE
    return _GCP_CACHE.get_access_details(arg_0=arg_0)


def Func(arg_0='cloudaux'):
    """
    Get default User Agent String.

    Try to import pkg_name to get an accurate version number.

    return: string
    """
    arg_1 = '0.0.1'
    try:
        import pkg_resources
        arg_1 = pkg_resources.get_distribution(arg_0).version
    except pkg_resources.DistributionNotFound:
        pass
    except ImportError:
        pass

    return 'cloudaux/%s' % (arg_1)


def Func(arg_0=None, **arg_1):
    """
    Rule='string'
    """
    arg_2 = arg_0.Func(**arg_1)
    if not arg_2.get("Targets"):
        arg_2.update({"Targets": []})

    return arg_2


def Func(**arg_0):
    """
    List objects in bucket.

    :param Bucket: name of bucket
    :type Bucket: ``str``

    :returns list of objects in bucket
    :rtype: ``list``
    """
    arg_1 = get_bucket(**arg_0)
    if arg_1:
        return [arg_2 for arg_2 in arg_1.list_blobs()]
    else:
        return None


def Func(arg_0, arg_1='camelized'):
    """
    Calls _Func and either passes the inflection.camelize method or the inflection.underscore method.

    :param item: dictionary representing item to be modified
    :param output: string 'camelized' or 'underscored'
    :return:
    """
    if arg_1 == 'camelized':
        return _Func(arg_0, camelize)
    elif arg_1 == 'underscored':
        return _Func(arg_0, underscore)


def Func(arg_0, arg_1=None, **arg_2):
    """Retrieve the currently active policy version document for every managed policy that is attached to the role."""
    arg_3 = get_role_managed_policies(arg_0, force_client=arg_1)

    arg_4 = (policy['name'] for policy in arg_3)
    arg_5 = (delayed(get_managed_policy_document)(policy['arn'], force_client=arg_1) for policy
                          in arg_3)
    arg_6 = Parallel(n_jobs=20, backend="threading")(arg_5)

    return dict(zip(arg_4, arg_6))


def Func(arg_0, **arg_1):
    """Fetch the base IAM Server Certificate."""
    arg_0['_version'] = 1

    # Get the initial cert details:
    arg_2 = get_server_certificate_api(arg_0['ServerCertificateName'], **arg_1)

    if arg_2:
        arg_0.update(arg_2['ServerCertificateMetadata'])
        arg_0['CertificateBody'] = arg_2['CertificateBody']
        arg_0['CertificateChain'] = arg_2.get('CertificateChain', None)

        # Cast dates from a datetime to something JSON serializable.
        arg_0['UploadDate'] = get_iso_string(arg_0['UploadDate'])
        arg_0['Expiration'] = get_iso_string(arg_0['Expiration'])

    return arg_0


def Func(arg_0, arg_1='client', arg_2=15, arg_3=None,
                      arg_4=None, arg_5='cloudaux', arg_6='us-east-1', arg_7=False,
                      arg_8=None, arg_9='aws'):
    """
    Used to obtain a boto3 client or resource connection.
    For cross account, provide both account_number and assume_role.

    :usage:

    # Same Account:
    client = Func('iam')
    resource = Func('iam', service_type='resource')

    # Cross Account Client:
    client = Func('iam', account_number='000000000000', assume_role='role_name')

    # Cross Account Resource:
    resource = Func('iam', service_type='resource', account_number='000000000000', assume_role='role_name')

    :param service: AWS service (i.e. 'iam', 'ec2', 'kms')
    :param service_type: 'client' or 'resource'
    :param future_expiration_minutes: Connections will expire from the cache
        when their expiration is within this many minutes of the present time. [Default 15]
    :param account_number: Required if assume_role is provided.
    :param assume_role:  Name of the role to assume into for account described by account_number.
    :param session_name: Session name to attach to requests. [Default 'cloudaux']
    :param region: Region name for connection. [Default us-east-1]
    :param return_credentials: Indicates if the STS credentials should be returned with the client [Default False]
    :param external_id: Optional external id to pass to sts:AssumeRole.
        See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
    :param arn_partition: Optional parameter to specify other aws partitions such as aws-us-gov for aws govcloud
    :return: boto3 client or resource connection
    """
    arg_10 = (
        arg_3,
        arg_4,
        arg_5,
        arg_8,
        arg_6,
        arg_1,
        arg_0,
        arg_9
    )

    if arg_10 in arg_17:
        arg_11 = _get_cached_creds(arg_10, arg_0, arg_1, arg_6, arg_2, arg_7)
        if arg_11:
            return arg_11

    arg_12 = None
    if arg_4:
        arg_13 = boto3.session.Session().client('sts')

        # prevent malformed ARN
        if not all([arg_3, arg_4]):
            raise ValueError("Account number and role to assume are both required")

        arg_14 = 'arn:{partition}:iam::{0}:role/{1}'.format(
            arg_3,
            arg_4,
            partition=arg_9
        )

        arg_15 = {
            'RoleArn': arg_14,
            'RoleSessionName': arg_5
        }

        if arg_8:
            arg_15['ExternalId'] = arg_8

        arg_12 = arg_13.assume_role(**arg_15)

    if arg_1 == 'client':
        arg_16 = _client(arg_0, arg_6, arg_12)
    elif arg_1 == 'resource':
        arg_16 = _resource(arg_0, arg_6, arg_12)

    if arg_12:
        arg_17[arg_10] = arg_12

    if arg_7:
        return arg_16, arg_12['Credentials']

    return arg_16


def Func(arg_0, arg_1=arg_2.ALL, **arg_4):
    arg_5 = registry.build_out(arg_1, start_with=arg_0,  pass_datastructure=True, **arg_4)
    """ just store the AWS formatted rules """
    arg_5.pop('security_group_rules', [])
    return arg_5


def Func(arg_0, **arg_1):
    """Get the inline policies for the group."""
    arg_2 = list_group_policies(arg_0['GroupName'])

    arg_3 = {}

    for arg_4 in arg_2:
        arg_3[arg_4] = get_group_policy_document(arg_0['GroupName'], arg_4, **arg_1)

    return arg_3


def Func(arg_0, **arg_1):
    """Get a list of the managed policy names that are attached to the group."""
    arg_2 = list_attached_group_managed_policies(arg_0['GroupName'], **arg_1)

    arg_3 = []

    for arg_4 in arg_2:
        arg_3.append(arg_4['PolicyName'])

    return arg_3


def Func(arg_0, **arg_1):
    """Gets a list of the usernames that are a part of this group."""
    arg_2 = get_group_api(arg_0['GroupName'], **arg_1)

    arg_3 = []
    for arg_4 in arg_2.get('Users', []):
        arg_3.append(arg_4['UserName'])

    return arg_3


def Func(arg_0, **arg_1):
    """Fetch the base IAM Group."""
    arg_0['_version'] = 1

    # Get the initial group details (only needed if we didn't grab the users):
    arg_0.update(get_group_api(arg_0['GroupName'], users=False, **arg_1)['Group'])

    # Cast CreateDate from a datetime to something JSON serializable.
    arg_0['CreateDate'] = get_iso_string(arg_0['CreateDate'])
    return arg_0


def Func(arg_0, arg_1=None, arg_2=None):
        '''
          Returns a list of stores in the catalog. If workspaces is specified will only return stores in those workspaces.
          If names is specified, will only return stores that match.
          names can either be a comma delimited string or an array.
          Will return an empty list if no stores are found.
        '''

        if isinstance(arg_2, Workspace):
            arg_2 = [arg_2]
        elif isinstance(arg_2, list) and [arg_3 for arg_3 in arg_2 if isinstance(arg_3, Workspace)]:
            # nothing
            pass
        else:
            arg_2 = arg_0.get_workspaces(arg_1=arg_2)

        arg_4 = []
        for arg_5 in arg_2:
            arg_6 = arg_0.get_xml(arg_5.datastore_url)
            arg_7 = arg_0.get_xml(arg_5.coveragestore_url)
            arg_8 = arg_0.get_xml(arg_5.wmsstore_url)
            arg_4.extend([datastore_from_index(arg_0, arg_5, arg_9) for arg_9 in arg_6.findall("dataStore")])
            arg_4.extend([coveragestore_from_index(arg_0, arg_5, arg_9) for arg_9 in arg_7.findall("coverageStore")])
            arg_4.extend([wmsstore_from_index(arg_0, arg_5, arg_9) for arg_9 in arg_8.findall("wmsStore")])

        if arg_1 is None:
            arg_1 = []
        elif isinstance(arg_1, basestring):
            arg_1 = [s.strip() for s in arg_1.split(',') if s.strip()]

        if arg_4 and arg_1:
            return ([arg_10 for arg_10 in arg_4 if arg_10.name in arg_1])

        return arg_4


def Func(arg_0, arg_1, arg_2=None):
        '''
          Returns a single store object.
          Will return None if no store is found.
          Will raise an error if more than one store with the same name is found.
        '''

        arg_3 = arg_0.Funcs(workspaces=arg_2, names=arg_1)
        return arg_0._return_first_item(arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None, arg_6=None):
        '''List granules of an imagemosaic'''
        arg_7 = dict()

        if arg_4 is not None:
            arg_7['filter'] = arg_4
        if arg_5 is not None:
            arg_7['limit'] = arg_5
        if arg_6 is not None:
            arg_7['offset'] = arg_6

        arg_8 = arg_3
        if isinstance(arg_2, basestring):
            arg_9 = arg_2
        else:
            arg_9 = arg_2.name
            arg_8 = arg_2.workspace.name

        if arg_8 is None:
            raise ValueError("Must specify workspace")

        arg_10 = build_url(
            arg_0.service_url,
            [
                "workspaces",
                arg_8,
                "coveragestores",
                arg_9,
                "coverages",
                arg_1,
                "index/granules.json"
            ],
            arg_7
        )

        # GET /workspaces/<ws>/coveragestores/<name>/coverages/<coverage>/index/granules.json
        arg_11 = {
            "Content-type": "application/json",
            "Accept": "application/json"
        }

        arg_12 = arg_0.http_request(arg_10, arg_11=arg_11)
        if arg_12.status_code != 200:
            FailedRequestError('Failed to list granules in mosaic {} : {}, {}'.format(arg_2, arg_12.status_code, arg_12.text))

        arg_0._cache.clear()
        return arg_12.json()


def Func(arg_0, arg_1):
        '''Returns all coverages in a coverage store'''
        arg_2 = dict()
        arg_3 = build_url(
            arg_0.service_url,
            [
                "workspaces",
                arg_1.workspace.name,
                "coveragestores",
                arg_1.name,
                "coverages.json"
            ],
            arg_2
        )
        # GET /workspaces/<ws>/coveragestores/<name>/coverages.json
        arg_4 = {
            "Content-type": "application/json",
            "Accept": "application/json"
        }

        arg_5 = arg_0.http_request(arg_3, arg_4=arg_4)
        if arg_5.status_code != 200:
            FailedRequestError('Failed to get mosaic coverages {} : {}, {}'.format(arg_1, arg_5.status_code, arg_5.text))

        arg_0._cache.clear()
        return arg_5.json()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None, arg_6=None):
        '''Publish a featuretype from data in an existing store'''
        # @todo native_srs doesn't seem to get detected, even when in the DB
        # metadata (at least for postgis in geometry_columns) and then there
        # will be a misconfigured layer
        if arg_3 is None:
            raise ValueError("must specify native_crs")

        arg_4 = arg_4 or arg_3
        arg_7 = FeatureType(arg_0, arg_2.workspace, arg_2, arg_1)
        # because name is the in FeatureType base class, work around that
        # and hack in these others that don't have xml properties
        arg_7.dirty['name'] = arg_1
        arg_7.dirty['srs'] = arg_4
        arg_7.dirty['nativeCRS'] = arg_3
        arg_7.enabled = True
        arg_7.advertised = True
        arg_7.title = arg_1

        if arg_6 is not None:
            arg_7.native_name = arg_6

        arg_12 = {
            "Content-type": "application/xml",
            "Accept": "application/xml"
        }

        arg_13 = arg_2.resource_url
        if arg_5 is not None:
            arg_7.metadata = ({'JDBC_VIRTUAL_TABLE': arg_5})
            arg_15 = dict()
            arg_13 = build_url(
                arg_0.service_url,
                [
                    "workspaces",
                    arg_2.workspace.name,
                    "datastores", arg_2.name,
                    "featuretypes.xml"
                ],
                arg_15
            )

        arg_16 = arg_0.http_request(arg_13, method='post', data=arg_7.message(), arg_12=arg_12)
        if arg_16.status_code not in (200, 201, 202):
            FailedRequestError('Failed to publish feature type {} : {}, {}'.format(arg_1, arg_16.status_code, arg_16.text))

        arg_0._cache.clear()
        arg_7.fetch()
        return arg_7


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
        '''
          returns a single resource object.
          Will return None if no resource is found.
          Will raise an error if more than one resource with the same name is found.
        '''

        arg_4 = arg_0.Funcs(names=arg_1, stores=arg_2, workspaces=arg_3)
        return arg_0._return_first_item(arg_4)


def Func(arg_0, arg_1, arg_2=None):
        '''
          returns a single layergroup object.
          Will return None if no layergroup is found.
          Will raise an error if more than one layergroup with the same name is found.
        '''

        arg_3 = arg_0.Funcs(names=arg_1, workspaces=arg_2)
        return arg_0._return_first_item(arg_3)


def Func(arg_0, arg_1, arg_2=None):
        '''
          returns a single style object.
          Will return None if no style is found.
          Will raise an error if more than one style with the same name is found.
        '''

        arg_3 = arg_0.Funcs(names=arg_1, workspaces=arg_2)
        return arg_0._return_first_item(arg_3)


def Func(arg_0, arg_1=None):
        '''
          Returns a list of workspaces in the catalog.
          If names is specified, will only return workspaces that match.
          names can either be a comma delimited string or an array.
          Will return an empty list if no workspaces are found.
        '''
        if arg_1 is None:
            arg_1 = []
        elif isinstance(arg_1, basestring):
            arg_1 = [s.strip() for s in arg_1.split(',') if s.strip()]

        arg_2 = arg_0.get_xml("{}/workspaces.xml".format(arg_0.service_url))
        arg_3 = []
        arg_3.extend([workspace_from_index(arg_0, arg_4) for arg_4 in arg_2.findall("workspace")])

        if arg_3 and arg_1:
            return ([arg_5 for arg_5 in arg_3 if arg_5.name in arg_1])

        return arg_3


def Func(arg_0, arg_1):
        '''
          returns a single workspace object.
          Will return None if no workspace is found.
          Will raise an error if more than one workspace with the same name is found.
        '''

        arg_2 = arg_0.Funcs(names=arg_1)
        return arg_0._return_first_item(arg_2)


def Func(arg_0):
    """Extract a metadata link tuple from an xml node"""
    arg_1 = arg_0.find("type")
    arg_2 = arg_0.find("metadataType")
    arg_3 = arg_0.find("content")
    if None in [arg_1, arg_2, arg_3]:
        return None
    else:
        return (arg_1.text, arg_2.text, arg_3.text)


def Func(arg_0, arg_1, arg_2=None):
    """
    Create a URL from a list of path segments and an optional dict of query
    parameters.
    """

    def clean_segment(arg_3):
        """
        Cleans the segment and encodes to UTF-8 if the segment is unicode.
        """
        arg_3 = arg_3.strip('/')
        if isinstance(arg_3, basestring):
            arg_3 = arg_3.encode('utf-8')
        return arg_3

    arg_1 = (quote(clean_segment(s)) for s in arg_1)
    if arg_2 is None or len(arg_2) == 0:
        arg_4 = ''
    else:
        arg_4 = "?" + urlencode(arg_2)
    arg_5 = '/'.join(arg_1) + arg_4
    arg_6 = arg_0.rstrip('/') + '/'
    return urljoin(str(arg_6), str(arg_5))


def Func(arg_0, arg_1):
    """GeoServer's REST API uses ZIP archives as containers for file formats such
    as Shapefile and WorldImage which include several 'boxcar' files alongside
    the main data.  In such archives, GeoServer assumes that all of the relevant
    files will have the same base name and appropriate extensions, and live in
    the root of the ZIP archive.  This method produces a zip file that matches
    these expectations, based on a basename, and a dict of extensions to paths or
    file-like objects. The client code is responsible for deleting the zip
    archive when it's done."""
    arg_2, arg_3 = mkstemp()
    arg_4 = ZipFile(arg_3, 'w')
    for arg_5, arg_6 in arg_1.items():
        arg_7 = "%s.%s" % (arg_0, arg_5)
        if (isinstance(arg_6, basestring)):
            arg_4.write(arg_6, arg_7)
        else:
            arg_4.writestr(arg_7, arg_6.read())
    arg_4.close()
    os.close(arg_2)
    return arg_3


def Func(arg_0, arg_1):
    """Extract metadata Dimension Info from an xml node"""
    def _get_value(arg_2):
        return getattr(arg_1.find(arg_2), 'text', None)

    arg_3 = _get_value('resolution')
    arg_4 = arg_1.find("defaultValue")
    arg_5 = arg_4.find("strategy") if arg_4 is not None else None
    arg_5 = arg_5.text if arg_5 is not None else None
    return DimensionInfo(
        arg_0,
        _get_value('enabled') == 'true',
        _get_value('presentation'),
        int(arg_3) if arg_3 else None,
        _get_value('units'),
        _get_value('unitSymbol'),
        arg_5,
        _get_value('attribute'),
        _get_value('endAttribute'),
        _get_value('referenceValue'),
        _get_value('nearestMatchEnabled')
    )


def Func(arg_0, arg_1):
    """Extract metadata Dynamic Default Values from an xml node"""
    arg_2 = arg_1.find("configurations")
    if arg_2 is not None:
        arg_2 = []
        for arg_3 in arg_1.findall("configuration"):
            arg_4 = arg_3.find("dimension")
            arg_4 = arg_4.text if arg_4 is not None else None
            arg_5 = arg_3.find("policy")
            arg_5 = arg_5.text if arg_5 is not None else None
            arg_6 = arg_3.find("defaultValueExpression")
            arg_6 = arg_6.text if arg_6 is not None else None

            arg_2.append(DynamicDefaultValuesConfiguration(arg_4, arg_5, arg_6))

    return DynamicDefaultValues(arg_0, arg_2)


def Func(arg_0, arg_1):
        """Change semantic of MOVE to change resource tags."""
        # path and destPath must be '/by_tag/<tag>/<resname>'
        if "/by_tag/" not in arg_0.path:
            raise DAVError(HTTP_FORBIDDEN)
        if "/by_tag/" not in arg_1:
            raise DAVError(HTTP_FORBIDDEN)
        arg_2, arg_3, arg_4 = util.save_split(arg_0.path.strip("/"), "/", 2)
        assert arg_2 == "by_tag"
        assert arg_3 in arg_0.data["tags"]
        arg_0.data["tags"].remove(arg_3)
        arg_2, arg_3, arg_4 = util.save_split(arg_1.strip("/"), "/", 2)
        assert arg_2 == "by_tag"
        if arg_3 not in arg_0.data["tags"]:
            arg_0.data["tags"].append(arg_3)
        return True


def Func(arg_0, arg_1, arg_2):
        """Return _VirtualResource object for path.

        path is expected to be
            categoryType/category/name/artifact
        for example:
            'by_tag/cool/My doc 2/info.html'

        See DAVProvider.Func()
        """
        _logger.info("Func('%s')" % arg_1)
        arg_0._count_Func += 1
        arg_3 = RootCollection(arg_2)
        return arg_3.resolve("", arg_1)


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """Add a provider to the provider_map routing table."""
        # Make sure share starts with, or is '/'
        arg_1 = "/" + arg_1.strip("/")
        assert arg_1 not in arg_0.provider_map

        if compat.is_basestring(arg_2):
            # Syntax:
            #   <mount_path>: <folder_path>
            # We allow a simple string as 'provider'. In this case we interpret
            # it as a file system root folder that is published.
            arg_2 = FilesystemProvider(arg_2, arg_3)
        elif type(arg_2) in (dict,):
            if "provider" in arg_2:
                # Syntax:
                #   <mount_path>: {"provider": <class_path>, "args": <pos_args>, "kwargs": <named_args}
                arg_4 = dynamic_import_class(arg_2["provider"])
                arg_2 = arg_4(
                    *arg_2.get("args", []), **arg_2.get("kwargs", {})
                )
            else:
                # Syntax:
                #   <mount_path>: {"root": <path>, "redaonly": <bool>}
                arg_2 = FilesystemProvider(
                    arg_2["root"], bool(arg_2.get("readonly", False))
                )
        elif type(arg_2) in (list, tuple):
            raise ValueError(
                "Provider {}: tuple/list syntax is no longer supported".format(arg_2)
            )
            # provider = FilesystemProvider(provider[0], provider[1])

        if not isinstance(arg_2, DAVProvider):
            raise ValueError("Invalid provider {}".format(arg_2))

        arg_2.set_share_path(arg_1)
        if arg_0.mount_path:
            arg_2.set_mount_path(arg_0.mount_path)

        # TODO: someday we may want to configure different lock/prop
        # managers per provider
        arg_2.set_lock_manager(arg_0.lock_manager)
        arg_2.set_prop_manager(arg_0.prop_manager)

        arg_0.provider_map[arg_1] = arg_2
        # self.provider_map[share] = {"provider": provider, "allow_anonymous": False}

        # Store the list of share paths, ordered by length, so route lookups
        # will return the most specific match
        arg_0.sorted_share_list = [s.lower() for s in arg_0.provider_map.keys()]
        arg_0.sorted_share_list = sorted(arg_0.sorted_share_list, key=len, reverse=True)

        return arg_2


def Func(arg_0, arg_1):
        """Get the registered DAVProvider for a given path.

        Returns:
            tuple: (share, provider)
        """
        # Find DAV provider that matches the share
        arg_2 = None
        arg_3 = arg_1.lower()
        for arg_4 in arg_0.sorted_share_list:
            # @@: Case sensitivity should be an option of some sort here;
            # os.path.normpath might give the preferred case for a filename.
            if arg_4 == "/":
                arg_2 = arg_4
                break
            elif arg_3 == arg_4 or arg_3.startswith(arg_4 + "/"):
                arg_2 = arg_4
                break

        if arg_2 is None:
            return None, None
        return arg_2, arg_0.provider_map.get(arg_2)


def Func(
        arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9
    ):
        """Computes digest hash.

        Calculation of the A1 (HA1) part is delegated to the dc interface method
        `digest_auth_user()`.

        Args:
            realm (str):
            user_name (str):
            method (str): WebDAV Request Method
            uri (str):
            nonce (str): server generated nonce value
            cnonce (str): client generated cnonce value
            qop (str): quality of protection
            nc (str) (number), nonce counter incremented by client
        Returns:
            MD5 hash string
            or False if user rejected by domain controller
        """

        def md5h(arg_10):
            return md5(compat.to_bytes(arg_10)).hexdigest()

        def md5kd(arg_11, arg_10):
            return md5h(arg_11 + ":" + arg_10)

        arg_12 = arg_0.domain_controller.digest_auth_user(arg_1, arg_2, arg_9)
        if not arg_12:
            return False

        arg_13 = arg_3 + ":" + arg_4

        if arg_7:
            arg_14 = md5kd(
                arg_12, arg_5 + ":" + arg_8 + ":" + arg_6 + ":" + arg_7 + ":" + md5h(arg_13)
            )
        else:
            arg_14 = md5kd(arg_12, arg_5 + ":" + md5h(arg_13))

        return arg_14


def Func(arg_0, arg_1, arg_2):
        """Handle a COPY request natively.

        """
        arg_3, arg_4 = util.pop_path(arg_1)
        arg_4 = arg_4.strip("/")
        arg_5 = arg_0.provider.ui
        arg_6 = arg_0.provider.repo
        _logger.info("Func %s -> %s" % (arg_0.localHgPath, arg_4))
        if arg_0.rev is None and arg_3 == "edit":
            # COPY /edit/a/b to /edit/c/d: turn into 'hg copy -f a/b c/d'
            commands.copy(arg_5, arg_6, arg_0.localHgPath, arg_4, force=True)
        elif arg_0.rev is None and arg_3 == "released":
            # COPY /edit/a/b to /released/c/d
            # This is interpreted as 'hg commit a/b' (ignoring the dest. path)
            arg_0._commit("WsgiDAV commit (COPY %s -> %s)" % (arg_0.path, arg_1))
        else:
            raise DAVError(HTTP_FORBIDDEN)
        # Return True: request was handled
        return True


def Func(arg_0, arg_1=None):
        """Read log entries into a list of dictionaries."""
        arg_0.ui.pushbuffer()
        commands.log(arg_0.ui, arg_0.repo, arg_1=arg_1, date=None, rev=None, user=None)
        arg_2 = arg_0.ui.popbuffer().strip()

        arg_3 = []
        for arg_4 in arg_2.split("\n\n"):
            arg_5 = {}
            arg_3.append(arg_5)
            for arg_6 in arg_4.split("\n"):
                arg_7, arg_8 = arg_6.split(":", 1)
                assert arg_7 in ("changeset", "tag", "user", "date", "summary")
                arg_5[arg_7.strip()] = arg_8.strip()
            arg_5["parsed_date"] = util.parse_time_string(arg_5["date"])
            arg_10, arg_11 = arg_5["changeset"].split(":")
            arg_5["local_id"] = int(arg_10)
            arg_5["unid"] = arg_11
        #        pprint(logList)
        return arg_3


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """Return a dictionary containing all files under source control.

        dirinfos:
            Dictionary containing direct members for every collection.
            {folderpath: (collectionlist, filelist), ...}
        files:
            Sorted list of all file paths in the manifest.
        filedict:
            Dictionary containing all files under source control.

        ::

            {'dirinfos': {'': (['wsgidav',
                                'tools',
                                'WsgiDAV.egg-info',
                                'tests'],
                               ['index.rst',
                                'wsgidav MAKE_DAILY_BUILD.launch',
                                'wsgidav run_server.py DEBUG.launch',
                                'wsgidav-paste.conf',
                                ...
                                'setup.py']),
                          'wsgidav': (['addons', 'samples', 'server', 'interfaces'],
                                      ['__init__.pyc',
                                       'dav_error.pyc',
                                       'dav_provider.pyc',
                                       ...
                                       'wsgidav_app.py']),
                           },
             'files': ['.hgignore',
                       'ADDONS.txt',
                       'wsgidav/samples/mysql_dav_provider.py',
                       ...
                       ],
             'filedict': {'.hgignore': True,
                           'README.txt': True,
                           'WsgiDAV.egg-info/PKG-INFO': True,
                           }
                           }
        """
        arg_4 = arg_1.setdefault("wsgidav.hg.cache", {})
        if arg_4.get(arg_17.to_native(arg_2)) is not None:
            _logger.debug("Func(%s): cache hit." % arg_2)
            return arg_4[arg_17.to_native(arg_2)]

        arg_5 = time.time()
        arg_0.ui.pushbuffer()
        commands.manifest(arg_0.ui, arg_0.repo, arg_2)
        arg_6 = arg_0.ui.popbuffer()
        arg_7 = []
        arg_8 = {}
        arg_9 = {}
        for arg_10 in arg_6.split("\n"):
            if arg_10.strip() == "":
                continue
            arg_10 = arg_10.replace("\\", "/")
            # add all parent directories to 'dirinfos'
            arg_11 = arg_10.split("/")
            if len(arg_11) >= 1:
                arg_12 = ""
                for arg_13 in range(0, len(arg_11) - 1):
                    arg_14 = arg_11[arg_13]
                    arg_15 = arg_8.setdefault(arg_12, ([], []))
                    if arg_14 not in arg_15[0]:
                        arg_15[0].append(arg_14)
                    if arg_12 == "":
                        arg_12 = arg_14
                    else:
                        arg_12 = "%s/%s" % (arg_12, arg_14)
                arg_8.setdefault(arg_12, ([], []))[1].append(arg_11[-1])
            arg_9[arg_10] = True
        arg_7.sort()

        arg_16 = {"files": arg_7, "dirinfos": arg_8, "filedict": arg_9}
        arg_4[arg_17.to_native(arg_2)] = arg_16
        _logger.info("_getRepoInfo(%s) took %.3f" % (arg_2, time.time() - arg_5))
        return arg_16


def Func(arg_0):
        """Return preferred mapping for a resource mapping.

        Different URLs may map to the same resource, e.g.:
            '/a/b' == '/A/b' == '/a/b/'
        Func() returns the same value for all these variants, e.g.:
            '/a/b/'   (assuming resource names considered case insensitive)

        @param path: a UTF-8 encoded, unquoted byte string.
        @return: a UTF-8 encoded, unquoted byte string.
        """
        if arg_0.path in ("", "/"):
            return "/"
        # Append '/' for collections
        if arg_0.is_collection and not arg_0.path.endswith("/"):
            return arg_0.path + "/"
        # TODO: handle case-sensitivity, depending on OS
        # (FileSystemProvider could do this with os.path:
        # (?) on unix we can assume that the path already matches exactly the case of filepath
        # on windows we could use path.lower() or get the real case from the
        # file system
        return arg_0.path


def Func(arg_0):
        """Convert path to a URL that can be passed to XML responses.

        Byte string, UTF-8 encoded, quoted.

        See http://www.webdav.org/specs/rfc4918.html#rfc.section.8.3
        We are using the path-absolute option. i.e. starting with '/'.
        URI ; See section 3.2.1 of [RFC2068]
        """
        # Nautilus chokes, if href encodes '(' as '%28'
        # So we don't encode 'extra' and 'safe' characters (see rfc2068 3.2.1)
        arg_1 = "/" + "!*'()," + "$-_|."
        return compat.quote(
            arg_0.provider.mount_path
            + arg_0.provider.share_path
            + arg_0.get_preferred_path(),
            arg_1=arg_1,
        )


def Func(arg_0, arg_1):
        """Remove all associated dead properties."""
        if arg_0.provider.prop_manager:
            arg_0.provider.prop_manager.remove_properties(
                arg_0.get_ref_url(), arg_0.environ
            )


def Func(arg_0, arg_1):
        """Set application location for this resource provider.

        @param share_path: a UTF-8 encoded, unquoted byte string.
        """
        # if isinstance(share_path, unicode):
        #     share_path = share_path.encode("utf8")
        assert arg_1 == "" or arg_1.startswith("/")
        if arg_1 == "/":
            arg_1 = ""  # This allows to code 'absPath = share_path + path'
        assert arg_1 in ("", "/") or not arg_1.endswith("/")
        arg_0.share_path = arg_1


def Func(arg_0, arg_1):
        """Convert a refUrl to a path, by stripping the share prefix.

        Used to calculate the <path> from a storage key by inverting get_ref_url().
        """
        return "/" + compat.unquote(util.lstripstr(arg_1, arg_0.share_path)).lstrip(
            "/"
        )


def Func(arg_0, arg_1, arg_2):
        """Return True, if path maps to an existing collection resource.

        This method should only be used, if no other information is queried
        for <path>. Otherwise a _DAVResource should be created first.
        """
        arg_3 = arg_0.get_resource_inst(arg_1, arg_2)
        return arg_3 and arg_3.Func


def Func(arg_0):
    """Convert XML string into etree.Element."""
    try:
        return etree.XML(arg_0)
    except Exception:
        # TODO:
        # ExpatError: reference to invalid character number: line 1, column 62
        # litmus fails, when xml is used instead of lxml
        # 18. propget............... FAIL (PROPFIND on `/temp/litmus/prop2':
        #   Could not read status line: connection was closed by server)
        # text = <ns0:high-unicode xmlns:ns0="http://example.com/neon/litmus/">��
        #   </ns0:high-unicode>
        #        t2 = text.encode("utf8")
        #        return etree.XML(t2)
        _logger.error(
            "Error parsing XML string. "
            "If lxml is not available, and unicode is involved, then "
            "installing lxml _may_ solve this issue."
        )
        _logger.error("XML source: {}".format(arg_0))
        raise


def Func(arg_0, arg_1=False):
    """Wrapper for etree.tostring, that takes care of unsupported pretty_print
    option and prepends an encoding header."""
    if use_lxml:
        arg_2 = etree.tostring(
            arg_0, encoding="UTF-8", xml_declaration=True, arg_1=arg_1
        )
    else:
        arg_2 = etree.tostring(arg_0, encoding="UTF-8")
        if not arg_2.startswith(b"<?xml "):
            arg_2 = b'<?xml version="1.0" encoding="utf-8" ?>\n' + arg_2

    assert arg_2.startswith(b"<?xml ")  # ET should prepend an encoding header
    return arg_2


def Func(arg_0):
    """Serialize etree.Element.

    Note: element may contain more than one child or only text (i.e. no child
          at all). Therefore the resulting string may raise an exception, when
          passed back to etree.XML().
    """
    if len(arg_0) == 0:
        return arg_0.text or ""  # Make sure, None is returned as ''
    arg_1 = compat.StringIO()
    for arg_2 in arg_0:
        arg_1.write(xml_to_bytes(arg_2, pretty_print=False) + "\n")
        # print(xml_to_bytes(childnode, pretty_print=False), file=stream)
    arg_3 = arg_1.getvalue()
    arg_1.close()
    return arg_3


def Func(arg_0, arg_1, arg_2=True, arg_3=True):
    """Convert path to absolute if not None."""
    if arg_0 in (None, ""):
        if arg_3:
            return None
        raise ValueError("Invalid path {!r}".format(arg_0))
    # Evaluate path relative to the folder of the config file (if any)
    arg_4 = arg_1.get("_config_file")
    if arg_4 and not os.path.isabs(arg_0):
        arg_0 = os.path.normpath(os.path.join(os.path.dirname(arg_4), arg_0))
    else:
        arg_0 = os.path.abspath(arg_0)
    if arg_2 and not os.path.exists(arg_0):
        raise ValueError("Invalid path {!r}".format(arg_0))
    return arg_0


def Func(arg_0, arg_1):
    """Read configuration file options into a dictionary."""

    arg_0 = os.path.abspath(arg_0)

    if not os.path.exists(arg_0):
        raise RuntimeError("Couldn't open configuration file '{}'.".format(arg_0))

    if arg_0.endswith(".json"):
        with io.open(arg_0, mode="r", encoding="utf-8") as json_file:
            # Minify the JSON file to strip embedded comments
            arg_2 = jsmin(json_file.read())
        arg_3 = json.loads(arg_2)

    elif arg_0.endswith(".yaml"):
        with io.open(arg_0, mode="r", encoding="utf-8") as yaml_file:
            arg_3 = yaml.safe_load(yaml_file)

    else:
        try:
            import imp

            arg_3 = {}
            arg_4 = imp.load_source("configuration_module", arg_0)

            for arg_5, arg_6 in vars(arg_4).items():
                if arg_5.startswith("__"):
                    continue
                elif isfunction(arg_6):
                    continue
                arg_3[arg_5] = arg_6
        except Exception:
            arg_7, arg_8 = sys.exc_info()[:2]
            arg_9 = traceback.format_exception_only(arg_7, arg_8)
            arg_10 = "\n".join(arg_9)
            print(
                "Failed to read configuration file: "
                + arg_0
                + "\nDue to "
                + arg_10,
                file=sys.stderr,
            )
            raise

    arg_3["_config_file"] = arg_0
    return arg_3


def Func(arg_0, arg_1, arg_2):
    """Run WsgiDAV using paste.httpserver, if Paste is installed.

    See http://pythonpaste.org/modules/httpserver.html for more options
    """
    from paste import httpserver

    arg_3 = "WsgiDAV/{} {} Python {}".format(
        __version__, httpserver.WSGIHandler.server_version, util.PYTHON_VERSION
    )
    _logger.info("Running {}...".format(arg_3))

    # See http://pythonpaste.org/modules/httpserver.html for more options
    arg_4 = httpserver.serve(
        arg_0,
        arg_9=arg_1["host"],
        arg_10=arg_1["port"],
        server_version=arg_3,
        # This option enables handling of keep-alive
        # and expect-100:
        protocol_version="HTTP/1.1",
        start_loop=False,
    )

    if arg_1["verbose"] >= 5:
        arg_5 = arg_4.RequestHandlerClass.handle_one_request

        def arg_8(arg_6):
            arg_5(arg_6)
            if arg_6.close_connection == 1:
                _logger.debug("HTTP Connection : close")
            else:
                _logger.debug("HTTP Connection : continue")

        arg_4.RequestHandlerClass.handle_one_request = arg_8

        # __handle = server.RequestHandlerClass.handle

        # def handle(self):
        #     _logger.debug("open HTTP connection")
        #     __handle(self)

        arg_4.RequestHandlerClass.handle_one_request = arg_8

    arg_9, arg_10 = arg_4.server_address
    if arg_9 == "0.0.0.0":
        _logger.info(
            "Serving on 0.0.0.0:{} view at {}://127.0.0.1:{}".format(arg_10, "http", arg_10)
        )
    else:
        _logger.info("Serving on {}://{}:{}".format("http", arg_9, arg_10))
    try:
        arg_4.serve_forever()
    except KeyboardInterrupt:
        _logger.warning("Caught Ctrl-C, shutting down...")
    return


def Func(arg_0, arg_1, arg_2):
    """Run WsgiDAV using gevent if gevent is installed.

    See
      https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356
      https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38
     for more options
    """
    import gevent
    import gevent.monkey

    gevent.monkey.patch_all()
    from gevent.pywsgi import WSGIServer

    arg_3 = {
        "bind_addr": (arg_1["host"], arg_1["port"]),
        "wsgi_app": arg_0,
        # TODO: SSL support
        "keyfile": None,
        "certfile": None,
    }
    arg_4 = "http"
    # Override or add custom args
    arg_3.update(arg_1.get("server_args", {}))

    arg_5 = WSGIServer(arg_3["bind_addr"], arg_0)
    _logger.info("Running {}".format(arg_5))
    _logger.info(
        "Serving on {}://{}:{} ...".format(arg_4, arg_1["host"], arg_1["port"])
    )
    try:
        gevent.spawn(arg_5.serve_forever())
    except KeyboardInterrupt:
        _logger.warning("Caught Ctrl-C, shutting down...")
    return


def Func(arg_0, arg_1, arg_2):
    """Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed."""
    assert arg_2 == "cherrypy-wsgiserver"

    try:
        from cherrypy import arg_4
        from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter

        _logger.warning("WARNING: cherrypy.wsgiserver is deprecated.")
        _logger.warning(
            "         Starting with CherryPy 9.0 the functionality from cherrypy.wsgiserver"
        )
        _logger.warning("         was moved to the cheroot project.")
        _logger.warning("         Consider using --server=cheroot.")
    except ImportError:
        _logger.error("*" * 78)
        _logger.error("ERROR: Could not import cherrypy.wsgiserver.")
        _logger.error(
            "Try `pip install cherrypy` or specify another server using the --server option."
        )
        _logger.error("Note that starting with CherryPy 9.0, the server was moved to")
        _logger.error(
            "the cheroot project, so it is recommended to use `-server=cheroot`"
        )
        _logger.error("and run `pip install cheroot` instead.")
        _logger.error("*" * 78)
        raise

    arg_3 = "WsgiDAV/{} {} Python/{}".format(
        __version__, arg_4.CherryPyWSGIServer.version, util.PYTHON_VERSION
    )
    arg_4.CherryPyWSGIServer.version = arg_3

    # Support SSL
    arg_7 = _get_checked_path(arg_1.get("ssl_certificate"), arg_1)
    arg_8 = _get_checked_path(arg_1.get("ssl_private_key"), arg_1)
    arg_9 = _get_checked_path(
        arg_1.get("ssl_certificate_chain"), arg_1
    )
    arg_10 = "http"
    if arg_7:
        assert arg_8
        arg_4.CherryPyWSGIServer.ssl_adapter = BuiltinSSLAdapter(
            arg_7, arg_8, arg_9
        )
        arg_10 = "https"
        _logger.info("SSL / HTTPS enabled.")

    _logger.info("Running {}".format(arg_3))
    _logger.info(
        "Serving on {}://{}:{} ...".format(arg_10, arg_1["host"], arg_1["port"])
    )

    arg_12 = {
        "bind_addr": (arg_1["host"], arg_1["port"]),
        "wsgi_app": arg_0,
        "server_name": arg_3,
    }
    # Override or add custom args
    arg_12.update(arg_1.get("server_args", {}))

    arg_13 = arg_4.CherryPyWSGIServer(**arg_12)

    # If the caller passed a startup event, monkey patch the server to set it
    # when the request handler loop is entered
    arg_14 = arg_1.get("startup_event")
    if arg_14:

        def _patched_tick():
            arg_13.tick = arg_16  # undo the monkey patch
            arg_16()
            _logger.info("CherryPyWSGIServer is ready")
            arg_14.set()

        arg_16 = arg_13.tick
        arg_13.tick = _patched_tick

    try:
        arg_13.start()
    except KeyboardInterrupt:
        _logger.warning("Caught Ctrl-C, shutting down...")
    finally:
        arg_13.stop()
    return


def Func(arg_0, arg_1, arg_2):
    """Run WsgiDAV using flup.server.fcgi if Flup is installed."""
    # http://trac.saddi.com/flup/wiki/FlupServers
    if arg_2 == "flup-fcgi":
        from flup.server.fcgi import WSGIServer, __version__ as flupver
    elif arg_2 == "flup-fcgi-fork":
        from flup.server.fcgi_fork import WSGIServer, __version__ as flupver
    else:
        raise ValueError

    _logger.info(
        "Running WsgiDAV/{} {}/{}...".format(
            __version__, WSGIServer.__module__, flupver
        )
    )
    arg_3 = WSGIServer(
        arg_0,
        bindAddress=(arg_1["host"], arg_1["port"]),
        # debug=True,
    )
    try:
        arg_3.run()
    except KeyboardInterrupt:
        _logger.warning("Caught Ctrl-C, shutting down...")
    return


def Func(arg_0, arg_1, arg_2):
    """Run WsgiDAV using ext_wsgiutils_server from the wsgidav package."""
    from wsgidav.server import ext_wsgiutils_server

    _logger.info(
        "Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...".format(__version__)
    )
    _logger.warning(
        "WARNING: This single threaded server (ext-wsgiutils) is not meant for production."
    )
    try:
        ext_wsgiutils_server.serve(arg_1, arg_0)
    except KeyboardInterrupt:
        _logger.warning("Caught Ctrl-C, shutting down...")
    return


def Func(arg_0, arg_1, arg_2):
        """Handle PROPPATCH request to set or remove a property.

        @see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
        """
        arg_3 = arg_1["PATH_INFO"]
        arg_4 = arg_0._davProvider.get_resource_inst(arg_3, arg_1)

        # Only accept Depth: 0 (but assume this, if omitted)
        arg_1.setdefault("HTTP_DEPTH", "0")
        if arg_1["HTTP_DEPTH"] != "0":
            arg_0._fail(HTTP_BAD_REQUEST, "Depth must be '0'.")

        if arg_4 is None:
            arg_0._fail(HTTP_NOT_FOUND)

        arg_0._evaluate_if_headers(arg_4, arg_1)
        arg_0._check_write_permission(arg_4, "0", arg_1)

        # Parse request
        arg_5 = util.parse_xml_body(arg_1)

        if arg_5.tag != "{DAV:}propertyupdate":
            arg_0._fail(HTTP_BAD_REQUEST)

        # Create a list of update request tuples: (name, value)
        arg_6 = []

        for arg_7 in arg_5:
            arg_8 = None
            if arg_7.tag == "{DAV:}remove":
                arg_8 = "remove"
            elif arg_7.tag == "{DAV:}set":
                arg_8 = "set"
            else:
                arg_0._fail(
                    HTTP_BAD_REQUEST, "Unknown tag (expected 'set' or 'remove')."
                )

            for arg_9 in arg_7:
                if arg_9.tag != "{DAV:}prop":
                    arg_0._fail(HTTP_BAD_REQUEST, "Unknown tag (expected 'prop').")

                for arg_10 in arg_9:
                    arg_11 = None
                    if arg_8 == "remove":
                        arg_11 = None  # Mark as 'remove'
                        if len(arg_10) > 0:
                            # 14.23: All the XML elements in a 'prop' XML
                            # element inside of a 'remove' XML element MUST be
                            # empty
                            arg_0._fail(
                                HTTP_BAD_REQUEST,
                                "prop element must be empty for 'remove'.",
                            )
                    else:
                        arg_11 = arg_10

                    arg_6.append((arg_10.tag, arg_11))

        # Apply updates in SIMULATION MODE and create a result list (name,
        # result)
        arg_12 = True
        arg_13 = []

        for (arg_14, arg_11) in arg_6:
            try:
                arg_4.set_property_value(arg_14, arg_11, dry_run=True)
            except Exception as arg_19:
                arg_15 = as_DAVError(arg_19)
            else:
                arg_15 = "200 OK"
            arg_13.append((arg_14, arg_15))
            arg_12 = arg_12 and arg_15 == "200 OK"

        # Generate response list of 2-tuples (name, value)
        # <value> is None on success, or an instance of DAVError
        arg_16 = []
        arg_17 = []

        if not arg_12:
            # If dry run failed: convert all OK to FAILED_DEPENDENCY.
            for (arg_14, arg_18) in arg_13:
                if arg_18 == "200 OK":
                    arg_18 = DAVError(HTTP_FAILED_DEPENDENCY)
                elif isinstance(arg_18, DAVError):
                    arg_17.append(arg_18.get_user_info())
                arg_16.append((arg_14, arg_18))

        else:
            # Dry-run succeeded: set properties again, this time in 'real' mode
            # In theory, there should be no exceptions thrown here, but this is
            # real live...
            for (arg_14, arg_11) in arg_6:
                try:
                    arg_4.set_property_value(arg_14, arg_11, dry_run=False)
                    # Set value to None, so the response xml contains empty tags
                    arg_16.append((arg_14, None))
                except Exception as arg_19:
                    arg_19 = as_DAVError(arg_19)
                    arg_16.append((arg_14, arg_19))
                    arg_17.append(arg_19.get_user_info())

        # Generate response XML
        arg_20 = xml_tools.make_multistatus_el()
        arg_21 = arg_4.get_href()
        util.add_property_response(arg_20, arg_21, arg_16)
        if arg_17:
            arg_22.SubElement(
                arg_20, "{DAV:}responsedescription"
            ).text = "\n".join(arg_17)

        # Send response
        return util.send_multi_status_response(arg_1, arg_2, arg_20)


def Func(arg_0, arg_1, arg_2):
        """Handle MKCOL request to create a new collection.

        @see http://www.webdav.org/specs/rfc4918.html#METHOD_MKCOL
        """
        arg_3 = arg_1["PATH_INFO"]
        arg_4 = arg_0._davProvider
        #        res = provider.get_resource_inst(path, environ)

        # Do not understand ANY request body entities
        if util.get_content_length(arg_1) != 0:
            arg_0._fail(
                HTTP_MEDIATYPE_NOT_SUPPORTED,
                "The server does not handle any body content.",
            )

        # Only accept Depth: 0 (but assume this, if omitted)
        if arg_1.setdefault("HTTP_DEPTH", "0") != "0":
            arg_0._fail(HTTP_BAD_REQUEST, "Depth must be '0'.")

        if arg_4.exists(arg_3, arg_1):
            arg_0._fail(
                HTTP_METHOD_NOT_ALLOWED,
                "MKCOL can only be executed on an unmapped URL.",
            )

        arg_5 = arg_4.get_resource_inst(util.get_uri_parent(arg_3), arg_1)
        if not arg_5 or not arg_5.is_collection:
            arg_0._fail(HTTP_CONFLICT, "Parent must be an existing collection.")

        # TODO: should we check If headers here?
        #        self._evaluate_if_headers(res, environ)
        # Check for write permissions on the PARENT
        arg_0._check_write_permission(arg_5, "0", arg_1)

        arg_5.create_collection(util.get_uri_name(arg_3))

        return util.send_status_response(arg_1, arg_2, HTTP_CREATED)


def Func(arg_0, arg_1, arg_2):
        """Get the data from a chunked transfer."""
        # Chunked Transfer Coding
        # http://www.servlets.com/rfcs/rfc2616-sec3.html#sec3.6.1

        if "Darwin" in arg_1.get("HTTP_USER_AGENT", "") and arg_1.get(
            "HTTP_X_EXPECTED_ENTITY_LENGTH"
        ):
            # Mac Finder, that does not prepend chunk-size + CRLF ,
            # like it should to comply with the spec. It sends chunk
            # size as integer in a HTTP header instead.
            arg_3 = True
            arg_4 = arg_1.get("HTTP_X_EXPECTED_ENTITY_LENGTH", "0")
            arg_5 = int(arg_4)
        else:
            arg_3 = False
            arg_4 = arg_1["wsgi.input"].readline()
            arg_1["wsgidav.some_input_read"] = 1
            if arg_4 == compat.b_empty:
                arg_5 = 0
            else:
                arg_5 = int(arg_4, 16)

        while arg_5 > 0:
            arg_4 = arg_1["wsgi.input"].read(arg_2)
            yield arg_4
            if arg_3:
                arg_1["wsgidav.some_input_read"] = 1
                # Keep receiving until we read expected size or reach
                # EOF
                if arg_4 == compat.b_empty:
                    arg_5 = 0
                else:
                    arg_5 -= len(arg_4)
            else:
                arg_1["wsgi.input"].readline()
                arg_4 = arg_1["wsgi.input"].readline()
                if arg_4 == compat.b_empty:
                    arg_5 = 0
                else:
                    arg_5 = int(arg_4, 16)
        arg_1["wsgidav.all_input_read"] = 1


def Func(arg_0, arg_1, arg_2, arg_3):
        """Get the data from a non-chunked transfer."""
        if arg_2 == 0:
            # TODO: review this
            # XP and Vista MiniRedir submit PUT with Content-Length 0,
            # before LOCK and the real PUT. So we have to accept this.
            _logger.info("PUT: Content-Length == 0. Creating empty file...")

        #        elif content_length < 0:
        #            # TODO: review this
        #            # If CONTENT_LENGTH is invalid, we may try to workaround this
        #            # by reading until the end of the stream. This may block however!
        #            # The iterator produced small chunks of varying size, but not
        #            # sure, if we always get everything before it times out.
        #            _logger.warning("PUT with invalid Content-Length (%s). "
        #                            "Trying to read all (this may timeout)..."
        #                            .format(environ.get("CONTENT_LENGTH")))
        #            nb = 0
        #            try:
        #                for s in environ["wsgi.input"]:
        #                    environ["wsgidav.some_input_read"] = 1
        #                    _logger.debug("PUT: read from wsgi.input.__iter__, len=%s" % len(s))
        #                    yield s
        #                    nb += len (s)
        #            except socket.timeout:
        #                _logger.warning("PUT: input timed out after writing %s bytes" % nb)
        #                hasErrors = True
        else:
            assert arg_2 > 0
            arg_4 = arg_2
            while arg_4 > 0:
                arg_5 = min(arg_4, arg_3)
                arg_6 = arg_1["wsgi.input"].read(arg_5)
                # This happens with litmus expect-100 test:
                if not len(arg_6) > 0:
                    _logger.error("input.read({}) returned 0 bytes".format(arg_5))
                    break
                arg_1["wsgidav.some_input_read"] = 1
                yield arg_6
                arg_4 -= len(arg_6)

            if arg_4 == 0:
                arg_1["wsgidav.all_input_read"] = 1


def Func(arg_0, arg_1):
        """Return properties document for path."""
        # Query the permanent view to find a url
        arg_2 = arg_0.db.view("properties/by_url", key=arg_1, include_docs=True)
        _logger.debug("find(%r) returned %s" % (arg_1, len(arg_2)))
        assert len(arg_2) <= 1, "Found multiple matches for %r" % arg_1
        for arg_3 in arg_2:
            assert arg_3.doc
            return arg_3.doc
        return None


def Func(arg_0, arg_1, arg_2, arg_3):
        """Computes digest hash A1 part."""
        arg_4 = arg_0._get_realm_entry(arg_1, arg_2)
        if arg_4 is None:
            return False
        arg_5 = arg_4.get("password")
        arg_3["wsgidav.auth.roles"] = arg_4.get("roles", [])
        return arg_0._compute_http_digest_a1(arg_1, arg_2, arg_5)


def Func(arg_0, arg_1):
        """Return a lock dictionary for a token.

        If the lock does not exist or is expired, None is returned.

        token:
            lock token
        Returns:
            Lock dictionary or <None>

        Side effect: if lock is expired, it will be purged and None is returned.
        """
        arg_0._lock.acquire_read()
        try:
            arg_2 = arg_0._dict.Func(arg_1)
            if arg_2 is None:
                # Lock not found: purge dangling URL2TOKEN entries
                _logger.debug("Lock purged dangling: {}".format(arg_1))
                arg_0.delete(arg_1)
                return None
            arg_3 = float(arg_2["expire"])
            if arg_3 >= 0 and arg_3 < time.time():
                _logger.debug(
                    "Lock timed-out({}): {}".format(arg_3, lock_string(arg_2))
                )
                arg_0.delete(arg_1)
                return None
            return arg_2
        finally:
            arg_0._lock.release()


def Func(arg_0, arg_1, arg_2):
        """Create a direct lock for a resource path.

        path:
            Normalized path (utf8 encoded string, no trailing '/')
        lock:
            lock dictionary, without a token entry
        Returns:
            New unique lock token.: <lock

        **Note:** the lock dictionary may be modified on return:

        - lock['root'] is ignored and set to the normalized <path>
        - lock['timeout'] may be normalized and shorter than requested
        - lock['token'] is added
        """
        arg_0._lock.acquire_write()
        try:
            # We expect only a lock definition, not an existing lock
            assert arg_2.get("token") is None
            assert arg_2.get("expire") is None, "Use timeout instead of expire"
            assert arg_1 and "/" in arg_1

            # Normalize root: /foo/bar
            arg_3 = arg_1
            arg_1 = normalize_lock_root(arg_1)
            arg_2["root"] = arg_1

            # Normalize timeout from ttl to expire-date
            arg_4 = float(arg_2.get("timeout"))
            if arg_4 is None:
                arg_4 = LockStorageDict.LOCK_TIME_OUT_DEFAULT
            elif arg_4 < 0 or arg_4 > LockStorageDict.LOCK_TIME_OUT_MAX:
                arg_4 = LockStorageDict.LOCK_TIME_OUT_MAX

            arg_2["timeout"] = arg_4
            arg_2["expire"] = time.time() + arg_4

            validate_lock(arg_2)

            arg_5 = generate_lock_token()
            arg_2["token"] = arg_5

            # Store lock
            arg_0._dict[arg_5] = arg_2

            # Store locked path reference
            arg_7 = "URL2TOKEN:{}".format(arg_1)
            if arg_7 not in arg_0._dict:
                arg_0._dict[arg_7] = [arg_5]
            else:
                # Note: Shelve dictionary returns copies, so we must reassign
                # values:
                arg_8 = arg_0._dict[arg_7]
                arg_8.append(arg_5)
                arg_0._dict[arg_7] = arg_8
            arg_0._flush()
            _logger.debug(
                "LockStorageDict.set({!r}): {}".format(arg_3, lock_string(arg_2))
            )
            return arg_2
        finally:
            arg_0._lock.release()


def Func(arg_0, arg_1):
        """Delete lock.

        Returns True on success. False, if token does not exist, or is expired.
        """
        arg_0._lock.acquire_write()
        try:
            arg_2 = arg_0._dict.get(arg_1)
            _logger.debug("Func {}".format(lock_string(arg_2)))
            if arg_2 is None:
                return False
            # Remove url to lock mapping
            arg_3 = "URL2TOKEN:{}".format(arg_2.get("root"))
            if arg_3 in arg_0._dict:
                # _logger.debug("    Func token {} from url {}".format(token, lock.get("root")))
                arg_4 = arg_0._dict[arg_3]
                if len(arg_4) > 1:
                    # Note: shelve dictionary returns copies, so we must
                    # reassign values:
                    arg_4.remove(arg_1)
                    arg_0._dict[arg_3] = arg_4
                else:
                    del arg_0._dict[arg_3]
            # Remove the lock
            del arg_0._dict[arg_1]

            arg_0._flush()
        finally:
            arg_0._lock.release()
        return True


def Func(arg_0):
        """Delete all entries."""
        arg_0._lock.acquire_write()  # TODO: read access is enough?
        try:
            arg_1 = arg_0._dict is None
            if arg_1:
                arg_0.open()
            if len(arg_0._dict):
                arg_0._dict.Func()
                arg_0._dict.sync()
            if arg_1:
                arg_0.close()
        finally:
            arg_0._lock.release()


def Func(arg_0):
    """Return readable rep."""
    if not arg_0:
        return "Lock: None"

    if arg_0["expire"] < 0:
        arg_1 = "Infinite ({})".format(arg_0["expire"])
    else:
        arg_1 = "{} (in {} seconds)".format(
            util.get_log_time(arg_0["expire"]), arg_0["expire"] - time.time()
        )

    return "Lock(<{}..>, '{}', {}, {}, depth-{}, until {}".format(
        # first 4 significant token characters
        arg_0.get("token", "?" * 30)[18:22],
        arg_0.get("root"),
        arg_0.get("principal"),
        arg_0.get("scope"),
        arg_0.get("depth"),
        arg_1,
    )


def Func(
        arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7
    ):
        """Acquire lock and return lock_dict.

        principal
            Name of the principal.
        lock_type
            Must be 'write'.
        lock_scope
            Must be 'shared' or 'exclusive'.
        lock_depth
            Must be '0' or 'infinity'.
        lock_owner
            String identifying the owner.
        path
            Resource URL.
        timeout
            Seconds to live

        This function does NOT check, if the new lock creates a conflict!
        """
        if arg_7 is None:
            arg_7 = LockManager.LOCK_TIME_OUT_DEFAULT
        elif arg_7 < 0:
            arg_7 = -1

        arg_8 = {
            "root": arg_6,
            "type": arg_2,
            "scope": arg_3,
            "depth": arg_4,
            "owner": arg_5,
            "timeout": arg_7,
            "principal": arg_1,
        }
        #
        arg_0.storage.create(arg_6, arg_8)
        return arg_8


def Func(
        arg_0,
        arg_1,
        arg_2,
        arg_3,
        arg_4,
        arg_5,
        arg_6,
        arg_7,
        arg_8,
    ):
        """Check for permissions and Func a lock.

        On success return new lock dictionary.
        On error raise a DAVError with an embedded DAVErrorCondition.
        """
        arg_1 = normalize_lock_root(arg_1)
        arg_0._lock.Func_write()
        try:
            # Raises DAVError on conflict:
            arg_0._check_lock_permission(
                arg_1, arg_2, arg_3, arg_4, arg_8, arg_7
            )
            return arg_0._generate_lock(
                arg_7, arg_2, arg_3, arg_4, arg_5, arg_1, arg_6
            )
        finally:
            arg_0._lock.release()


def Func(arg_0, arg_1, arg_2=None):
        """Set new timeout for lock, if existing and valid."""
        if arg_2 is None:
            arg_2 = LockManager.LOCK_TIME_OUT_DEFAULT
        return arg_0.storage.Func(arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=None):
        """Return lock_dict, or None, if not found or invalid.

        Side effect: if lock is expired, it will be purged and None is returned.

        key:
            name of lock attribute that will be returned instead of a dictionary.
        """
        assert arg_2 in (
            None,
            "type",
            "scope",
            "depth",
            "owner",
            "root",
            "timeout",
            "principal",
            "token",
        )
        arg_3 = arg_0.storage.get(arg_1)
        if arg_2 is None or arg_3 is None:
            return arg_3
        return arg_3[arg_2]


def Func(arg_0, arg_1=None):
        """Acquire a read lock for the current thread, waiting at most
        timeout seconds or doing a non-blocking check in case timeout is <= 0.

        In case timeout is None, the call to Func blocks until the
        lock request can be serviced.

        In case the timeout expires before the lock could be serviced, a
        RuntimeError is thrown."""

        if arg_1 is not None:
            arg_2 = time() + arg_1
        arg_3 = currentThread()
        arg_0.__condition.acquire()
        try:
            if arg_0.__writer is arg_3:
                # If we are the writer, grant a new read lock, always.
                arg_0.__writercount += 1
                return
            while True:
                if arg_0.__writer is None:
                    # Only test anything if there is no current writer.
                    if arg_0.__upgradewritercount or arg_0.__pendingwriters:
                        if arg_3 in arg_0.__readers:
                            # Only grant a read lock if we already have one
                            # in case writers are waiting for their turn.
                            # This means that writers can't easily get starved
                            # (but see below, readers can).
                            arg_0.__readers[arg_3] += 1
                            return
                        # No, we aren't a reader (yet), wait for our turn.
                    else:
                        # Grant a new read lock, always, in case there are
                        # no pending writers (and no writer).
                        arg_0.__readers[arg_3] = arg_0.__readers.get(arg_3, 0) + 1
                        return
                if arg_1 is not None:
                    arg_5 = arg_2 - time()
                    if arg_5 <= 0:
                        # Timeout has expired, signal caller of this.
                        raise RuntimeError("Acquiring read lock timed out")
                    arg_0.__condition.wait(arg_5)
                else:
                    arg_0.__condition.wait()
        finally:
            arg_0.__condition.release()


def Func(arg_0, arg_1=None):
        """Acquire a write lock for the current thread, waiting at most
        timeout seconds or doing a non-blocking check in case timeout is <= 0.

        In case the write lock cannot be serviced due to the deadlock
        condition mentioned above, a ValueError is raised.

        In case timeout is None, the call to Func blocks until the
        lock request can be serviced.

        In case the timeout expires before the lock could be serviced, a
        RuntimeError is thrown."""

        if arg_1 is not None:
            arg_2 = time() + arg_1
        arg_3, arg_4 = currentThread(), False
        arg_0.__condition.acquire()
        try:
            if arg_0.__writer is arg_3:
                # If we are the writer, grant a new write lock, always.
                arg_0.__writercount += 1
                return
            elif arg_3 in arg_0.__readers:
                # If we are a reader, no need to add us to pendingwriters,
                # we get the upgradewriter slot.
                if arg_0.__upgradewritercount:
                    # If we are a reader and want to upgrade, and someone
                    # else also wants to upgrade, there is no way we can do
                    # this except if one of us releases all his read locks.
                    # Signal this to user.
                    raise ValueError("Inevitable dead lock, denying write lock")
                arg_4 = True
                arg_0.__upgradewritercount = arg_0.__readers.pop(arg_3)
            else:
                # We aren't a reader, so add us to the pending writers queue
                # for synchronization with the readers.
                arg_0.__pendingwriters.append(arg_3)
            while True:
                if not arg_0.__readers and arg_0.__writer is None:
                    # Only test anything if there are no readers and writers.
                    if arg_0.__upgradewritercount:
                        if arg_4:
                            # There is a writer to upgrade, and it's us. Take
                            # the write lock.
                            arg_0.__writer = arg_3
                            arg_0.__writercount = arg_0.__upgradewritercount + 1
                            arg_0.__upgradewritercount = 0
                            return
                        # There is a writer to upgrade, but it's not us.
                        # Always leave the upgrade writer the advance slot,
                        # because he presumes he'll get a write lock directly
                        # from a previously held read lock.
                    elif arg_0.__pendingwriters[0] is arg_3:
                        # If there are no readers and writers, it's always
                        # fine for us to take the writer slot, removing us
                        # from the pending writers queue.
                        # This might mean starvation for readers, though.
                        arg_0.__writer = arg_3
                        arg_0.__writercount = 1
                        arg_0.__pendingwriters = arg_0.__pendingwriters[1:]
                        return
                if arg_1 is not None:
                    arg_9 = arg_2 - time()
                    if arg_9 <= 0:
                        # Timeout has expired, signal caller of this.
                        if arg_4:
                            # Put us back on the reader queue. No need to
                            # signal anyone of this change, because no other
                            # writer could've taken our spot before we got
                            # here (because of remaining readers), as the test
                            # for proper conditions is at the start of the
                            # loop, not at the end.
                            arg_0.__readers[arg_3] = arg_0.__upgradewritercount
                            arg_0.__upgradewritercount = 0
                        else:
                            # We were a simple pending writer, just remove us
                            # from the FIFO list.
                            arg_0.__pendingwriters.remove(arg_3)
                        raise RuntimeError("Acquiring write lock timed out")
                    arg_0.__condition.wait(arg_9)
                else:
                    arg_0.__condition.wait()
        finally:
            arg_0.__condition.release()


def Func(arg_0):
        """Release the currently held lock.

        In case the current thread holds no lock, a ValueError is thrown."""

        arg_1 = currentThread()
        arg_0.__condition.acquire()
        try:
            if arg_0.__writer is arg_1:
                # We are the writer, take one nesting depth away.
                arg_0.__writercount -= 1
                if not arg_0.__writercount:
                    # No more write locks; take our writer position away and
                    # notify waiters of the new circumstances.
                    arg_0.__writer = None
                    arg_0.__condition.notifyAll()
            elif arg_1 in arg_0.__readers:
                # We are a reader currently, take one nesting depth away.
                arg_0.__readers[arg_1] -= 1
                if not arg_0.__readers[arg_1]:
                    # No more read locks, take our reader position away.
                    del arg_0.__readers[arg_1]
                    if not arg_0.__readers:
                        # No more readers, notify waiters of the new
                        # circumstances.
                        arg_0.__condition.notifyAll()
            else:
                raise ValueError("Trying to Func unheld lock")
        finally:
            arg_0.__condition.Func()