def set_property_value(self, name, value, dry_run=False):

assert value is None or xml_tools.is_etree_element(value)<EOL>if name in _lockPropertyNames:<EOL><INDENT>raise DAVError(<EOL>HTTP_FORBIDDEN, err_condition=PRECONDITION_CODE_ProtectedProperty<EOL>)<EOL><DEDENT>config = self.environ["<STR_LIT>"]<EOL>mutableLiveProps = config.get("<STR_LIT>", [])<EOL>if (<EOL>name.startswith("<STR_LIT>")<EOL>and name in _standardLivePropNames<EOL>and name in mutableLiveProps<EOL>):<EOL><INDENT>if name in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>try:<EOL><INDENT>return self.set_last_modified(self.path, value.text, dry_run)<EOL><DEDENT>except Exception:<EOL><INDENT>_logger.warning(<EOL>"<STR_LIT>".format(<EOL>self.path<EOL>)<EOL>)<EOL><DEDENT><DEDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>if name.startswith("<STR_LIT>"):<EOL><INDENT>agent = self.environ.get("<STR_LIT>", "<STR_LIT:None>")<EOL>win32_emu = config.get("<STR_LIT>", {}).get("<STR_LIT>", False)<EOL>if win32_emu and "<STR_LIT>" not in agent:<EOL><INDENT>if "<STR_LIT>" in name:<EOL><INDENT>return self.set_last_modified(self.path, value.text, dry_run)<EOL><DEDENT>elif "<STR_LIT>" in name:<EOL><INDENT>return True<EOL><DEDENT>elif "<STR_LIT>" in name:<EOL><INDENT>return True<EOL><DEDENT>elif "<STR_LIT>" in name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>pm = self.provider.prop_manager<EOL>if pm and not name.startswith("<STR_LIT>"):<EOL><INDENT>refUrl = self.get_ref_url()<EOL>if value is None:<EOL><INDENT>return pm.remove_property(refUrl, name, dry_run, self.environ)<EOL><DEDENT>else:<EOL><INDENT>value = etree.tostring(value)<EOL>return pm.write_property(refUrl, name, value, dry_run, self.environ)<EOL><DEDENT><DEDENT>raise DAVError(HTTP_FORBIDDEN)<EOL>

Set a property value or remove a property.

        value == None means 'remove property'.
        Raise HTTP_FORBIDDEN if property is read-only, or not supported.

        When dry_run is True, this function should raise errors, as in a real
        run, but MUST NOT change any data.

        This default implementation

        - raises HTTP_FORBIDDEN, if trying to modify a locking property
        - raises HTTP_FORBIDDEN, if trying to modify an immutable {DAV:}
          property
        - handles Windows' Win32LastModifiedTime to set the getlastmodified
          property, if enabled
        - stores everything else as dead property, if a property manager is
          present.
        - raises HTTP_FORBIDDEN, else

        Removing a non-existing prop is NOT an error.

        Note: RFC 4918 states that {DAV:}displayname 'SHOULD NOT be protected'

        A resource provider may override this method, to update supported custom
        live properties.


raise NotImplementedError<EOL>

Contains the Content-Type header returned by a GET without accept
        headers.

        This getcontenttype property MUST be defined on any DAV compliant
        resource that returns the Content-Type header in response to a GET.
        See http://www.webdav.org/specs/rfc4918.html#PROPERTY_getcontenttype


def copy_move_single(self, dest_path, is_move):

if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>fpDest = self.provider._loc_to_file_path(dest_path, self.environ)<EOL>assert not util.is_equal_or_child_uri(self.path, dest_path)<EOL>if not os.path.exists(fpDest):<EOL><INDENT>os.mkdir(fpDest)<EOL><DEDENT>try:<EOL><INDENT>shutil.copystat(self._file_path, fpDest)<EOL><DEDENT>except Exception:<EOL><INDENT>_logger.exception("<STR_LIT>".format(self._file_path))<EOL><DEDENT>propMan = self.provider.prop_manager<EOL>if propMan:<EOL><INDENT>destRes = self.provider.get_resource_inst(dest_path, self.environ)<EOL>if is_move:<EOL><INDENT>propMan.move_properties(<EOL>self.get_ref_url(),<EOL>destRes.get_ref_url(),<EOL>with_children=False,<EOL>environ=self.environ,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>propMan.copy_properties(<EOL>self.get_ref_url(), destRes.get_ref_url(), self.environ<EOL>)<EOL><DEDENT><DEDENT>


<EOL>nameList = []<EOL>assert compat.is_unicode(self._file_path)<EOL>for name in os.listdir(self._file_path):<EOL><INDENT>if not compat.is_unicode(name):<EOL><INDENT>name = name.decode(sys.getfilesystemencoding())<EOL><DEDENT>assert compat.is_unicode(name)<EOL>fp = os.path.join(self._file_path, name)<EOL>if not os.path.isdir(fp) and not os.path.isfile(fp):<EOL><INDENT>_logger.debug("<STR_LIT>".format(fp))<EOL>continue<EOL><DEDENT>name = compat.to_native(name)<EOL>nameList.append(name)<EOL><DEDENT>return nameList<EOL>

Return list of direct collection member names (utf-8 encoded).

        See DAVCollection.get_member_names()


def _loc_to_file_path(self, path, environ=None):

root_path = self.root_folder_path<EOL>assert root_path is not None<EOL>assert compat.is_native(root_path)<EOL>assert compat.is_native(path)<EOL>path_parts = path.strip("<STR_LIT:/>").split("<STR_LIT:/>")<EOL>file_path = os.path.abspath(os.path.join(root_path, *path_parts))<EOL>if not file_path.startswith(root_path):<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(<EOL>file_path<EOL>)<EOL>)<EOL><DEDENT>file_path = util.to_unicode_safe(file_path)<EOL>return file_path<EOL>

Convert resource path to a unicode absolute file path.
        Optional environ argument may be useful e.g. in relation to per-user
        sub-folder chrooting inside root_folder_path.


if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>fpDest = self.provider._loc_to_file_path(dest_path, self.environ)<EOL>assert not util.is_equal_or_child_uri(self.path, dest_path)<EOL>shutil.copy2(self._file_path, fpDest)<EOL>propMan = self.provider.prop_manager<EOL>if propMan:<EOL><INDENT>destRes = self.provider.get_resource_inst(dest_path, self.environ)<EOL>if is_move:<EOL><INDENT>propMan.move_properties(<EOL>self.get_ref_url(),<EOL>destRes.get_ref_url(),<EOL>with_children=False,<EOL>environ=self.environ,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>propMan.copy_properties(<EOL>self.get_ref_url(), destRes.get_ref_url(), self.environ<EOL>)<EOL><DEDENT><DEDENT>


assert not self.is_collection<EOL>if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>return open(self._file_path, "<STR_LIT:wb>", BUFFER_SIZE)<EOL>

Open content as a stream for writing.

        See DAVResource.begin_write()


return True<EOL>

Return True, if move_recursive() is available (see comments there).


def set_last_modified(self, dest_path, time_stamp, dry_run):

<EOL>secs = util.parse_time_string(time_stamp)<EOL>if not dry_run:<EOL><INDENT>os.utime(self._file_path, (secs, secs))<EOL><DEDENT>return True<EOL>

Set last modified time for destPath to timeStamp on epoch-format


if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>fpDest = self.provider._loc_to_file_path(dest_path, self.environ)<EOL>assert not util.is_equal_or_child_uri(self.path, dest_path)<EOL>assert not os.path.exists(fpDest)<EOL>_logger.debug("<STR_LIT>".format(self._file_path, fpDest))<EOL>shutil.move(self._file_path, fpDest)<EOL>if self.provider.prop_manager:<EOL><INDENT>destRes = self.provider.get_resource_inst(dest_path, self.environ)<EOL>self.provider.prop_manager.move_properties(<EOL>self.get_ref_url(),<EOL>destRes.get_ref_url(),<EOL>with_children=True,<EOL>environ=self.environ,<EOL>)<EOL><DEDENT>


assert not self.is_collection<EOL>return open(self._file_path, "<STR_LIT:rb>", BUFFER_SIZE)<EOL>

Open content as a stream for reading.

        See DAVResource.get_content()


assert "<STR_LIT:/>" not in name<EOL>if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>path = util.join_uri(self.path, name)<EOL>fp = self.provider._loc_to_file_path(path, self.environ)<EOL>os.mkdir(fp)<EOL>

Create a new collection as member of self.

        See DAVResource.create_collection()


assert "<STR_LIT:/>" not in name<EOL>if self.provider.readonly:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>path = util.join_uri(self.path, name)<EOL>fp = self.provider._loc_to_file_path(path, self.environ)<EOL>f = open(fp, "<STR_LIT:wb>")<EOL>f.close()<EOL>return self.provider.get_resource_inst(path, self.environ)<EOL>

Create an empty (length-0) resource.

        See DAVResource.create_empty_resource()


assert compat.is_native(name), "<STR_LIT>".format(name)<EOL>fp = os.path.join(self._file_path, compat.to_unicode(name))<EOL>path = util.join_uri(self.path, name)<EOL>if os.path.isdir(fp):<EOL><INDENT>res = FolderResource(path, self.environ, fp)<EOL><DEDENT>elif os.path.isfile(fp):<EOL><INDENT>res = FileResource(path, self.environ, fp)<EOL><DEDENT>else:<EOL><INDENT>_logger.debug("<STR_LIT>".format(path))<EOL>res = None<EOL><DEDENT>return res<EOL>

Return direct collection member (DAVResource or derived).

        See DAVCollection.get_member()


def get_resource_inst(self, path, environ):

self._count_get_resource_inst += <NUM_LIT:1><EOL>fp = self._loc_to_file_path(path, environ)<EOL>if not os.path.exists(fp):<EOL><INDENT>return None<EOL><DEDENT>if os.path.isdir(fp):<EOL><INDENT>return FolderResource(path, environ, fp)<EOL><DEDENT>return FileResource(path, environ, fp)<EOL>

Return info dictionary for path.

        See DAVProvider.get_resource_inst()


Remove this resource or collection (recursive).

        See DAVResource.delete()


def compute_digest_response(<EOL>self, realm, user_name, method, uri, nonce, cnonce, qop, nc, environ<EOL>):

def md5h(data):<EOL><INDENT>return md5(compat.to_bytes(data)).hexdigest()<EOL><DEDENT>def md5kd(secret, data):<EOL><INDENT>return md5h(secret + "<STR_LIT::>" + data)<EOL><DEDENT>A1 = self.domain_controller.digest_auth_user(realm, user_name, environ)<EOL>if not A1:<EOL><INDENT>return False<EOL><DEDENT>A2 = method + "<STR_LIT::>" + uri<EOL>if qop:<EOL><INDENT>res = md5kd(<EOL>A1, nonce + "<STR_LIT::>" + nc + "<STR_LIT::>" + cnonce + "<STR_LIT::>" + qop + "<STR_LIT::>" + md5h(A2)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>res = md5kd(A1, nonce + "<STR_LIT::>" + md5h(A2))<EOL><DEDENT>return res<EOL>

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


<EOL>if self.err_condition:<EOL><INDENT>return ("<STR_LIT>", compat.to_bytes(self.err_condition.as_string()))<EOL><DEDENT>status = get_http_status_string(self)<EOL>html = []<EOL>html.append(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>html.append("<STR_LIT>")<EOL>html.append(<EOL>"<STR_LIT>"<EOL>)<EOL>html.append("<STR_LIT>".format(status))<EOL>html.append("<STR_LIT>")<EOL>html.append("<STR_LIT>".format(status))<EOL>html.append("<STR_LIT>".format(compat.html_escape(self.get_user_info())))<EOL>html.append("<STR_LIT>")<EOL>html.append(<EOL>"<STR_LIT>".format(<EOL>__version__, compat.html_escape(str(datetime.datetime.now()), "<STR_LIT:utf-8>")<EOL>)<EOL>)<EOL>html.append("<STR_LIT>")<EOL>html = "<STR_LIT:\n>".join(html)<EOL>return ("<STR_LIT>", compat.to_bytes(html))<EOL>

Return a tuple (content-type, response page).


if self.value in ERROR_DESCRIPTIONS:<EOL><INDENT>s = "<STR_LIT:{}>".format(ERROR_DESCRIPTIONS[self.value])<EOL><DEDENT>else:<EOL><INDENT>s = "<STR_LIT:{}>".format(self.value)<EOL><DEDENT>if self.context_info:<EOL><INDENT>s += "<STR_LIT>".format(self.context_info)<EOL><DEDENT>elif self.value in ERROR_RESPONSES:<EOL><INDENT>s += "<STR_LIT>".format(ERROR_RESPONSES[self.value])<EOL><DEDENT>if self.src_exception:<EOL><INDENT>s += "<STR_LIT>".format(self.src_exception)<EOL><DEDENT>if self.err_condition:<EOL><INDENT>s += "<STR_LIT>".format(self.err_condition)<EOL><DEDENT>return s<EOL>


import gevent<EOL>import gevent.monkey<EOL>gevent.monkey.patch_all()<EOL>from gevent.pywsgi import WSGIServer<EOL>server_args = {<EOL>"<STR_LIT>": (config["<STR_LIT:host>"], config["<STR_LIT:port>"]),<EOL>"<STR_LIT>": app,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>}<EOL>protocol = "<STR_LIT:http>"<EOL>server_args.update(config.get("<STR_LIT>", {}))<EOL>dav_server = WSGIServer(server_args["<STR_LIT>"], app)<EOL>_logger.info("<STR_LIT>".format(dav_server))<EOL>_logger.info(<EOL>"<STR_LIT>".format(protocol, config["<STR_LIT:host>"], config["<STR_LIT:port>"])<EOL>)<EOL>try:<EOL><INDENT>gevent.spawn(dav_server.serve_forever())<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>_logger.warning("<STR_LIT>")<EOL><DEDENT>return<EOL>

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


Parse command line options into a dictionary.


<EOL>from wsgiref.simple_server import make_server, software_version<EOL>version = "<STR_LIT>".format(__version__, software_version)<EOL>_logger.info("<STR_LIT>".format(version))<EOL>_logger.warning(<EOL>"<STR_LIT>"<EOL>)<EOL>httpd = make_server(config["<STR_LIT:host>"], config["<STR_LIT:port>"], app)<EOL>try:<EOL><INDENT>httpd.serve_forever()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>_logger.warning("<STR_LIT>")<EOL><DEDENT>return<EOL>

Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.


<EOL>if mode == "<STR_LIT>":<EOL><INDENT>from flup.server.fcgi import WSGIServer, __version__ as flupver<EOL><DEDENT>elif mode == "<STR_LIT>":<EOL><INDENT>from flup.server.fcgi_fork import WSGIServer, __version__ as flupver<EOL><DEDENT>else:<EOL><INDENT>raise ValueError<EOL><DEDENT>_logger.info(<EOL>"<STR_LIT>".format(<EOL>__version__, WSGIServer.__module__, flupver<EOL>)<EOL>)<EOL>server = WSGIServer(<EOL>app,<EOL>bindAddress=(config["<STR_LIT:host>"], config["<STR_LIT:port>"]),<EOL>)<EOL>try:<EOL><INDENT>server.run()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>_logger.warning("<STR_LIT>")<EOL><DEDENT>return<EOL>

Run WsgiDAV using flup.server.fcgi if Flup is installed.


def _get_checked_path(path, config, must_exist=True, allow_none=True):

if path in (None, "<STR_LIT>"):<EOL><INDENT>if allow_none:<EOL><INDENT>return None<EOL><DEDENT>raise ValueError("<STR_LIT>".format(path))<EOL><DEDENT>config_file = config.get("<STR_LIT>")<EOL>if config_file and not os.path.isabs(path):<EOL><INDENT>path = os.path.normpath(os.path.join(os.path.dirname(config_file), path))<EOL><DEDENT>else:<EOL><INDENT>path = os.path.abspath(path)<EOL><DEDENT>if must_exist and not os.path.exists(path):<EOL><INDENT>raise ValueError("<STR_LIT>".format(path))<EOL><DEDENT>return path<EOL>


self.stop_request = False<EOL>self.stopped = False<EOL>while not self.stop_request:<EOL><INDENT>self.handle_request()<EOL><DEDENT>self.stopped = True<EOL>

Handle one request at a time until stop_serve_forever().

        http://code.activestate.com/recipes/336012/


assert hasattr(<EOL>self, "<STR_LIT>"<EOL>), "<STR_LIT>"<EOL>assert not self.stop_request, "<STR_LIT>"<EOL>self.stop_request = True<EOL>time.sleep(<NUM_LIT:0.1>)<EOL>if self.stopped:<EOL><INDENT>return<EOL><DEDENT>def _shutdownHandler(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>self.send_response(<NUM_LIT:200>)<EOL>self.end_headers()<EOL>self.server.stop_request = True<EOL><DEDENT>if not hasattr(ExtHandler, "<STR_LIT>"):<EOL><INDENT>ExtHandler.do_SHUTDOWN = _shutdownHandler<EOL><DEDENT>(host, port) = self.server_address<EOL>conn = http_client.HTTPConnection("<STR_LIT>".format(host, port))<EOL>conn.request("<STR_LIT>", "<STR_LIT:/>")<EOL>conn.getresponse()<EOL>assert self.stop_request<EOL>


self._dict = None<EOL>


assert self._dict is None<EOL>self._dict = {}<EOL>

Called before first use.

        May be implemented to initialize a storage.


_logger.debug("<STR_LIT>")<EOL>self._lock.acquire_write()  <EOL>try:<EOL><INDENT>self._dict.sync()<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>


assert token in self._dict, "<STR_LIT>"<EOL>assert timeout == -<NUM_LIT:1> or timeout > <NUM_LIT:0><EOL>if timeout < <NUM_LIT:0> or timeout > LockStorageDict.LOCK_TIME_OUT_MAX:<EOL><INDENT>timeout = LockStorageDict.LOCK_TIME_OUT_MAX<EOL><DEDENT>self._lock.acquire_write()<EOL>try:<EOL><INDENT>lock = self._dict[token]<EOL>lock["<STR_LIT>"] = timeout<EOL>lock["<STR_LIT>"] = time.time() + timeout<EOL>self._dict[token] = lock<EOL>self._flush()<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>return lock<EOL>

Modify an existing lock's timeout.

        token:
            Valid lock token.
        timeout:
            Suggested lifetime in seconds (-1 for infinite).
            The real expiration time may be shorter than requested!
        Returns:
            Lock dictionary.
            Raises ValueError, if token is invalid.


self._lock.acquire_write()<EOL>try:<EOL><INDENT>lock = self._dict.get(token)<EOL>_logger.debug("<STR_LIT>".format(lock_string(lock)))<EOL>if lock is None:<EOL><INDENT>return False<EOL><DEDENT>key = "<STR_LIT>".format(lock.get("<STR_LIT:root>"))<EOL>if key in self._dict:<EOL><INDENT>tokList = self._dict[key]<EOL>if len(tokList) > <NUM_LIT:1>:<EOL><INDENT>tokList.remove(token)<EOL>self._dict[key] = tokList<EOL><DEDENT>else:<EOL><INDENT>del self._dict[key]<EOL><DEDENT><DEDENT>del self._dict[token]<EOL>self._flush()<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>return True<EOL>

Delete lock.

        Returns True on success. False, if token does not exist, or is expired.


if timeout is None:<EOL><INDENT>timeout = LockManager.LOCK_TIME_OUT_DEFAULT<EOL><DEDENT>return self.storage.refresh(token, timeout)<EOL>

Set new timeout for lock, if existing and valid.


assert hasattr(storage, "<STR_LIT>")<EOL>self._lock = ReadWriteLock()<EOL>self.storage = storage<EOL>self.storage.open()<EOL>


def check_write_permission(self, url, depth, token_list, principal):

assert compat.is_native(url)<EOL>assert depth in ("<STR_LIT:0>", "<STR_LIT>")<EOL>_logger.debug(<EOL>"<STR_LIT>".format(<EOL>url, depth, token_list, principal<EOL>)<EOL>)<EOL>errcond = DAVErrorCondition(PRECONDITION_CODE_LockConflict)<EOL>self._lock.acquire_read()<EOL>try:<EOL><INDENT>u = url<EOL>while u:<EOL><INDENT>ll = self.get_url_lock_list(u)<EOL>_logger.debug("<STR_LIT>".format(u))<EOL>for l in ll:<EOL><INDENT>_logger.debug("<STR_LIT>".format(lock_string(l)))<EOL>if u != url and l["<STR_LIT>"] != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>elif principal == l["<STR_LIT>"] and l["<STR_LIT>"] in token_list:<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>_logger.debug(<EOL>"<STR_LIT>".format(lock_string(l))<EOL>)<EOL>errcond.add_href(l["<STR_LIT:root>"])<EOL><DEDENT><DEDENT>u = util.get_uri_parent(u)<EOL><DEDENT>if depth == "<STR_LIT>":<EOL><INDENT>childLocks = self.storage.get_lock_list(<EOL>url, include_root=False, include_children=True, token_only=False<EOL>)<EOL>for l in childLocks:<EOL><INDENT>assert util.is_child_uri(url, l["<STR_LIT:root>"])<EOL>_logger.debug(<EOL>"<STR_LIT>".format(lock_string(l))<EOL>)<EOL>errcond.add_href(l["<STR_LIT:root>"])<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT>if len(errcond.hrefs) > <NUM_LIT:0>:<EOL><INDENT>raise DAVError(HTTP_LOCKED, err_condition=errcond)<EOL><DEDENT>return<EOL>

Check, if <principal> can modify <url>, otherwise raise HTTP_LOCKED.

        If modifying <url> is prevented by a lock, DAVError(HTTP_LOCKED) is
        raised. An embedded DAVErrorCondition contains the conflicting locks.

        <url> may be modified by <principal>, if it is not currently locked
        directly or indirectly (i.e. by a locked parent).
        For depth-infinity operations, <url> also must not have locked children.

        It is not enough to check whether a lock is owned by <principal>, but
        also the token must be passed with the request. Because <principal> may
        run two different applications.

        See http://www.webdav.org/specs/rfc4918.html#lock-model
            http://www.webdav.org/specs/rfc4918.html#rfc.section.7.4

        TODO: verify assumptions:
        - Parent locks WILL NOT be conflicting, if they are depth-0.
        - Exclusive child locks WILL be conflicting, even if they are owned by <principal>.

        @param url: URL that shall be modified, created, moved, or deleted
        @param depth: "0"|"infinity"
        @param token_list: list of lock tokens, that the principal submitted in If: header
        @param principal: name of the principal requesting a lock

        @return: None or raise error


url = normalize_lock_root(url)<EOL>lockList = self.storage.get_lock_list(<EOL>url, include_root=True, include_children=False, token_only=False<EOL>)<EOL>return lockList<EOL>

Return list of lock_dict, if <url> is protected by at least one direct, valid lock.

        Side effect: expired locks for this url are purged.


self.storage.delete(token)<EOL>


def get_indirect_url_lock_list(self, url, principal=None):

url = normalize_lock_root(url)<EOL>lockList = []<EOL>u = url<EOL>while u:<EOL><INDENT>ll = self.storage.get_lock_list(<EOL>u, include_root=True, include_children=False, token_only=False<EOL>)<EOL>for l in ll:<EOL><INDENT>if u != url and l["<STR_LIT>"] != "<STR_LIT>":<EOL><INDENT>continue  <EOL><DEDENT>if principal is None or principal == l["<STR_LIT>"]:<EOL><INDENT>lockList.append(l)<EOL><DEDENT><DEDENT>u = util.get_uri_parent(u)<EOL><DEDENT>return lockList<EOL>

Return a list of valid lockDicts, that protect <path> directly or indirectly.

        If a principal is given, only locks owned by this principal are returned.
        Side effect: expired locks for this path and all parents are purged.


if use_lxml:<EOL><INDENT>xml = etree.tostring(<EOL>element, encoding="<STR_LIT>", xml_declaration=True, pretty_print=pretty_print<EOL>)<EOL><DEDENT>else:<EOL><INDENT>xml = etree.tostring(element, encoding="<STR_LIT>")<EOL>if not xml.startswith(b"<STR_LIT>"):<EOL><INDENT>xml = b'<STR_LIT>' + xml<EOL><DEDENT><DEDENT>assert xml.startswith(b"<STR_LIT>")  <EOL>return xml<EOL>

Wrapper for etree.tostring, that takes care of unsupported pretty_print
    option and prepends an encoding header.


if use_lxml:<EOL><INDENT>return etree.Element("<STR_LIT>", nsmap={"<STR_LIT:D>": "<STR_LIT>"})<EOL><DEDENT>return etree.Element("<STR_LIT>")<EOL>

Wrapper for etree.Element, that takes care of unsupported nsmap option.


def make_sub_element(parent, tag, nsmap=None):

if use_lxml:<EOL><INDENT>return etree.SubElement(parent, tag, nsmap=nsmap)<EOL><DEDENT>return etree.SubElement(parent, tag)<EOL>

Wrapper for etree.SubElement, that takes care of unsupported nsmap option.


if len(element) == <NUM_LIT:0>:<EOL><INDENT>return element.text or "<STR_LIT>"  <EOL><DEDENT>stream = compat.StringIO()<EOL>for childnode in element:<EOL><INDENT>stream.write(xml_to_bytes(childnode, pretty_print=False) + "<STR_LIT:\n>")<EOL><DEDENT>s = stream.getvalue()<EOL>stream.close()<EOL>return s<EOL>

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 timeout is not None:<EOL><INDENT>endtime = time() + timeout<EOL><DEDENT>me, upgradewriter = currentThread(), False<EOL>self.__condition.acquire()<EOL>try:<EOL><INDENT>if self.__writer is me:<EOL><INDENT>self.__writercount += <NUM_LIT:1><EOL>return<EOL><DEDENT>elif me in self.__readers:<EOL><INDENT>if self.__upgradewritercount:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>upgradewriter = True<EOL>self.__upgradewritercount = self.__readers.pop(me)<EOL><DEDENT>else:<EOL><INDENT>self.__pendingwriters.append(me)<EOL><DEDENT>while True:<EOL><INDENT>if not self.__readers and self.__writer is None:<EOL><INDENT>if self.__upgradewritercount:<EOL><INDENT>if upgradewriter:<EOL><INDENT>self.__writer = me<EOL>self.__writercount = self.__upgradewritercount + <NUM_LIT:1><EOL>self.__upgradewritercount = <NUM_LIT:0><EOL>return<EOL><DEDENT><DEDENT>elif self.__pendingwriters[<NUM_LIT:0>] is me:<EOL><INDENT>self.__writer = me<EOL>self.__writercount = <NUM_LIT:1><EOL>self.__pendingwriters = self.__pendingwriters[<NUM_LIT:1>:]<EOL>return<EOL><DEDENT><DEDENT>if timeout is not None:<EOL><INDENT>remaining = endtime - time()<EOL>if remaining <= <NUM_LIT:0>:<EOL><INDENT>if upgradewriter:<EOL><INDENT>self.__readers[me] = self.__upgradewritercount<EOL>self.__upgradewritercount = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>self.__pendingwriters.remove(me)<EOL><DEDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.__condition.wait(remaining)<EOL><DEDENT>else:<EOL><INDENT>self.__condition.wait()<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self.__condition.release()<EOL><DEDENT>

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 acquire_write blocks until the
        lock request can be serviced.

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


if timeout is not None:<EOL><INDENT>endtime = time() + timeout<EOL><DEDENT>me = currentThread()<EOL>self.__condition.acquire()<EOL>try:<EOL><INDENT>if self.__writer is me:<EOL><INDENT>self.__writercount += <NUM_LIT:1><EOL>return<EOL><DEDENT>while True:<EOL><INDENT>if self.__writer is None:<EOL><INDENT>if self.__upgradewritercount or self.__pendingwriters:<EOL><INDENT>if me in self.__readers:<EOL><INDENT>self.__readers[me] += <NUM_LIT:1><EOL>return<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.__readers[me] = self.__readers.get(me, <NUM_LIT:0>) + <NUM_LIT:1><EOL>return<EOL><DEDENT><DEDENT>if timeout is not None:<EOL><INDENT>remaining = endtime - time()<EOL>if remaining <= <NUM_LIT:0>:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.__condition.wait(remaining)<EOL><DEDENT>else:<EOL><INDENT>self.__condition.wait()<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self.__condition.release()<EOL><DEDENT>

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 acquire_read blocks until the
        lock request can be serviced.

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


<EOL>if name == "<STR_LIT>":<EOL><INDENT>return self.data["<STR_LIT:key>"]<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>return self.data["<STR_LIT:title>"]<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>return self.data["<STR_LIT:status>"]<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>return self.data["<STR_LIT>"]<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>return "<STR_LIT:U+002C>".join(self.data["<STR_LIT>"])<EOL><DEDENT>elif name == "<STR_LIT>":<EOL><INDENT>return self.data["<STR_LIT:description>"]<EOL><DEDENT>return super(VirtualResource, self).get_property_value(name)<EOL>

Return the value of a property.

        See get_property_value()


def handle_copy(self, dest_path, depth_infinity):

<EOL>if "<STR_LIT>" not in dest_path:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>catType, tag, _rest = util.save_split(dest_path.strip("<STR_LIT:/>"), "<STR_LIT:/>", <NUM_LIT:2>)<EOL>assert catType == "<STR_LIT>"<EOL>if tag not in self.data["<STR_LIT>"]:<EOL><INDENT>self.data["<STR_LIT>"].append(tag)<EOL><DEDENT>return True<EOL>

Change semantic of COPY to add resource tags.


<EOL>propNameList = super(VirtualResource, self).get_property_names(is_allprop)<EOL>propNameList.extend(VirtualResource._supportedProps)<EOL>return propNameList<EOL>

Return list of supported property names in Clark Notation.

        See DAVResource.get_property_names()


<EOL>if "<STR_LIT>" not in self.path:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>catType, tag, _rest = util.save_split(self.path.strip("<STR_LIT:/>"), "<STR_LIT:/>", <NUM_LIT:2>)<EOL>assert catType == "<STR_LIT>"<EOL>assert tag in self.data["<STR_LIT>"]<EOL>self.data["<STR_LIT>"].remove(tag)<EOL>return True<EOL>

Change semantic of DELETE to remove resource tags.


<EOL>if "<STR_LIT>" not in self.path:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>if "<STR_LIT>" not in dest_path:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>catType, tag, _rest = util.save_split(self.path.strip("<STR_LIT:/>"), "<STR_LIT:/>", <NUM_LIT:2>)<EOL>assert catType == "<STR_LIT>"<EOL>assert tag in self.data["<STR_LIT>"]<EOL>self.data["<STR_LIT>"].remove(tag)<EOL>catType, tag, _rest = util.save_split(dest_path.strip("<STR_LIT:/>"), "<STR_LIT:/>", <NUM_LIT:2>)<EOL>assert catType == "<STR_LIT>"<EOL>if tag not in self.data["<STR_LIT>"]:<EOL><INDENT>self.data["<STR_LIT>"].append(tag)<EOL><DEDENT>return True<EOL>

Change semantic of MOVE to change resource tags.


self.ui.pushbuffer()<EOL>commands.log(self.ui, self.repo, limit=limit, date=None, rev=None, user=None)<EOL>res = self.ui.popbuffer().strip()<EOL>logList = []<EOL>for logentry in res.split("<STR_LIT>"):<EOL><INDENT>log = {}<EOL>logList.append(log)<EOL>for line in logentry.split("<STR_LIT:\n>"):<EOL><INDENT>k, v = line.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>assert k in ("<STR_LIT>", "<STR_LIT>", "<STR_LIT:user>", "<STR_LIT:date>", "<STR_LIT>")<EOL>log[k.strip()] = v.strip()<EOL><DEDENT>log["<STR_LIT>"] = util.parse_time_string(log["<STR_LIT:date>"])<EOL>local_id, unid = log["<STR_LIT>"].split("<STR_LIT::>")<EOL>log["<STR_LIT>"] = int(local_id)<EOL>log["<STR_LIT>"] = unid<EOL><DEDENT>return logList<EOL>

Read log entries into a list of dictionaries.


assert self.is_collection<EOL>self._check_write_access()<EOL>collpath = self._getFilePath(name)<EOL>os.mkdir(collpath)<EOL>filepath = self._getFilePath(name, "<STR_LIT>")<EOL>f = open(filepath, "<STR_LIT:w>")<EOL>f.write("<STR_LIT>")<EOL>f.close()<EOL>commands.add(self.provider.ui, self.provider.repo, filepath)<EOL>

Create a new collection as member of self.

        A dummy member is created, because Mercurial doesn't handle folders.


self._check_write_access()<EOL>filepath = self._getFilePath()<EOL>commands.remove(self.provider.ui, self.provider.repo, filepath, force=True)<EOL>


if self.rev is not None:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Return True, to prevent locking.

        See prevent_locking()


if self.rev is not None:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>

Raise HTTP_FORBIDDEN, if resource is unwritable.


destType, destHgPath = util.pop_path(dest_path)<EOL>destHgPath = destHgPath.strip("<STR_LIT:/>")<EOL>ui = self.provider.ui<EOL>repo = self.provider.repo<EOL>_logger.info("<STR_LIT>" % (self.localHgPath, destHgPath))<EOL>if self.rev is None and destType == "<STR_LIT>":<EOL><INDENT>commands.copy(ui, repo, self.localHgPath, destHgPath, force=True)<EOL><DEDENT>elif self.rev is None and destType == "<STR_LIT>":<EOL><INDENT>self._commit("<STR_LIT>" % (self.path, dest_path))<EOL><DEDENT>else:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>return True<EOL>


destType, destHgPath = util.pop_path(dest_path)<EOL>destHgPath = destHgPath.strip("<STR_LIT:/>")<EOL>ui = self.provider.ui<EOL>repo = self.provider.repo<EOL>_logger.info("<STR_LIT>" % (self.localHgPath, destHgPath))<EOL>if self.rev is None and destType == "<STR_LIT>":<EOL><INDENT>commands.rename(ui, repo, self.localHgPath, destHgPath, force=True)<EOL><DEDENT>elif self.rev is None and destType == "<STR_LIT>":<EOL><INDENT>self._commit("<STR_LIT>" % (self.path, dest_path))<EOL><DEDENT>else:<EOL><INDENT>raise DAVError(HTTP_FORBIDDEN)<EOL><DEDENT>return True<EOL>


raise DAVError(<EOL>HTTP_FORBIDDEN, err_condition=PRECONDITION_CODE_ProtectedProperty<EOL>)<EOL>

Set or remove property value.

        See DAVResource.set_property_value()


<EOL>self.provider._count_get_resource_inst_init += <NUM_LIT:1><EOL>tableName, primKey = self.provider._split_path(self.path)<EOL>display_type = "<STR_LIT>"<EOL>displayTypeComment = "<STR_LIT>"<EOL>contentType = "<STR_LIT>"<EOL>if tableName is None:<EOL><INDENT>display_type = "<STR_LIT>"<EOL><DEDENT>elif primKey is None:  <EOL><INDENT>display_type = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>contentType = "<STR_LIT>"<EOL>if primKey == "<STR_LIT>":<EOL><INDENT>display_type = "<STR_LIT>"<EOL>displayTypeComment = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>display_type = "<STR_LIT>"<EOL>displayTypeComment = "<STR_LIT>"<EOL><DEDENT><DEDENT>is_collection = primKey is None<EOL>self._cache = {<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": contentType,<EOL>"<STR_LIT>": time.time(),<EOL>"<STR_LIT>": self.name,<EOL>"<STR_LIT>": hashlib.md5().update(self.path).hexdigest(),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False,<EOL>"<STR_LIT>": {"<STR_LIT:type>": display_type, "<STR_LIT>": displayTypeComment},<EOL>}<EOL>if not is_collection:<EOL><INDENT>self._cache["<STR_LIT>"] = time.time()<EOL><DEDENT>_logger.debug("<STR_LIT>" % self.provider._count_initConnection)<EOL>

Read resource information into self._cache, for cached access.

        See DAVResource._init()


<EOL>self._count_get_resource_inst += <NUM_LIT:1><EOL>if not self.exists(path, environ):<EOL><INDENT>return None<EOL><DEDENT>_tableName, primKey = self._split_path(path)<EOL>is_collection = primKey is None<EOL>return MySQLBrowserResource(self, path, is_collection, environ)<EOL>

Return info dictionary for path.

        See get_resource_inst()


members = []<EOL>conn = self.provider._init_connection()<EOL>try:<EOL><INDENT>tableName, primKey = self.provider._split_path(self.path)<EOL>if tableName is None:<EOL><INDENT>retlist = self.provider._list_tables(conn)<EOL>for name in retlist:<EOL><INDENT>members.append(<EOL>MySQLBrowserResource(<EOL>self.provider,<EOL>util.join_uri(self.path, name),<EOL>True,<EOL>self.environ,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>elif primKey is None:<EOL><INDENT>pri_key = self.provider._find_primary_key(conn, tableName)<EOL>if pri_key is not None:<EOL><INDENT>retlist = self.provider._list_fields(conn, tableName, pri_key)<EOL>for name in retlist:<EOL><INDENT>members.append(<EOL>MySQLBrowserResource(<EOL>self.provider,<EOL>util.join_uri(self.path, name),<EOL>False,<EOL>self.environ,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>members.insert(<EOL><NUM_LIT:0>,<EOL>MySQLBrowserResource(<EOL>self.provider,<EOL>util.join_uri(self.path, "<STR_LIT>"),<EOL>False,<EOL>self.environ,<EOL>),<EOL>)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>conn.close()<EOL><DEDENT>return members<EOL>

Return list of (direct) collection member names (UTF-8 byte strings).

        See DAVResource.get_member_list()


<EOL>propNames = super(MySQLBrowserResource, self).get_property_names(is_allprop)<EOL>tableName, primKey = self.provider._split_path(self.path)<EOL>if primKey is not None:<EOL><INDENT>conn = self.provider._init_connection()<EOL>fieldlist = self.provider._get_field_list(conn, tableName)<EOL>for fieldname in fieldlist:<EOL><INDENT>propNames.append("<STR_LIT>" % (tableName, fieldname))<EOL><DEDENT>conn.close()<EOL><DEDENT>return propNames<EOL>

Return list of supported property names in Clark Notation.

        Return supported live and dead properties. (See also DAVProvider.get_property_names().)

        In addition, all table field names are returned as properties.


filestream = compat.StringIO()<EOL>tableName, primKey = self.provider._split_path(self.path)<EOL>if primKey is not None:<EOL><INDENT>conn = self.provider._init_connection()<EOL>listFields = self.provider._get_field_list(conn, tableName)<EOL>csvwriter = csv.DictWriter(filestream, listFields, extrasaction="<STR_LIT:ignore>")<EOL>dictFields = {}<EOL>for field_name in listFields:<EOL><INDENT>dictFields[field_name] = field_name<EOL><DEDENT>csvwriter.writerow(dictFields)<EOL>if primKey == "<STR_LIT>":<EOL><INDENT>cursor = conn.cursor(MySQLdb.cursors.DictCursor)<EOL>cursor.execute("<STR_LIT>" + self.provider._db + "<STR_LIT:.>" + tableName)<EOL>result_set = cursor.fetchall()<EOL>for row in result_set:<EOL><INDENT>csvwriter.writerow(row)<EOL><DEDENT>cursor.close()<EOL><DEDENT>else:<EOL><INDENT>row = self.provider._get_record_by_primary_key(conn, tableName, primKey)<EOL>if row is not None:<EOL><INDENT>csvwriter.writerow(row)<EOL><DEDENT><DEDENT>conn.close()<EOL><DEDENT>filestream.seek(<NUM_LIT:0>)<EOL>return filestream<EOL>

Open content as a stream for reading.

        See DAVResource.get_content()


def run_wsgidav_server(with_auth, with_ssl, provider=None, **kwargs):

package_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "<STR_LIT:..>"))<EOL>share_path = os.path.join(gettempdir(), "<STR_LIT>")<EOL>if not os.path.exists(share_path):<EOL><INDENT>os.mkdir(share_path)<EOL><DEDENT>if provider is None:<EOL><INDENT>provider = FilesystemProvider(share_path)<EOL><DEDENT>config = {<EOL>"<STR_LIT:host>": "<STR_LIT:127.0.0.1>",<EOL>"<STR_LIT:port>": <NUM_LIT>,<EOL>"<STR_LIT>": {"<STR_LIT:/>": provider},<EOL>"<STR_LIT>": {"<STR_LIT>": None},<EOL>"<STR_LIT>": {"<STR_LIT>": {"<STR_LIT:*>": True}},  <EOL>"<STR_LIT>": <NUM_LIT:1>,<EOL>"<STR_LIT>": [],<EOL>"<STR_LIT>": True,  <EOL>"<STR_LIT>": True,  <EOL>}<EOL>if with_auth:<EOL><INDENT>config["<STR_LIT>"].update(<EOL>{"<STR_LIT>": True, "<STR_LIT>": False, "<STR_LIT>": False}<EOL>)<EOL>config["<STR_LIT>"].update(<EOL>{<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:*>": {<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:password>": "<STR_LIT>",<EOL>"<STR_LIT:description>": "<STR_LIT>",<EOL>"<STR_LIT>": [],<EOL>},<EOL>"<STR_LIT>": {<EOL>"<STR_LIT:password>": "<STR_LIT>",<EOL>"<STR_LIT:description>": "<STR_LIT>",<EOL>"<STR_LIT>": [],<EOL>},<EOL>}<EOL>}<EOL>}<EOL>)<EOL><DEDENT>if with_ssl:<EOL><INDENT>config.update(<EOL>{<EOL>"<STR_LIT>": os.path.join(<EOL>package_path, "<STR_LIT>"<EOL>),<EOL>"<STR_LIT>": os.path.join(<EOL>package_path, "<STR_LIT>"<EOL>),<EOL>"<STR_LIT>": None,<EOL>}<EOL>)<EOL><DEDENT>util.init_logging(config)<EOL>if kwargs.get("<STR_LIT>"):<EOL><INDENT>config["<STR_LIT>"] = kwargs["<STR_LIT>"]<EOL><DEDENT>app = WsgiDAVApp(config)<EOL>from wsgidav.server.server_cli import _run_cheroot<EOL>_run_cheroot(app, config, "<STR_LIT>")<EOL>

Start blocking WsgiDAV server (called as a separate process).


__tracebackhide__ = True<EOL>res = self.response<EOL>full_status = "<STR_LIT>" % (res.status_code, res.reason)<EOL>content_length = int(res.headers.get("<STR_LIT>", <NUM_LIT:0>))<EOL>if content_length and len(res.content) != content_length:<EOL><INDENT>raise AppError(<EOL>"<STR_LIT>"<EOL>% (content_length, len(res.content))<EOL>)<EOL><DEDENT>if status == "<STR_LIT:*>":<EOL><INDENT>return<EOL><DEDENT>if isinstance(status, (list, tuple)):<EOL><INDENT>if res.status_code not in status:<EOL><INDENT>raise AppError(<EOL>"<STR_LIT>".format(<EOL>full_status,<EOL>"<STR_LIT:U+002CU+0020>".join(map(str, status)),<EOL>self.request["<STR_LIT>"],<EOL>self.request["<STR_LIT:path>"],<EOL>res.content,<EOL>)<EOL>)<EOL><DEDENT>return<EOL><DEDENT>if status is None:<EOL><INDENT>if res.status_code >= <NUM_LIT:200> and res.status_code < <NUM_LIT>:<EOL><INDENT>return<EOL><DEDENT>raise AssertionError(<EOL>"<STR_LIT>".format(<EOL>full_status,<EOL>self.request["<STR_LIT>"],<EOL>self.request["<STR_LIT:path>"],<EOL>res.content,<EOL>)<EOL>)<EOL><DEDENT>if status != res.status_code:<EOL><INDENT>raise AppError("<STR_LIT>" % (full_status, status))<EOL><DEDENT>

Raise an error, if self.response doesn"t match expected status.

        Inspired by paste.fixture


def propfind(<EOL>self, path, properties="<STR_LIT>", namespace="<STR_LIT>", depth=None, headers=None<EOL>):

<EOL>root = ElementTree.Element("<STR_LIT>")<EOL>if is_native(properties):<EOL><INDENT>ElementTree.SubElement(root, "<STR_LIT>" % properties)<EOL><DEDENT>else:<EOL><INDENT>props = ElementTree.SubElement(root, "<STR_LIT>")<EOL>object_to_etree(props, properties, namespace=namespace)<EOL><DEDENT>tree = ElementTree.ElementTree(root)<EOL>body = self._tree_to_binary_body(tree)<EOL>if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>if depth is not None:<EOL><INDENT>headers["<STR_LIT>"] = depth<EOL><DEDENT>headers["<STR_LIT:Content-Type>"] = '<STR_LIT>'<EOL>self._request("<STR_LIT>", path, body=body, headers=headers)<EOL>if self.response is not None and hasattr(self.response, "<STR_LIT>") is True:<EOL><INDENT>property_responses = {}<EOL>for response in self.response.tree:<EOL><INDENT>property_href = response.find("<STR_LIT>")<EOL>property_stat = response.find("<STR_LIT>")<EOL>def parse_props(props):<EOL><INDENT>property_dict = {}<EOL>for prop in props:<EOL><INDENT>if prop.tag.find("<STR_LIT>") is not -<NUM_LIT:1>:<EOL><INDENT>name = prop.tag.split("<STR_LIT:}>")[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>name = prop.tag<EOL><DEDENT>if len(list(prop)):<EOL><INDENT>property_dict[name] = parse_props(prop)<EOL><DEDENT>else:<EOL><INDENT>property_dict[name] = prop.text<EOL><DEDENT><DEDENT>return property_dict<EOL><DEDENT>if property_href is not None and property_stat is not None:<EOL><INDENT>property_dict = parse_props(property_stat.find("<STR_LIT>"))<EOL>property_responses[property_href.text] = property_dict<EOL><DEDENT><DEDENT>return property_responses<EOL><DEDENT>

Property find. If properties arg is unspecified it defaults to 'allprop'.


def unlock(self, path, token, headers=None):

if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>headers["<STR_LIT>"] = "<STR_LIT>" % token<EOL>self._request("<STR_LIT>", path, body=None, headers=headers)<EOL>


<EOL>body = BytesIO()<EOL>tree.write(body)<EOL>body = body.getvalue()  <EOL>body = b'<STR_LIT>' + body<EOL>assert is_bytes(body)<EOL>return body<EOL>


def copy_collection(<EOL>self, source, destination, depth="<STR_LIT>", overwrite=True, headers=None<EOL>):

body = (<EOL>b'<STR_LIT>'<EOL>b'<STR_LIT>'<EOL>b"<STR_LIT>"<EOL>)<EOL>if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>headers["<STR_LIT:Content-Type>"] = '<STR_LIT>'<EOL>self.copy(<EOL>source,<EOL>destination,<EOL>body=body,<EOL>depth=depth,<EOL>overwrite=overwrite,<EOL>headers=headers,<EOL>)<EOL>

Copy DAV collection.

        Note: support for the "propertybehavior" request body for COPY and MOVE
              has been removed with RFC4918


def put(self, path, body=None, f=None, headers=None):

assert body is None or is_bytes(body)<EOL>if f is not None:<EOL><INDENT>body = f.read()<EOL><DEDENT>self._request("<STR_LIT>", path, body=body, headers=headers)<EOL>


def proppatch(<EOL>self, path, set_props=None, remove_props=None, namespace="<STR_LIT>", headers=None<EOL>):

root = ElementTree.Element("<STR_LIT>")<EOL>if set_props is not None:<EOL><INDENT>prop_set = ElementTree.SubElement(root, "<STR_LIT>")<EOL>for p in set_props:<EOL><INDENT>prop_prop = ElementTree.SubElement(prop_set, "<STR_LIT>")<EOL>object_to_etree(prop_prop, p, namespace=namespace)<EOL><DEDENT><DEDENT>if remove_props is not None:<EOL><INDENT>prop_remove = ElementTree.SubElement(root, "<STR_LIT>")<EOL>for p in remove_props:<EOL><INDENT>prop_prop = ElementTree.SubElement(prop_remove, "<STR_LIT>")<EOL>object_to_etree(prop_prop, p, namespace=namespace)<EOL><DEDENT><DEDENT>tree = ElementTree.ElementTree(root)<EOL>body = self._tree_to_binary_body(tree)<EOL>if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>headers["<STR_LIT:Content-Type>"] = '<STR_LIT>'<EOL>self._request("<STR_LIT>", path, body=body, headers=headers)<EOL>

Patch properties on a DAV resource.

        If namespace is not specified, the DAV namespace is used for all properties.


root = ElementTree.Element("<STR_LIT>")<EOL>object_to_etree(<EOL>root,<EOL>{"<STR_LIT>": lock_type, "<STR_LIT>": lock_scope, "<STR_LIT>": {"<STR_LIT>": owner}},<EOL>namespace="<STR_LIT>",<EOL>)<EOL>tree = ElementTree.ElementTree(root)<EOL>if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>if depth is not None:<EOL><INDENT>headers["<STR_LIT>"] = depth<EOL><DEDENT>headers["<STR_LIT:Content-Type>"] = '<STR_LIT>'<EOL>headers["<STR_LIT>"] = "<STR_LIT>"<EOL>body = self._tree_to_binary_body(tree)<EOL>self._request("<STR_LIT>", path, body=body, headers=headers)<EOL>locks = self.response.tree.findall("<STR_LIT>")<EOL>lock_list = []<EOL>for lock in locks:<EOL><INDENT>lock_list.append(lock[<NUM_LIT:0>].text.strip().strip("<STR_LIT:\n>"))<EOL><DEDENT>return lock_list<EOL>


self._request("<STR_LIT>", path=path, headers=headers)<EOL>


<EOL>assert body is None or is_bytes(body)<EOL>if headers is None:<EOL><INDENT>headers = {"<STR_LIT>": destination}<EOL><DEDENT>else:<EOL><INDENT>headers["<STR_LIT>"] = self._url.geturl() + destination<EOL><DEDENT>if overwrite is False:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT:F>"<EOL><DEDENT>headers["<STR_LIT>"] = depth<EOL>self._request("<STR_LIT>", source, body=body, headers=headers)<EOL>


self._request("<STR_LIT>", path, headers=headers)<EOL>


def move_collection(<EOL>self, source, destination, depth="<STR_LIT>", overwrite=True, headers=None<EOL>):

body = (<EOL>b'<STR_LIT>'<EOL>b'<STR_LIT>'<EOL>b"<STR_LIT>"<EOL>)<EOL>if headers is None:<EOL><INDENT>headers = {}<EOL><DEDENT>headers["<STR_LIT:Content-Type>"] = '<STR_LIT>'<EOL>self.move(<EOL>source, destination, body, depth=depth, overwrite=overwrite, headers=headers<EOL>)<EOL>

Move DAV collection and copy all properties.

        Note: support for the "propertybehavior" request body for COPY and MOVE
              has been removed with RFC4918


def post(self, path, body=None, headers=None):

assert body is None or is_bytes(body)<EOL>self._request("<STR_LIT:POST>", path, body=body, headers=headers)<EOL>


def _isLockResultFault(self, lock, conflictList, status=None):

try:<EOL><INDENT>if lock is not None:<EOL><INDENT>return False<EOL><DEDENT>if len(conflictList) < <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT>resultTuple = conflictList[<NUM_LIT:0>]<EOL>if (<EOL>len(resultTuple) != <NUM_LIT:2><EOL>or not self._isLockDict(resultTuple[<NUM_LIT:0>])<EOL>or not isinstance(resultTuple[<NUM_LIT:1>], DAVError)<EOL>):<EOL><INDENT>return False<EOL><DEDENT>elif status and status != DAVError.value:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>

Return True, if it is a valid result tuple containing a DAVError.


Wrapper for lm.acquire, that returns None instead of raising DAVError.


pieces = []<EOL>_EncodeVarint(pieces.append, value)<EOL>return b"<STR_LIT>".join(pieces)<EOL>

Encode the given integer as a varint and return the bytes.  This is only
    called at startup time so it doesn't need to be fast.


def SpecificSizer(field_number, is_repeated, is_packed):<EOL><INDENT>tag_size = _TagSize(field_number)<EOL>if is_packed:<EOL><INDENT>local_VarintSize = _VarintSize<EOL>def PackedFieldSize(value):<EOL><INDENT>result = <NUM_LIT:0><EOL>for element in value:<EOL><INDENT>result += compute_value_size(modify_value(element))<EOL><DEDENT>return result + local_VarintSize(result) + tag_size<EOL><DEDENT>return PackedFieldSize<EOL><DEDENT>elif is_repeated:<EOL><INDENT>def RepeatedFieldSize(value):<EOL><INDENT>result = tag_size * len(value)<EOL>for element in value:<EOL><INDENT>result += compute_value_size(modify_value(element))<EOL><DEDENT>return result<EOL><DEDENT>return RepeatedFieldSize<EOL><DEDENT>else:<EOL><INDENT>def FieldSize(value):<EOL><INDENT>return tag_size + compute_value_size(modify_value(value))<EOL><DEDENT>return FieldSize<EOL><DEDENT><DEDENT>return SpecificSizer<EOL>

Like SimpleSizer, but modify_value is invoked on each value before it is
    passed to compute_value_size.  modify_value is typically ZigZagEncode.


<EOL>message_type = field_descriptor.message_type<EOL>message_sizer = MessageSizer(field_descriptor.number, False, False)<EOL>def FieldSize(map_value):<EOL><INDENT>total = <NUM_LIT:0><EOL>for key in map_value:<EOL><INDENT>value = map_value[key]<EOL>entry_msg = message_type._concrete_class(key=key, value=value)<EOL>total += message_sizer(entry_msg)<EOL><DEDENT>return total<EOL><DEDENT>return FieldSize<EOL>


return _VarintBytes(wire_format.PackTag(field_number, wire_type))<EOL>

Encode the given tag and return the bytes.  Only called at startup.


def EncodeVarint(write, value):<EOL><INDENT>bits = value & <NUM_LIT><EOL>value >>= <NUM_LIT:7><EOL>while value:<EOL><INDENT>write(six.int2byte(<NUM_LIT>|bits))<EOL>bits = value & <NUM_LIT><EOL>value >>= <NUM_LIT:7><EOL><DEDENT>return write(six.int2byte(bits))<EOL><DEDENT>return EncodeVarint<EOL>

Return an encoder for a basic varint value (does not include tag).


def StringSizer(field_number, is_repeated, is_packed):

tag_size = _TagSize(field_number)<EOL>local_VarintSize = _VarintSize<EOL>local_len = len<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>def RepeatedFieldSize(value):<EOL><INDENT>result = tag_size * len(value)<EOL>for element in value:<EOL><INDENT>l = local_len(element.encode('<STR_LIT:utf-8>'))<EOL>result += local_VarintSize(l) + l<EOL><DEDENT>return result<EOL><DEDENT>return RepeatedFieldSize<EOL><DEDENT>else:<EOL><INDENT>def FieldSize(value):<EOL><INDENT>l = local_len(value.encode('<STR_LIT:utf-8>'))<EOL>return tag_size + local_VarintSize(l) + l<EOL><DEDENT>return FieldSize<EOL><DEDENT>


def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value):

def SpecificEncoder(field_number, is_repeated, is_packed):<EOL><INDENT>if is_packed:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>local_EncodeVarint = _EncodeVarint<EOL>def EncodePackedField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>size = <NUM_LIT:0><EOL>for element in value:<EOL><INDENT>size += compute_value_size(modify_value(element))<EOL><DEDENT>local_EncodeVarint(write, size)<EOL>for element in value:<EOL><INDENT>encode_value(write, modify_value(element))<EOL><DEDENT><DEDENT>return EncodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(tag_bytes)<EOL>encode_value(write, modify_value(element))<EOL><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>return encode_value(write, modify_value(value))<EOL><DEDENT>return EncodeField<EOL><DEDENT><DEDENT>return SpecificEncoder<EOL>

Like SimpleEncoder but additionally invokes modify_value on every value
    before passing it to encode_value.  Usually modify_value is ZigZagEncode.


def GroupEncoder(field_number, is_repeated, is_packed):

start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)<EOL>end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(start_tag)<EOL>element._InternalSerialize(write)<EOL>write(end_tag)<EOL><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def EncodeField(write, value):<EOL><INDENT>write(start_tag)<EOL>value._InternalSerialize(write)<EOL>return write(end_tag)<EOL><DEDENT>return EncodeField<EOL><DEDENT>


start_bytes = b"<STR_LIT>".join([<EOL>TagBytes(<NUM_LIT:1>, wire_format.WIRETYPE_START_GROUP),<EOL>TagBytes(<NUM_LIT:2>, wire_format.WIRETYPE_VARINT),<EOL>_VarintBytes(field_number),<EOL>TagBytes(<NUM_LIT:3>, wire_format.WIRETYPE_LENGTH_DELIMITED)])<EOL>end_bytes = TagBytes(<NUM_LIT:1>, wire_format.WIRETYPE_END_GROUP)<EOL>local_EncodeVarint = _EncodeVarint<EOL>def EncodeField(write, value):<EOL><INDENT>write(start_bytes)<EOL>local_EncodeVarint(write, value.ByteSize())<EOL>value._InternalSerialize(write)<EOL>return write(end_bytes)<EOL><DEDENT>return EncodeField<EOL>

Encoder for extensions of MessageSet.

    The message set message looks like this:
      message MessageSet {
        repeated group Item = 1 {
          required int32 type_id = 2;
          required string message = 3;
        }
      }


def _SimpleEncoder(wire_type, encode_value, compute_value_size):

def SpecificEncoder(field_number, is_repeated, is_packed):<EOL><INDENT>if is_packed:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>local_EncodeVarint = _EncodeVarint<EOL>def EncodePackedField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>size = <NUM_LIT:0><EOL>for element in value:<EOL><INDENT>size += compute_value_size(element)<EOL><DEDENT>local_EncodeVarint(write, size)<EOL>for element in value:<EOL><INDENT>encode_value(write, element)<EOL><DEDENT><DEDENT>return EncodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(tag_bytes)<EOL>encode_value(write, element)<EOL><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>return encode_value(write, value)<EOL><DEDENT>return EncodeField<EOL><DEDENT><DEDENT>return SpecificEncoder<EOL>

Return a constructor for an encoder for fields of a particular type.

    Args:
        wire_type:  The field's wire type, for encoding tags.
        encode_value:  A function which encodes an individual value, e.g.
          _EncodeVarint().
        compute_value_size:  A function which computes the size of an individual
          value, e.g. _VarintSize().


<EOL>message_type = field_descriptor.message_type<EOL>encode_message = MessageEncoder(field_descriptor.number, False, False)<EOL>def EncodeField(write, value):<EOL><INDENT>for key in value:<EOL><INDENT>entry_msg = message_type._concrete_class(key=key, value=value[key])<EOL>encode_message(write, entry_msg)<EOL><DEDENT><DEDENT>return EncodeField<EOL>

Encoder for extensions of MessageSet.

    Maps always have a wire format like this:
      message MapEntry {
        key_type key = 1;
        value_type value = 2;
      }
      repeated MapEntry map = N;


value_size = struct.calcsize(format)<EOL>def SpecificEncoder(field_number, is_repeated, is_packed):<EOL><INDENT>local_struct_pack = struct.pack<EOL>if is_packed:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>local_EncodeVarint = _EncodeVarint<EOL>def EncodePackedField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>local_EncodeVarint(write, len(value) * value_size)<EOL>for element in value:<EOL><INDENT>write(local_struct_pack(format, element))<EOL><DEDENT><DEDENT>return EncodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(tag_bytes)<EOL>write(local_struct_pack(format, element))<EOL><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>return write(local_struct_pack(format, value))<EOL><DEDENT>return EncodeField<EOL><DEDENT><DEDENT>return SpecificEncoder<EOL>

Return a constructor for an encoder for a fixed-width field.

    Args:
        wire_type:  The field's wire type, for encoding tags.
        format:  The format string to pass to struct.pack().


def MessageEncoder(field_number, is_repeated, is_packed):

tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>local_EncodeVarint = _EncodeVarint<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(tag)<EOL>local_EncodeVarint(write, element.ByteSize())<EOL>element._InternalSerialize(write)<EOL><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def EncodeField(write, value):<EOL><INDENT>write(tag)<EOL>local_EncodeVarint(write, value.ByteSize())<EOL>return value._InternalSerialize(write)<EOL><DEDENT>return EncodeField<EOL><DEDENT>


value_size = struct.calcsize(format)<EOL>if value_size == <NUM_LIT:4>:<EOL><INDENT>def EncodeNonFiniteOrRaise(write, value):<EOL><INDENT>if value == _POS_INF:<EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>elif value == _NEG_INF:<EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>elif value != value:           <EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>elif value_size == <NUM_LIT:8>:<EOL><INDENT>def EncodeNonFiniteOrRaise(write, value):<EOL><INDENT>if value == _POS_INF:<EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>elif value == _NEG_INF:<EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>elif value != value:                         <EOL><INDENT>write(b'<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % value_size)<EOL><DEDENT>def SpecificEncoder(field_number, is_repeated, is_packed):<EOL><INDENT>local_struct_pack = struct.pack<EOL>if is_packed:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>local_EncodeVarint = _EncodeVarint<EOL>def EncodePackedField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>local_EncodeVarint(write, len(value) * value_size)<EOL>for element in value:<EOL><INDENT>try:<EOL><INDENT>write(local_struct_pack(format, element))<EOL><DEDENT>except SystemError:<EOL><INDENT>EncodeNonFiniteOrRaise(write, element)<EOL><DEDENT><DEDENT><DEDENT>return EncodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeRepeatedField(write, value):<EOL><INDENT>for element in value:<EOL><INDENT>write(tag_bytes)<EOL>try:<EOL><INDENT>write(local_struct_pack(format, element))<EOL><DEDENT>except SystemError:<EOL><INDENT>EncodeNonFiniteOrRaise(write, element)<EOL><DEDENT><DEDENT><DEDENT>return EncodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>tag_bytes = TagBytes(field_number, wire_type)<EOL>def EncodeField(write, value):<EOL><INDENT>write(tag_bytes)<EOL>try:<EOL><INDENT>write(local_struct_pack(format, value))<EOL><DEDENT>except SystemError:<EOL><INDENT>EncodeNonFiniteOrRaise(write, value)<EOL><DEDENT><DEDENT>return EncodeField<EOL><DEDENT><DEDENT>return SpecificEncoder<EOL>

Return a constructor for an encoder for float fields.

    This is like StructPackEncoder, but catches errors that may be due to
    passing non-finite floating-point values to struct.pack, and makes a
    second attempt to encode those values.

    Args:
        wire_type:  The field's wire type, for encoding tags.
        format:  The format string to pass to struct.pack().


if value <= <NUM_LIT>: return <NUM_LIT:1><EOL>if value <= <NUM_LIT>: return <NUM_LIT:2><EOL>if value <= <NUM_LIT>: return <NUM_LIT:3><EOL>if value <= <NUM_LIT>: return <NUM_LIT:4><EOL>if value <= <NUM_LIT>: return <NUM_LIT:5><EOL>if value <= <NUM_LIT>: return <NUM_LIT:6><EOL>if value <= <NUM_LIT>: return <NUM_LIT:7><EOL>if value <= <NUM_LIT>: return <NUM_LIT:8><EOL>if value <= <NUM_LIT>: return <NUM_LIT:9><EOL>return <NUM_LIT:10><EOL>


return self.values.add().list_value<EOL>

Appends and returns a list value as the next value in the list.


self.FromDatetime(datetime.utcnow())<EOL>


return timedelta(<EOL>seconds=self.seconds, microseconds=_RoundTowardZero(<EOL>self.nanos, _NANOS_PER_MICROSECOND))<EOL>


if not node:<EOL><INDENT>self.AddPath(prefix)<EOL><DEDENT>for name in node:<EOL><INDENT>child_path = prefix + '<STR_LIT:.>' + name<EOL>self.AddLeafNodes(child_path, node[name])<EOL><DEDENT>

Adds leaf nodes begin with prefix to this tree.


return self.fields[key].struct_value<EOL>

Returns a struct for this key, creating if it didn't exist already.


def MergeMessage(<EOL>self, source, destination,<EOL>replace_message_field=False, replace_repeated_field=False):

tree = _FieldMaskTree(self)<EOL>tree.MergeMessage(<EOL>source, destination, replace_message_field, replace_repeated_field)<EOL>

Merges fields specified in FieldMask from source to destination.

        Args:
          source: Source message.
          destination: The destination message to be merged into.
          replace_message_field: Replace message field if True. Merge message
              field if False.
          replace_repeated_field: Replace repeated field if True. Append
              elements of repeated field if False.


def MergeMessage(<EOL>self, source, destination,<EOL>replace_message, replace_repeated):

_MergeMessage(<EOL>self._root, source, destination, replace_message, replace_repeated)<EOL>

Merge all fields specified by this tree from source to destination.


self.seconds = micros // _MICROS_PER_SECOND<EOL>self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND<EOL>

Converts microseconds since epoch to Timestamp.


self.Clear()<EOL>for path in value.split('<STR_LIT:U+002C>'):<EOL><INDENT>self.paths.append(path)<EOL><DEDENT>

Converts string to FieldMask according to proto3 JSON spec.


return self.seconds * _NANOS_PER_SECOND + self.nanos<EOL>

Converts Timestamp to nanoseconds since epoch.


self._NormalizeDuration(<EOL>micros // _MICROS_PER_SECOND,<EOL>(micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND)<EOL>


tree = _FieldMaskTree(mask)<EOL>tree.ToFieldMask(self)<EOL>

Converts a FieldMask to the canonical form.

        Removes paths that are covered by another path. For example,
        "foo.bar" is covered by "foo" and will be removed if "foo"
        is also in the FieldMask. Then sorts all paths in alphabetical order.

        Args:
          mask: The original FieldMask to be converted.


return self.fields[key].list_value<EOL>

Returns a list for this key, creating if it didn't exist already.


self.seconds = millis // _MILLIS_PER_SECOND<EOL>self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND<EOL>

Converts milliseconds since epoch to Timestamp.


self.seconds = seconds<EOL>self.nanos = <NUM_LIT:0><EOL>

Converts seconds since epoch to Timestamp.


descriptor = msg.DESCRIPTOR<EOL>if not self.Is(descriptor):<EOL><INDENT>return False<EOL><DEDENT>msg.ParseFromString(self.value)<EOL>return True<EOL>

Unpacks the current Any message into specified message.


return self.seconds<EOL>


return [(value_descriptor.name, value_descriptor.number)<EOL>for value_descriptor in self._enum_type.values]<EOL>

Return a list of the (name, value) pairs of the enum.

        These are returned in the order they were defined in the .proto file.


if name in self._enum_type.values_by_name:<EOL><INDENT>return self._enum_type.values_by_name[name].number<EOL><DEDENT>raise ValueError('<STR_LIT>' % (<EOL>self._enum_type.name, name))<EOL>

Returns the value coresponding to the given enum name.


return [value_descriptor.name<EOL>for value_descriptor in self._enum_type.values]<EOL>

Return a list of the string names in the enum.

        These are returned in the order they were defined in the .proto file.


if not isinstance(proposed_value, self._acceptable_types):<EOL><INDENT>message = ('<STR_LIT>' %<EOL>(proposed_value, type(proposed_value), self._acceptable_types))<EOL>raise TypeError(message)<EOL><DEDENT>return proposed_value<EOL>

Type check the provided value and return it.

        The returned value might have been normalized to another type.


def _RaiseInvalidWireType(buffer, pos, end):

raise _DecodeError('<STR_LIT>')<EOL>

Skip function for unknown wire types.  Raises an exception.


start = pos<EOL>while six.indexbytes(buffer, pos) & <NUM_LIT>:<EOL><INDENT>pos += <NUM_LIT:1><EOL><DEDENT>pos += <NUM_LIT:1><EOL>return (buffer[start:pos], pos)<EOL>

Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.

    We return the raw bytes of the tag rather than decoding them.  The raw
    bytes can then be used to look up the proper decoder.  This effectively allows
    us to trade some work that would be done in pure-python (decoding a varint)
    for work that is done in C (searching for a byte string in a hash table).
    In a low-level language it would be much cheaper to decode the varint and
    use that, but not in Python.


def DecodeVarint(buffer, pos):<EOL><INDENT>result = <NUM_LIT:0><EOL>shift = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>b = six.indexbytes(buffer, pos)<EOL>result |= ((b & <NUM_LIT>) << shift)<EOL>pos += <NUM_LIT:1><EOL>if not (b & <NUM_LIT>):<EOL><INDENT>result &= mask<EOL>result = result_type(result)<EOL>return (result, pos)<EOL><DEDENT>shift += <NUM_LIT:7><EOL>if shift >= <NUM_LIT:64>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return DecodeVarint<EOL>

Return an encoder for a basic varint value (does not include tag).

    Decoded values will be bitwise-anded with the given mask before being
    returned, e.g. to limit them to 32 bits.  The returned decoder does not
    take the usual "end" parameter -- the caller is expected to do bounds checking
    after the fact (often the caller can defer such checking until later).  The
    decoder returns a (value, new_pos) pair.


local_unpack = struct.unpack<EOL>def InnerDecode(buffer, pos):<EOL><INDENT>new_pos = pos + <NUM_LIT:8><EOL>double_bytes = buffer[pos:new_pos]<EOL>if ((double_bytes[<NUM_LIT:7>:<NUM_LIT:8>] in b'<STR_LIT>')<EOL>and (double_bytes[<NUM_LIT:6>:<NUM_LIT:7>] >= b'<STR_LIT>')<EOL>and (double_bytes[<NUM_LIT:0>:<NUM_LIT:7>] != b'<STR_LIT>')):<EOL><INDENT>return (_NAN, new_pos)<EOL><DEDENT>result = local_unpack('<STR_LIT>', double_bytes)[<NUM_LIT:0>]<EOL>return (result, new_pos)<EOL><DEDENT>return _SimpleDecoder(wire_format.WIRETYPE_FIXED64, InnerDecode)<EOL>

Returns a decoder for a double field.

    This code works around a bug in struct.unpack for not-a-number.


def DecodeVarint(buffer, pos):<EOL><INDENT>result = <NUM_LIT:0><EOL>shift = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>b = six.indexbytes(buffer, pos)<EOL>result |= ((b & <NUM_LIT>) << shift)<EOL>pos += <NUM_LIT:1><EOL>if not (b & <NUM_LIT>):<EOL><INDENT>if result > <NUM_LIT>:<EOL><INDENT>result -= (<NUM_LIT:1> << <NUM_LIT:64>)<EOL>result |= ~mask<EOL><DEDENT>else:<EOL><INDENT>result &= mask<EOL><DEDENT>result = result_type(result)<EOL>return (result, pos)<EOL><DEDENT>shift += <NUM_LIT:7><EOL>if shift >= <NUM_LIT:64>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>return DecodeVarint<EOL>

Like _VarintDecoder() but decodes signed values.


return -<NUM_LIT:1><EOL>

Skipping an END_GROUP tag returns -1 to tell the parent loop to break.


def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):

local_DecodeVarint = _DecodeVarint<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>value.append(buffer[pos:new_pos])<EOL>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>field_dict[key] = buffer[pos:new_pos]<EOL>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


def MapDecoder(field_descriptor, new_default, is_message_map):

key = field_descriptor<EOL>tag_bytes = encoder.TagBytes(field_descriptor.number,<EOL>wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>tag_len = len(tag_bytes)<EOL>local_DecodeVarint = _DecodeVarint<EOL>message_type = field_descriptor.message_type<EOL>def DecodeMap(buffer, pos, end, message, field_dict):<EOL><INDENT>submsg = message_type._concrete_class()<EOL>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(size, pos) = local_DecodeVarint(buffer, pos)<EOL>new_pos = pos + size<EOL>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>submsg.Clear()<EOL>if submsg._InternalParse(buffer, pos, new_pos) != new_pos:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if is_message_map:<EOL><INDENT>value[submsg.key].MergeFrom(submsg.value)<EOL><DEDENT>else:<EOL><INDENT>value[submsg.key] = submsg.value<EOL><DEDENT>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeMap<EOL>


def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):

end_tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_END_GROUP)<EOL>end_tag_len = len(end_tag_bytes)<EOL>assert not is_packed<EOL>if is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number,<EOL>wire_format.WIRETYPE_START_GROUP)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>pos = value.add()._InternalParse(buffer, pos, end)<EOL>new_pos = pos+end_tag_len<EOL>if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos == end:<EOL><INDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>pos = value._InternalParse(buffer, pos, end)<EOL>new_pos = pos+end_tag_len<EOL>if buffer[pos:new_pos] != end_tag_bytes or new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return new_pos<EOL><DEDENT>return DecodeField<EOL><DEDENT>


<EOL>while ord(buffer[pos:pos+<NUM_LIT:1>]) & <NUM_LIT>:<EOL><INDENT>pos += <NUM_LIT:1><EOL><DEDENT>pos += <NUM_LIT:1><EOL>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL>

Skip a varint value.  Returns the new position.


def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default):<EOL><INDENT>if is_packed:<EOL><INDENT>local_DecodeVarint = _DecodeVarint<EOL>def DecodePackedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>(endpoint, pos) = local_DecodeVarint(buffer, pos)<EOL>endpoint += pos<EOL>if endpoint > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>while pos < endpoint:<EOL><INDENT>(element, pos) = decode_value(buffer, pos)<EOL>value.append(element)<EOL><DEDENT>if pos > endpoint:<EOL><INDENT>del value[-<NUM_LIT:1>]   <EOL>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL><DEDENT>return DecodePackedField<EOL><DEDENT>elif is_repeated:<EOL><INDENT>tag_bytes = encoder.TagBytes(field_number, wire_type)<EOL>tag_len = len(tag_bytes)<EOL>def DecodeRepeatedField(buffer, pos, end, message, field_dict):<EOL><INDENT>value = field_dict.get(key)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(key, new_default(message))<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>(element, new_pos) = decode_value(buffer, pos)<EOL>value.append(element)<EOL>pos = new_pos + tag_len<EOL>if buffer[new_pos:pos] != tag_bytes or new_pos >= end:<EOL><INDENT>if new_pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return new_pos<EOL><DEDENT><DEDENT><DEDENT>return DecodeRepeatedField<EOL><DEDENT>else:<EOL><INDENT>def DecodeField(buffer, pos, end, message, field_dict):<EOL><INDENT>(field_dict[key], pos) = decode_value(buffer, pos)<EOL>if pos > end:<EOL><INDENT>del field_dict[key]  <EOL>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>return pos<EOL><DEDENT>return DecodeField<EOL><DEDENT><DEDENT>return SpecificDecoder<EOL>

Return a constructor for a decoder for fields of a particular type.

    Args:
        wire_type:  The field's wire type.
        decode_value:  A function which decodes an individual value, e.g.
          _DecodeVarint()


type_id_tag_bytes = encoder.TagBytes(<NUM_LIT:2>, wire_format.WIRETYPE_VARINT)<EOL>message_tag_bytes = encoder.TagBytes(<NUM_LIT:3>, wire_format.WIRETYPE_LENGTH_DELIMITED)<EOL>item_end_tag_bytes = encoder.TagBytes(<NUM_LIT:1>, wire_format.WIRETYPE_END_GROUP)<EOL>local_ReadTag = ReadTag<EOL>local_DecodeVarint = _DecodeVarint<EOL>local_SkipField = SkipField<EOL>def DecodeItem(buffer, pos, end, message, field_dict):<EOL><INDENT>message_set_item_start = pos<EOL>type_id = -<NUM_LIT:1><EOL>message_start = -<NUM_LIT:1><EOL>message_end = -<NUM_LIT:1><EOL>while <NUM_LIT:1>:<EOL><INDENT>(tag_bytes, pos) = local_ReadTag(buffer, pos)<EOL>if tag_bytes == type_id_tag_bytes:<EOL><INDENT>(type_id, pos) = local_DecodeVarint(buffer, pos)<EOL><DEDENT>elif tag_bytes == message_tag_bytes:<EOL><INDENT>(size, message_start) = local_DecodeVarint(buffer, pos)<EOL>pos = message_end = message_start + size<EOL><DEDENT>elif tag_bytes == item_end_tag_bytes:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>pos = SkipField(buffer, pos, end, tag_bytes)<EOL>if pos == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>if pos > end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if type_id == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>if message_start == -<NUM_LIT:1>:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT>extension = extensions_by_number.get(type_id)<EOL>if extension is not None:<EOL><INDENT>value = field_dict.get(extension)<EOL>if value is None:<EOL><INDENT>value = field_dict.setdefault(<EOL>extension, extension.message_type._concrete_class())<EOL><DEDENT>if value._InternalParse(buffer, message_start,message_end) != message_end:<EOL><INDENT>raise _DecodeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not message._unknown_fields:<EOL><INDENT>message._unknown_fields = []<EOL><DEDENT>message._unknown_fields.append((MESSAGE_SET_ITEM_TAG,<EOL>buffer[message_set_item_start:pos]))<EOL><DEDENT>return pos<EOL><DEDENT>return DecodeItem<EOL>

Returns a decoder for a MessageSet item.

    The parameter is the _extensions_by_number map for the message class.

    The message set message looks like this:
      message MessageSet {
        repeated group Item = 1 {
          required int32 type_id = 2;
          required string message = 3;
        }
      }


def __init__(self, parent_message, field):

super(_OneofListener, self).__init__(parent_message)<EOL>self._field = field<EOL>

Args:
          parent_message: The message whose _Modified() method we should call when
            we receive Modified() messages.
          field: The descriptor of the field being set in the parent message.


def SerializePartialToString(self):<EOL><INDENT>out = BytesIO()<EOL>self._InternalSerialize(out.write)<EOL>return out.getvalue()<EOL><DEDENT>cls.SerializePartialToString = SerializePartialToString<EOL>def InternalSerialize(self, write_bytes):<EOL><INDENT>for field_descriptor, field_value in self.ListFields():<EOL><INDENT>field_descriptor._encoder(write_bytes, field_value)<EOL><DEDENT>for tag_bytes, value_bytes in self._unknown_fields:<EOL><INDENT>write_bytes(tag_bytes)<EOL>write_bytes(value_bytes)<EOL><DEDENT><DEDENT>cls._InternalSerialize = InternalSerialize<EOL>


def ListFields(self):<EOL><INDENT>all_fields = [item for item in self._fields.items() if _IsPresent(item)]<EOL>all_fields.sort(key = lambda item: item[<NUM_LIT:0>].number)<EOL>return all_fields<EOL><DEDENT>cls.ListFields = ListFields<EOL>


<EOL>if isinstance(parent_message, weakref.ProxyType):<EOL><INDENT>self._parent_message_weakref = parent_message<EOL><DEDENT>else:<EOL><INDENT>self._parent_message_weakref = weakref.proxy(parent_message)<EOL><DEDENT>self.dirty = False<EOL>

Args:
          parent_message: The message whose _Modified() method we should call when
            we receive Modified() messages.


def ClearExtension(self, extension_handle):<EOL><INDENT>_VerifyExtensionHandle(self, extension_handle)<EOL>if extension_handle in self._fields:<EOL><INDENT>del self._fields[extension_handle]<EOL><DEDENT>self._Modified()<EOL><DEDENT>cls.ClearExtension = ClearExtension<EOL>


is_proto3 = (message_descriptor.syntax == "<STR_LIT>")<EOL>error_msg = _Proto3HasError if is_proto3 else _Proto2HasError<EOL>hassable_fields = {}<EOL>for field in message_descriptor.fields:<EOL><INDENT>if field.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>continue<EOL><DEDENT>if (is_proto3 and field.cpp_type != _FieldDescriptor.CPPTYPE_MESSAGE and<EOL>not field.containing_oneof):<EOL><INDENT>continue<EOL><DEDENT>hassable_fields[field.name] = field<EOL><DEDENT>if not is_proto3:<EOL><INDENT>for oneof in message_descriptor.oneofs:<EOL><INDENT>hassable_fields[oneof.name] = oneof<EOL><DEDENT><DEDENT>def HasField(self, field_name):<EOL><INDENT>try:<EOL><INDENT>field = hassable_fields[field_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError(error_msg % field_name)<EOL><DEDENT>if isinstance(field, descriptor_mod.OneofDescriptor):<EOL><INDENT>try:<EOL><INDENT>return HasField(self, self._oneofs[field].name)<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>value = self._fields.get(field)<EOL>return value is not None and value._is_present_in_parent<EOL><DEDENT>else:<EOL><INDENT>return field in self._fields<EOL><DEDENT><DEDENT><DEDENT>cls.HasField = HasField<EOL>


def __setitem__(self, extension_handle, value):

_VerifyExtensionHandle(self._extended_message, extension_handle)<EOL>if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or<EOL>extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % extension_handle.full_name)<EOL><DEDENT>type_checker = type_checkers.GetTypeChecker(extension_handle)<EOL>self._extended_message._fields[extension_handle] = (<EOL>type_checker.CheckValue(value))<EOL>self._extended_message._Modified()<EOL>

If extension_handle specifies a non-repeated, scalar extension
        field, sets the value of that field.


if item[<NUM_LIT:0>].label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>return bool(item[<NUM_LIT:1>])<EOL><DEDENT>elif item[<NUM_LIT:0>].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>return item[<NUM_LIT:1>]._is_present_in_parent<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>

Given a (FieldDescriptor, value) tuple from _fields, return true if the
    value should be included in the list returned by ListFields().


def __str__(self):<EOL><INDENT>return text_format.MessageToString(self)<EOL><DEDENT>cls.__str__ = __str__<EOL>


dictionary['<STR_LIT>'] = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL>

Adds a __slots__ entry to dictionary, containing the names of all valid
    attributes for this message type.

    Args:
      message_descriptor: A Descriptor instance describing this message type.
      dictionary: Class dictionary to which we'll add a '__slots__' entry.


def __unicode__(self):<EOL><INDENT>return text_format.MessageToString(self, as_utf8=True).decode('<STR_LIT:utf-8>')<EOL><DEDENT>cls.__unicode__ = __unicode__<EOL>


self._extended_message = extended_message<EOL>

extended_message: Message instance for which we are the Extensions dict.


def Modified(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not self._cached_byte_size_dirty:<EOL><INDENT>self._cached_byte_size_dirty = True<EOL>self._listener_for_children.dirty = True<EOL>self._is_present_in_parent = True<EOL>self._listener.Modified()<EOL><DEDENT><DEDENT>def _UpdateOneofState(self, field):<EOL><INDENT>"""<STR_LIT>"""<EOL>other_field = self._oneofs.setdefault(field.containing_oneof, field)<EOL>if other_field is not field:<EOL><INDENT>del self._fields[other_field]<EOL>self._oneofs[field.containing_oneof] = field<EOL><DEDENT><DEDENT>cls._Modified = Modified<EOL>cls.SetInParent = Modified<EOL>cls._UpdateOneofState = _UpdateOneofState<EOL>

Adds implementation of private helper methods to cls.


return self._extended_message._extensions_by_number.get(number, None)<EOL>

Tries to find a known extension with the field number.

        Args:
          number: Extension field number.

        Returns:
          Extension field descriptor.


exc = sys.exc_info()[<NUM_LIT:1>]<EOL>if len(exc.args) == <NUM_LIT:1> and type(exc) is TypeError:<EOL><INDENT>exc = TypeError('<STR_LIT>' % (str(exc), message_name, field_name))<EOL><DEDENT>six.reraise(type(exc), exc, sys.exc_info()[<NUM_LIT:2>])<EOL>

Re-raise the currently-handled TypeError with the field name added.


for enum_type in descriptor.enum_types:<EOL><INDENT>setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type))<EOL>for enum_value in enum_type.values:<EOL><INDENT>setattr(cls, enum_value.name, enum_value.number)<EOL><DEDENT><DEDENT>

Sets class-level attributes for all enum fields defined in this message.

    Also exporting a class-level object that can name enum values.

    Args:
      descriptor: Descriptor object for this message type.
      cls: Class we're constructing for this message type.


type_url = msg.type_url<EOL>db = symbol_database.Default()<EOL>if not type_url:<EOL><INDENT>return None<EOL><DEDENT>type_name = type_url.split("<STR_LIT:/>")[-<NUM_LIT:1>]<EOL>descriptor = db.pool.FindMessageTypeByName(type_name)<EOL>if descriptor is None:<EOL><INDENT>return None<EOL><DEDENT>message_class = db.GetPrototype(descriptor)<EOL>message = message_class()<EOL>message.ParseFromString(msg.value)<EOL>return message<EOL>

Unpacks Any message and returns the unpacked message.

    This internal method is differnt from public Any Unpack method which takes
    the target message as argument. _InternalUnpackAny method does not have
    target message type and need to find the message type in descriptor pool.

    Args:
      msg: An Any message to be unpacked.

    Returns:
      The unpacked message.


def __new__(cls, name, bases, dictionary):

descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY]<EOL>if descriptor.full_name in well_known_types.WKTBASES:<EOL><INDENT>bases += (well_known_types.WKTBASES[descriptor.full_name],)<EOL><DEDENT>_AddClassAttributesForNestedExtensions(descriptor, dictionary)<EOL>_AddSlots(descriptor, dictionary)<EOL>superclass = super(GeneratedProtocolMessageType, cls)<EOL>new_class = superclass.__new__(cls, name, bases, dictionary)<EOL>return new_class<EOL>

Custom allocation for runtime-generated class types.

        We override __new__ because this is apparently the only place
        where we can meaningfully set __slots__ on the class we're creating(?).
        (The interplay between metaclasses and slots is not very well-documented).

        Args:
          name: Name of the class (ignored, but required by the
            metaclass protocol).
          bases: Base classes of the class we're constructing.
            (Should be message.Message).  We ignore this field, but
            it's required by the metaclass protocol
          dictionary: The class dictionary of the class we're
            constructing.  dictionary[_DESCRIPTOR_KEY] must contain
            a Descriptor object describing this protocol message
            type.

        Returns:
          Newly-allocated class.


_VerifyExtensionHandle(self._extended_message, extension_handle)<EOL>result = self._extended_message._fields.get(extension_handle)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT>if extension_handle.label == _FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>result = extension_handle._default_constructor(self._extended_message)<EOL><DEDENT>elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>result = extension_handle.message_type._concrete_class()<EOL>try:<EOL><INDENT>result._SetListener(self._extended_message._listener_for_children)<EOL><DEDENT>except ReferenceError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return extension_handle.default_value<EOL><DEDENT>result = self._extended_message._fields.setdefault(<EOL>extension_handle, result)<EOL>return result<EOL>

Returns the current value of the given extension handle.


<EOL>proto_field_name = field.name<EOL>property_name = _PropertyName(proto_field_name)<EOL>def getter(self):<EOL><INDENT>field_value = self._fields.get(field)<EOL>if field_value is None:<EOL><INDENT>field_value = field._default_constructor(self)<EOL>field_value = self._fields.setdefault(field, field_value)<EOL><DEDENT>return field_value<EOL><DEDENT>getter.__module__ = None<EOL>getter.__doc__ = '<STR_LIT>' % proto_field_name<EOL>def setter(self, new_value):<EOL><INDENT>raise AttributeError('<STR_LIT>'<EOL>'<STR_LIT>' % proto_field_name)<EOL><DEDENT>doc = '<STR_LIT>' % proto_field_name<EOL>setattr(cls, property_name, property(getter, setter, doc=doc))<EOL>

Adds a public property for a nonrepeated, composite protocol message field.
    A composite field is a "group" or "message" field.

    Clients can use this property to get the value of the field, but cannot
    assign to the property directly.

    Args:
      field: A FieldDescriptor for this field.
      cls: The class we're constructing.


def __init__(self, message_listener, message_descriptor):

super(RepeatedCompositeFieldContainer, self).__init__(message_listener)<EOL>self._message_descriptor = message_descriptor<EOL>

Note that we pass in a descriptor instead of the generated directly,
since at the time we construct a _RepeatedCompositeFieldContainer we
haven't yet necessarily initialized the type that will be contained in the
container.

Args:
  message_listener: A MessageListener implementation.
    The RepeatedCompositeFieldContainer will call this object's
    Modified() method when it is modified.
  message_descriptor: A Descriptor instance describing the protocol type
    that should be present in this container.  We'll use the
    _concrete_class field of this descriptor when the client calls add().


def __init__(self, message_listener, message_descriptor, key_checker):

self._message_listener = message_listener<EOL>self._message_descriptor = message_descriptor<EOL>self._key_checker = key_checker<EOL>self._values = {}<EOL>

Args:
  message_listener: A MessageListener implementation.
    The ScalarMap will call this object's Modified() method when it
    is modified.
  key_checker: A type_checkers.ValueChecker instance to run on keys
    inserted into this container.
  value_checker: A type_checkers.ValueChecker instance to run on values
    inserted into this container.


if self is other:<EOL><INDENT>return True<EOL><DEDENT>if not isinstance(other, self.__class__):<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return self._values == other._values<EOL>

Compares the current instance with another one.


Appends the contents of another repeated field of the same type to this
        one, copying each individual message.


def __init__(self, message_listener, key_checker, value_checker):

self._message_listener = message_listener<EOL>self._key_checker = key_checker<EOL>self._value_checker = value_checker<EOL>self._values = {}<EOL>


self._values.insert(key, self._type_checker.CheckValue(value))<EOL>if not self._message_listener.dirty:<EOL><INDENT>self._message_listener.Modified()<EOL><DEDENT>

Inserts the item at the specified position. Similar to list.insert().


value = self._values[key]<EOL>self.__delitem__(key)<EOL>return value<EOL>

Removes and returns an item at a given index. Similar to list.pop().


if self is other:<EOL><INDENT>return True<EOL><DEDENT>if isinstance(other, self.__class__):<EOL><INDENT>return other._values == self._values<EOL><DEDENT>return other == self._values<EOL>


self._values.remove(elem)<EOL>self._message_listener.Modified()<EOL>

Removes an item from the list. Similar to list.remove().


<EOL>return not self == other<EOL>

Checks if another instance isn't equal to this one.


self._values.extend(other._values)<EOL>self._message_listener.Modified()<EOL>

Appends the contents of another repeated field of the same type to this
        one. We do not check the types of the individual fields.


out = self.out<EOL>out.write('<STR_LIT:U+0020>' * self.indent)<EOL>if self.use_field_number:<EOL><INDENT>out.write(str(field.number))<EOL><DEDENT>else:<EOL><INDENT>if field.is_extension:<EOL><INDENT>out.write('<STR_LIT:[>')<EOL>if (field.containing_type.GetOptions().message_set_wire_format and<EOL>field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and<EOL>field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):<EOL><INDENT>out.write(field.message_type.full_name)<EOL><DEDENT>else:<EOL><INDENT>out.write(field.full_name)<EOL><DEDENT>out.write('<STR_LIT:]>')<EOL><DEDENT>elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:<EOL><INDENT>out.write(field.message_type.name)<EOL><DEDENT>else:<EOL><INDENT>out.write(field.name)<EOL><DEDENT><DEDENT>if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>out.write('<STR_LIT>')<EOL><DEDENT>self.PrintFieldValue(field, value)<EOL>if self.as_one_line:<EOL><INDENT>out.write('<STR_LIT:U+0020>')<EOL><DEDENT>else:<EOL><INDENT>out.write('<STR_LIT:\n>')<EOL><DEDENT>


self._allow_multiple_scalars = False<EOL>self._ParseOrMerge(lines, message)<EOL>return message<EOL>

Parses an text representation of a protocol message into a message.


def ParseFromString(self, text, message):

if not isinstance(text, str):<EOL><INDENT>text = text.decode('<STR_LIT:utf-8>')<EOL><DEDENT>return self.ParseLines(text.split('<STR_LIT:\n>'), message)<EOL>


def Merge(text, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

return MergeLines(text.split('<STR_LIT:\n>'), message, allow_unknown_extension,<EOL>allow_field_number)<EOL>

Parses an text representation of a protocol message into a message.

    Like Parse(), but allows repeated values for a non-repeated field, and uses
    the last one.

    Args:
      text: Message text representation.
      message: A protocol buffer message to merge into.
      allow_unknown_extension: if True, skip over missing extensions and keep
        parsing
      allow_field_number: if True, both field number and field name are allowed.

    Returns:
      The same message passed as argument.

    Raises:
      ParseError: On text parsing problems.


text = self.token<EOL>if len(text) < <NUM_LIT:1> or text[<NUM_LIT:0>] not in _QUOTES:<EOL><INDENT>raise self._ParseError('<STR_LIT>' % (text,))<EOL><DEDENT>if len(text) < <NUM_LIT:2> or text[-<NUM_LIT:1>] != text[<NUM_LIT:0>]:<EOL><INDENT>raise self._ParseError('<STR_LIT>' % (text,))<EOL><DEDENT>try:<EOL><INDENT>result = text_encoding.CUnescape(text[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consume one token of a string literal.

        String literals (whether bytes or text) can come in multiple adjacent
        tokens which are automatically concatenated, like in C or Python.  This
        method only consumes one token.

        Returns:
          The token parsed.
        Raises:
          ParseError: When the wrong format data is found.


def ParseLines(lines, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

parser = _Parser(allow_unknown_extension, allow_field_number)<EOL>return parser.ParseLines(lines, message)<EOL>

Parses an text representation of a protocol message into a message.

    Args:
      lines: An iterable of lines of a message's text representation.
      message: A protocol buffer message to merge into.
      allow_unknown_extension: if True, skip over missing extensions and keep
        parsing
      allow_field_number: if True, both field number and field name are allowed.

    Returns:
      The same message passed as argument.

    Raises:
      ParseError: On text parsing problems.


if not self.TryConsume(token):<EOL><INDENT>raise self._ParseError('<STR_LIT>' % token)<EOL><DEDENT>

Consumes a piece of text.

        Args:
          token: Text to consume.

        Raises:
          ParseError: If the text couldn't be consumed.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=False, is_long=True)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes an unsigned 64bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If an unsigned 64bit integer couldn't be consumed.


def __init__(self, out, indent=<NUM_LIT:0>, as_utf8=False, as_one_line=False,<EOL>pointy_brackets=False, use_index_order=False, float_format=None,<EOL>use_field_number=False):

self.out = out<EOL>self.indent = indent<EOL>self.as_utf8 = as_utf8<EOL>self.as_one_line = as_one_line<EOL>self.pointy_brackets = pointy_brackets<EOL>self.use_index_order = use_index_order<EOL>self.float_format = float_format<EOL>self.use_field_number = use_field_number<EOL>

Initialize the Printer.

        Floating point values can be formatted compactly with 15 digits of
        precision (which is the most that IEEE 754 "double" can guarantee)
        using float_format='.15g'. To ensure that converting to text and back to a
        proto will result in an identical value, float_format='.17g' should be used.

        Args:
          out: To record the text format result.
          indent: The indent level for pretty print.
          as_utf8: Produce text output in UTF8 format.
          as_one_line: Don't introduce newlines between fields.
          pointy_brackets: If True, use angle brackets instead of curly braces for
            nesting.
          use_index_order: If True, print fields of a proto message using the order
            defined in source code instead of the field number. By default, use the
            field number order.
          float_format: If set, use this to specify floating point number formatting
            (per the "Format Specification Mini-Language"); otherwise, str() is
            used.
          use_field_number: If True, print field numbers instead of names.


<EOL>if tokenizer.TryConsumeByteString():<EOL><INDENT>while tokenizer.TryConsumeByteString():<EOL><INDENT>pass<EOL><DEDENT>return<EOL><DEDENT>if (not tokenizer.TryConsumeIdentifier() and<EOL>not tokenizer.TryConsumeInt64() and<EOL>not tokenizer.TryConsumeUint64() and<EOL>not tokenizer.TryConsumeFloat()):<EOL><INDENT>raise ParseError('<STR_LIT>' + tokenizer.token)<EOL><DEDENT>

Skips over a field value.

    Args:
      tokenizer: A tokenizer to parse the field name and values.

    Raises:
      ParseError: In case an invalid field value is found.


return ParseError('<STR_LIT>' % (<EOL>self._previous_line + <NUM_LIT:1>, self._previous_column + <NUM_LIT:1>, message))<EOL>

Creates and *returns* a ParseError for the previously read token.

        Args:
          message: A message to set for the exception.

        Returns:
          A ParseError instance.


Skips over a complete field (name and value/message).

    Args:
      tokenizer: A tokenizer to parse the field name and values.


<EOL>if tokenizer.TryConsume('<STR_LIT::>') and not tokenizer.LookingAt(<EOL>'<STR_LIT:{>') and not tokenizer.LookingAt('<STR_LIT:<>'):<EOL><INDENT>_SkipFieldValue(tokenizer)<EOL><DEDENT>else:<EOL><INDENT>_SkipFieldMessage(tokenizer)<EOL><DEDENT>

Skips over contents (value or message) of a field.

    Args:
      tokenizer: A tokenizer to parse the field name and values.


enum_descriptor = field.enum_type<EOL>try:<EOL><INDENT>number = int(value, <NUM_LIT:0>)<EOL><DEDENT>except ValueError:<EOL><INDENT>enum_value = enum_descriptor.values_by_name.get(value, None)<EOL>if enum_value is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>enum_descriptor.full_name, value))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>enum_value = enum_descriptor.values_by_number.get(number, None)<EOL>if enum_value is None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>enum_descriptor.full_name, number))<EOL><DEDENT><DEDENT>return enum_value.number<EOL>

Parse an enum value.

    The value can be specified by a number (the enum value), or by
    a string literal (the enum name).

    Args:
      field: Enum field descriptor.
      value: String value.

    Returns:
      Enum value number.

    Raises:
      ValueError: If the enum value could not be parsed.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=True, is_long=True)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes a signed 64bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If a signed 64bit integer couldn't be consumed.


def MergeLines(lines, message, allow_unknown_extension=False,<EOL>allow_field_number=False):

parser = _Parser(allow_unknown_extension, allow_field_number)<EOL>return parser.MergeLines(lines, message)<EOL>


def MessageToString(message, as_utf8=False, as_one_line=False,<EOL>pointy_brackets=False, use_index_order=False,<EOL>float_format=None, use_field_number=False):

out = TextWriter(as_utf8)<EOL>printer = _Printer(out, <NUM_LIT:0>, as_utf8, as_one_line,<EOL>pointy_brackets, use_index_order, float_format,<EOL>use_field_number)<EOL>printer.PrintMessage(message)<EOL>result = out.getvalue()<EOL>out.close()<EOL>if as_one_line:<EOL><INDENT>return result.rstrip()<EOL><DEDENT>return result<EOL>

Convert protobuf message to text format.

    Floating point values can be formatted compactly with 15 digits of
    precision (which is the most that IEEE 754 "double" can guarantee)
    using float_format='.15g'. To ensure that converting to text and back to a
    proto will result in an identical value, float_format='.17g' should be used.

    Args:
      message: The protocol buffers message.
      as_utf8: Produce text output in UTF8 format.
      as_one_line: Don't introduce newlines between fields.
      pointy_brackets: If True, use angle brackets instead of curly braces for
        nesting.
      use_index_order: If True, print fields of a proto message using the order
        defined in source code instead of the field number. By default, use the
        field number order.
      float_format: If set, use this to specify floating point number formatting
        (per the "Format Specification Mini-Language"); otherwise, str() is used.
      use_field_number: If True, print field numbers instead of names.

    Returns:
      A string of the text formatted protocol buffer message.