id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
224,700
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
CookieJar.clear
def clear(self, domain=None, path=None, name=None): """Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three arguments, then the cookie with the specified name, path and domain is removed. Raises KeyError if no matching cookie exists. """ if name is not None: if (domain is None) or (path is None): raise ValueError( "domain and path must be given to remove a cookie by name") del self._cookies[domain][path][name] elif path is not None: if domain is None: raise ValueError( "domain must be given to remove cookies by path") del self._cookies[domain][path] elif domain is not None: del self._cookies[domain] else: self._cookies = {}
python
def clear(self, domain=None, path=None, name=None): if name is not None: if (domain is None) or (path is None): raise ValueError( "domain and path must be given to remove a cookie by name") del self._cookies[domain][path][name] elif path is not None: if domain is None: raise ValueError( "domain must be given to remove cookies by path") del self._cookies[domain][path] elif domain is not None: del self._cookies[domain] else: self._cookies = {}
[ "def", "clear", "(", "self", ",", "domain", "=", "None", ",", "path", "=", "None", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", "if", "(", "domain", "is", "None", ")", "or", "(", "path", "is", "None", ")", ":", ...
Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three arguments, then the cookie with the specified name, path and domain is removed. Raises KeyError if no matching cookie exists.
[ "Clear", "some", "cookies", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1671-L1696
224,701
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
CookieJar.clear_session_cookies
def clear_session_cookies(self): """Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. """ self._cookies_lock.acquire() try: for cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
python
def clear_session_cookies(self): self._cookies_lock.acquire() try: for cookie in self: if cookie.discard: self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
[ "def", "clear_session_cookies", "(", "self", ")", ":", "self", ".", "_cookies_lock", ".", "acquire", "(", ")", "try", ":", "for", "cookie", "in", "self", ":", "if", "cookie", ".", "discard", ":", "self", ".", "clear", "(", "cookie", ".", "domain", ",",...
Discard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.
[ "Discard", "all", "session", "cookies", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1698-L1711
224,702
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
CookieJar.clear_expired_cookies
def clear_expired_cookies(self): """Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (unless you ask otherwise by passing a true ignore_expires argument). """ self._cookies_lock.acquire() try: now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
python
def clear_expired_cookies(self): self._cookies_lock.acquire() try: now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
[ "def", "clear_expired_cookies", "(", "self", ")", ":", "self", ".", "_cookies_lock", ".", "acquire", "(", ")", "try", ":", "now", "=", "time", ".", "time", "(", ")", "for", "cookie", "in", "self", ":", "if", "cookie", ".", "is_expired", "(", "now", "...
Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (unless you ask otherwise by passing a true ignore_expires argument).
[ "Discard", "all", "expired", "cookies", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1713-L1730
224,703
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
FileCookieJar.load
def load(self, filename=None, ignore_discard=False, ignore_expires=False): """Load cookies from a file.""" if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) f = open(filename) try: self._really_load(f, filename, ignore_discard, ignore_expires) finally: f.close()
python
def load(self, filename=None, ignore_discard=False, ignore_expires=False): if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) f = open(filename) try: self._really_load(f, filename, ignore_discard, ignore_expires) finally: f.close()
[ "def", "load", "(", "self", ",", "filename", "=", "None", ",", "ignore_discard", "=", "False", ",", "ignore_expires", "=", "False", ")", ":", "if", "filename", "is", "None", ":", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "=",...
Load cookies from a file.
[ "Load", "cookies", "from", "a", "file", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1778-L1788
224,704
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
FileCookieJar.revert
def revert(self, filename=None, ignore_discard=False, ignore_expires=False): """Clear all cookies and reload cookies from a saved file. Raises LoadError (or IOError) if reversion is not successful; the object's state will not be altered if this happens. """ if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() try: old_state = copy.deepcopy(self._cookies) self._cookies = {} try: self.load(filename, ignore_discard, ignore_expires) except (LoadError, IOError): self._cookies = old_state raise finally: self._cookies_lock.release()
python
def revert(self, filename=None, ignore_discard=False, ignore_expires=False): if filename is None: if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) self._cookies_lock.acquire() try: old_state = copy.deepcopy(self._cookies) self._cookies = {} try: self.load(filename, ignore_discard, ignore_expires) except (LoadError, IOError): self._cookies = old_state raise finally: self._cookies_lock.release()
[ "def", "revert", "(", "self", ",", "filename", "=", "None", ",", "ignore_discard", "=", "False", ",", "ignore_expires", "=", "False", ")", ":", "if", "filename", "is", "None", ":", "if", "self", ".", "filename", "is", "not", "None", ":", "filename", "=...
Clear all cookies and reload cookies from a saved file. Raises LoadError (or IOError) if reversion is not successful; the object's state will not be altered if this happens.
[ "Clear", "all", "cookies", "and", "reload", "cookies", "from", "a", "saved", "file", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1790-L1814
224,705
PythonCharmers/python-future
src/future/backports/http/cookiejar.py
LWPCookieJar.as_lwp_str
def as_lwp_str(self, ignore_discard=True, ignore_expires=True): """Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save """ now = time.time() r = [] for cookie in self: if not ignore_discard and cookie.discard: continue if not ignore_expires and cookie.is_expired(now): continue r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie)) return "\n".join(r+[""])
python
def as_lwp_str(self, ignore_discard=True, ignore_expires=True): now = time.time() r = [] for cookie in self: if not ignore_discard and cookie.discard: continue if not ignore_expires and cookie.is_expired(now): continue r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie)) return "\n".join(r+[""])
[ "def", "as_lwp_str", "(", "self", ",", "ignore_discard", "=", "True", ",", "ignore_expires", "=", "True", ")", ":", "now", "=", "time", ".", "time", "(", ")", "r", "=", "[", "]", "for", "cookie", "in", "self", ":", "if", "not", "ignore_discard", "and...
Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save
[ "Return", "cookies", "as", "a", "string", "of", "\\\\", "n", "-", "separated", "Set", "-", "Cookie3", "headers", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/cookiejar.py#L1858-L1872
224,706
PythonCharmers/python-future
src/future/backports/email/headerregistry.py
Address.addr_spec
def addr_spec(self): """The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding. """ nameset = set(self.username) if len(nameset) > len(nameset-parser.DOT_ATOM_ENDS): lp = parser.quote_string(self.username) else: lp = self.username if self.domain: return lp + '@' + self.domain if not lp: return '<>' return lp
python
def addr_spec(self): nameset = set(self.username) if len(nameset) > len(nameset-parser.DOT_ATOM_ENDS): lp = parser.quote_string(self.username) else: lp = self.username if self.domain: return lp + '@' + self.domain if not lp: return '<>' return lp
[ "def", "addr_spec", "(", "self", ")", ":", "nameset", "=", "set", "(", "self", ".", "username", ")", "if", "len", "(", "nameset", ")", ">", "len", "(", "nameset", "-", "parser", ".", "DOT_ATOM_ENDS", ")", ":", "lp", "=", "parser", ".", "quote_string"...
The addr_spec (username@domain) portion of the address, quoted according to RFC 5322 rules, but with no Content Transfer Encoding.
[ "The", "addr_spec", "(", "username" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/headerregistry.py#L73-L86
224,707
PythonCharmers/python-future
src/future/backports/email/headerregistry.py
BaseHeader.fold
def fold(self, **_3to2kwargs): policy = _3to2kwargs['policy']; del _3to2kwargs['policy'] """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator. """ # At some point we need to only put fws here if it was in the source. header = parser.Header([ parser.HeaderLabel([ parser.ValueTerminal(self.name, 'header-name'), parser.ValueTerminal(':', 'header-sep')]), parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')]), self._parse_tree]) return header.fold(policy=policy)
python
def fold(self, **_3to2kwargs): policy = _3to2kwargs['policy']; del _3to2kwargs['policy'] # At some point we need to only put fws here if it was in the source. header = parser.Header([ parser.HeaderLabel([ parser.ValueTerminal(self.name, 'header-name'), parser.ValueTerminal(':', 'header-sep')]), parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')]), self._parse_tree]) return header.fold(policy=policy)
[ "def", "fold", "(", "self", ",", "*", "*", "_3to2kwargs", ")", ":", "policy", "=", "_3to2kwargs", "[", "'policy'", "]", "del", "_3to2kwargs", "[", "'policy'", "]", "# At some point we need to only put fws here if it was in the source.", "header", "=", "parser", ".",...
Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped bytes, the bytes are CTE encoded using the charset 'unknown-8bit". Any non-ASCII characters in the parse tree are CTE encoded using charset utf-8. XXX: make this a policy setting. The returned value is an ASCII-only string possibly containing linesep characters, and ending with a linesep character. The string includes the header name and the ': ' separator.
[ "Fold", "header", "according", "to", "policy", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/headerregistry.py#L237-L261
224,708
PythonCharmers/python-future
src/future/backports/http/server.py
nobody_uid
def nobody_uid(): """Internal routine to get nobody's uid""" global nobody if nobody: return nobody try: import pwd except ImportError: return -1 try: nobody = pwd.getpwnam('nobody')[2] except KeyError: nobody = 1 + max(x[2] for x in pwd.getpwall()) return nobody
python
def nobody_uid(): global nobody if nobody: return nobody try: import pwd except ImportError: return -1 try: nobody = pwd.getpwnam('nobody')[2] except KeyError: nobody = 1 + max(x[2] for x in pwd.getpwall()) return nobody
[ "def", "nobody_uid", "(", ")", ":", "global", "nobody", "if", "nobody", ":", "return", "nobody", "try", ":", "import", "pwd", "except", "ImportError", ":", "return", "-", "1", "try", ":", "nobody", "=", "pwd", ".", "getpwnam", "(", "'nobody'", ")", "["...
Internal routine to get nobody's uid
[ "Internal", "routine", "to", "get", "nobody", "s", "uid" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L901-L914
224,709
PythonCharmers/python-future
src/future/backports/http/server.py
HTTPServer.server_bind
def server_bind(self): """Override server_bind to store the server name.""" socketserver.TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port
python
def server_bind(self): socketserver.TCPServer.server_bind(self) host, port = self.socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port
[ "def", "server_bind", "(", "self", ")", ":", "socketserver", ".", "TCPServer", ".", "server_bind", "(", "self", ")", "host", ",", "port", "=", "self", ".", "socket", ".", "getsockname", "(", ")", "[", ":", "2", "]", "self", ".", "server_name", "=", "...
Override server_bind to store the server name.
[ "Override", "server_bind", "to", "store", "the", "server", "name", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L139-L144
224,710
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.handle
def handle(self): """Handle multiple requests if necessary.""" self.close_connection = 1 self.handle_one_request() while not self.close_connection: self.handle_one_request()
python
def handle(self): self.close_connection = 1 self.handle_one_request() while not self.close_connection: self.handle_one_request()
[ "def", "handle", "(", "self", ")", ":", "self", ".", "close_connection", "=", "1", "self", ".", "handle_one_request", "(", ")", "while", "not", "self", ".", "close_connection", ":", "self", ".", "handle_one_request", "(", ")" ]
Handle multiple requests if necessary.
[ "Handle", "multiple", "requests", "if", "necessary", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L402-L408
224,711
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.send_response
def send_response(self, code, message=None): """Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date. """ self.log_request(code) self.send_response_only(code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
python
def send_response(self, code, message=None): self.log_request(code) self.send_response_only(code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
[ "def", "send_response", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "self", ".", "log_request", "(", "code", ")", "self", ".", "send_response_only", "(", "code", ",", "message", ")", "self", ".", "send_header", "(", "'Server'", ",", ...
Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date.
[ "Add", "the", "response", "header", "to", "the", "headers", "buffer", "and", "log", "the", "response", "code", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L441-L452
224,712
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.send_response_only
def send_response_only(self, code, message=None): """Send the response header only.""" if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode( 'latin-1', 'strict'))
python
def send_response_only(self, code, message=None): if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode( 'latin-1', 'strict'))
[ "def", "send_response_only", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "if", "message", "is", "None", ":", "if", "code", "in", "self", ".", "responses", ":", "message", "=", "self", ".", "responses", "[", "code", "]", "[", "0",...
Send the response header only.
[ "Send", "the", "response", "header", "only", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L454-L466
224,713
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.send_header
def send_header(self, keyword, value): """Send a MIME header to the headers buffer.""" if self.request_version != 'HTTP/0.9': if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append( ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict')) if keyword.lower() == 'connection': if value.lower() == 'close': self.close_connection = 1 elif value.lower() == 'keep-alive': self.close_connection = 0
python
def send_header(self, keyword, value): if self.request_version != 'HTTP/0.9': if not hasattr(self, '_headers_buffer'): self._headers_buffer = [] self._headers_buffer.append( ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict')) if keyword.lower() == 'connection': if value.lower() == 'close': self.close_connection = 1 elif value.lower() == 'keep-alive': self.close_connection = 0
[ "def", "send_header", "(", "self", ",", "keyword", ",", "value", ")", ":", "if", "self", ".", "request_version", "!=", "'HTTP/0.9'", ":", "if", "not", "hasattr", "(", "self", ",", "'_headers_buffer'", ")", ":", "self", ".", "_headers_buffer", "=", "[", "...
Send a MIME header to the headers buffer.
[ "Send", "a", "MIME", "header", "to", "the", "headers", "buffer", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L468-L480
224,714
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.end_headers
def end_headers(self): """Send the blank line ending the MIME headers.""" if self.request_version != 'HTTP/0.9': self._headers_buffer.append(b"\r\n") self.flush_headers()
python
def end_headers(self): if self.request_version != 'HTTP/0.9': self._headers_buffer.append(b"\r\n") self.flush_headers()
[ "def", "end_headers", "(", "self", ")", ":", "if", "self", ".", "request_version", "!=", "'HTTP/0.9'", ":", "self", ".", "_headers_buffer", ".", "append", "(", "b\"\\r\\n\"", ")", "self", ".", "flush_headers", "(", ")" ]
Send the blank line ending the MIME headers.
[ "Send", "the", "blank", "line", "ending", "the", "MIME", "headers", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L482-L486
224,715
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.log_message
def log_message(self, format, *args): """Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!). The client ip and current date/time are prefixed to every message. """ sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args))
python
def log_message(self, format, *args): sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args))
[ "def", "log_message", "(", "self", ",", "format", ",", "*", "args", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"%s - - [%s] %s\\n\"", "%", "(", "self", ".", "address_string", "(", ")", ",", "self", ".", "log_date_time_string", "(", ")", ",", ...
Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it's just like printf!). The client ip and current date/time are prefixed to every message.
[ "Log", "an", "arbitrary", "message", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L517-L537
224,716
PythonCharmers/python-future
src/future/backports/http/server.py
BaseHTTPRequestHandler.log_date_time_string
def log_date_time_string(self): """Return the current time formatted for logging.""" now = time.time() year, month, day, hh, mm, ss, x, y, z = time.localtime(now) s = "%02d/%3s/%04d %02d:%02d:%02d" % ( day, self.monthname[month], year, hh, mm, ss) return s
python
def log_date_time_string(self): now = time.time() year, month, day, hh, mm, ss, x, y, z = time.localtime(now) s = "%02d/%3s/%04d %02d:%02d:%02d" % ( day, self.monthname[month], year, hh, mm, ss) return s
[ "def", "log_date_time_string", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "year", ",", "month", ",", "day", ",", "hh", ",", "mm", ",", "ss", ",", "x", ",", "y", ",", "z", "=", "time", ".", "localtime", "(", "now", ")", ...
Return the current time formatted for logging.
[ "Return", "the", "current", "time", "formatted", "for", "logging", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L554-L560
224,717
PythonCharmers/python-future
src/future/backports/http/server.py
CGIHTTPRequestHandler.is_cgi
def is_cgi(self): """Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly. The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string). """ collapsed_path = _url_collapse_path(self.path) dir_sep = collapsed_path.find('/', 1) head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:] if head in self.cgi_directories: self.cgi_info = head, tail return True return False
python
def is_cgi(self): collapsed_path = _url_collapse_path(self.path) dir_sep = collapsed_path.find('/', 1) head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:] if head in self.cgi_directories: self.cgi_info = head, tail return True return False
[ "def", "is_cgi", "(", "self", ")", ":", "collapsed_path", "=", "_url_collapse_path", "(", "self", ".", "path", ")", "dir_sep", "=", "collapsed_path", ".", "find", "(", "'/'", ",", "1", ")", "head", ",", "tail", "=", "collapsed_path", "[", ":", "dir_sep",...
Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly. The default implementation tests whether the normalized url path begins with one of the strings in self.cgi_directories (and the next character is a '/' or the end of the string).
[ "Test", "whether", "self", ".", "path", "corresponds", "to", "a", "CGI", "script", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L958-L979
224,718
PythonCharmers/python-future
src/future/backports/http/server.py
CGIHTTPRequestHandler.is_python
def is_python(self, path): """Test whether argument path is a Python script.""" head, tail = os.path.splitext(path) return tail.lower() in (".py", ".pyw")
python
def is_python(self, path): head, tail = os.path.splitext(path) return tail.lower() in (".py", ".pyw")
[ "def", "is_python", "(", "self", ",", "path", ")", ":", "head", ",", "tail", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "return", "tail", ".", "lower", "(", ")", "in", "(", "\".py\"", ",", "\".pyw\"", ")" ]
Test whether argument path is a Python script.
[ "Test", "whether", "argument", "path", "is", "a", "Python", "script", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L988-L991
224,719
PythonCharmers/python-future
src/future/types/newrange.py
newrange.index
def index(self, value): """Return the 0-based position of integer `value` in the sequence this range represents.""" try: diff = value - self._start except TypeError: raise ValueError('%r is not in range' % value) quotient, remainder = divmod(diff, self._step) if remainder == 0 and 0 <= quotient < self._len: return abs(quotient) raise ValueError('%r is not in range' % value)
python
def index(self, value): try: diff = value - self._start except TypeError: raise ValueError('%r is not in range' % value) quotient, remainder = divmod(diff, self._step) if remainder == 0 and 0 <= quotient < self._len: return abs(quotient) raise ValueError('%r is not in range' % value)
[ "def", "index", "(", "self", ",", "value", ")", ":", "try", ":", "diff", "=", "value", "-", "self", ".", "_start", "except", "TypeError", ":", "raise", "ValueError", "(", "'%r is not in range'", "%", "value", ")", "quotient", ",", "remainder", "=", "divm...
Return the 0-based position of integer `value` in the sequence this range represents.
[ "Return", "the", "0", "-", "based", "position", "of", "integer", "value", "in", "the", "sequence", "this", "range", "represents", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newrange.py#L90-L100
224,720
PythonCharmers/python-future
src/future/types/newrange.py
newrange.__getitem_slice
def __getitem_slice(self, slce): """Return a range which represents the requested slce of the sequence represented by this range. """ scaled_indices = (self._step * n for n in slce.indices(self._len)) start_offset, stop_offset, new_step = scaled_indices return newrange(self._start + start_offset, self._start + stop_offset, new_step)
python
def __getitem_slice(self, slce): scaled_indices = (self._step * n for n in slce.indices(self._len)) start_offset, stop_offset, new_step = scaled_indices return newrange(self._start + start_offset, self._start + stop_offset, new_step)
[ "def", "__getitem_slice", "(", "self", ",", "slce", ")", ":", "scaled_indices", "=", "(", "self", ".", "_step", "*", "n", "for", "n", "in", "slce", ".", "indices", "(", "self", ".", "_len", ")", ")", "start_offset", ",", "stop_offset", ",", "new_step",...
Return a range which represents the requested slce of the sequence represented by this range.
[ "Return", "a", "range", "which", "represents", "the", "requested", "slce", "of", "the", "sequence", "represented", "by", "this", "range", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newrange.py#L133-L141
224,721
PythonCharmers/python-future
src/future/backports/urllib/robotparser.py
RobotFileParser.set_url
def set_url(self, url): """Sets the URL referring to a robots.txt file.""" self.url = url self.host, self.path = urllib.parse.urlparse(url)[1:3]
python
def set_url(self, url): self.url = url self.host, self.path = urllib.parse.urlparse(url)[1:3]
[ "def", "set_url", "(", "self", ",", "url", ")", ":", "self", ".", "url", "=", "url", "self", ".", "host", ",", "self", ".", "path", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "[", "1", ":", "3", "]" ]
Sets the URL referring to a robots.txt file.
[ "Sets", "the", "URL", "referring", "to", "a", "robots", ".", "txt", "file", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/robotparser.py#L55-L58
224,722
PythonCharmers/python-future
src/future/backports/urllib/robotparser.py
RobotFileParser.read
def read(self): """Reads the robots.txt URL and feeds it to the parser.""" try: f = urllib.request.urlopen(self.url) except urllib.error.HTTPError as err: if err.code in (401, 403): self.disallow_all = True elif err.code >= 400: self.allow_all = True else: raw = f.read() self.parse(raw.decode("utf-8").splitlines())
python
def read(self): try: f = urllib.request.urlopen(self.url) except urllib.error.HTTPError as err: if err.code in (401, 403): self.disallow_all = True elif err.code >= 400: self.allow_all = True else: raw = f.read() self.parse(raw.decode("utf-8").splitlines())
[ "def", "read", "(", "self", ")", ":", "try", ":", "f", "=", "urllib", ".", "request", ".", "urlopen", "(", "self", ".", "url", ")", "except", "urllib", ".", "error", ".", "HTTPError", "as", "err", ":", "if", "err", ".", "code", "in", "(", "401", ...
Reads the robots.txt URL and feeds it to the parser.
[ "Reads", "the", "robots", ".", "txt", "URL", "and", "feeds", "it", "to", "the", "parser", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/robotparser.py#L60-L71
224,723
PythonCharmers/python-future
src/future/backports/urllib/robotparser.py
RobotFileParser.parse
def parse(self, lines): """Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines. """ # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line state = 0 entry = Entry() for line in lines: if not line: if state == 1: entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.parse.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state != 0: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state != 0: entry.rulelines.append(RuleLine(line[1], True)) state = 2 if state == 2: self._add_entry(entry)
python
def parse(self, lines): # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line state = 0 entry = Entry() for line in lines: if not line: if state == 1: entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.parse.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state != 0: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state != 0: entry.rulelines.append(RuleLine(line[1], True)) state = 2 if state == 2: self._add_entry(entry)
[ "def", "parse", "(", "self", ",", "lines", ")", ":", "# states:", "# 0: start state", "# 1: saw user-agent line", "# 2: saw an allow or disallow line", "state", "=", "0", "entry", "=", "Entry", "(", ")", "for", "line", "in", "lines", ":", "if", "not", "lin...
Parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.
[ "Parse", "the", "input", "lines", "from", "a", "robots", ".", "txt", "file", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/robotparser.py#L82-L130
224,724
PythonCharmers/python-future
src/future/backports/urllib/robotparser.py
RobotFileParser.can_fetch
def can_fetch(self, useragent, url): """using the parsed robots.txt decide if useragent can fetch url""" if self.disallow_all: return False if self.allow_all: return True # search for given user agent matches # the first match counts parsed_url = urllib.parse.urlparse(urllib.parse.unquote(url)) url = urllib.parse.urlunparse(('','',parsed_url.path, parsed_url.params,parsed_url.query, parsed_url.fragment)) url = urllib.parse.quote(url) if not url: url = "/" for entry in self.entries: if entry.applies_to(useragent): return entry.allowance(url) # try the default entry last if self.default_entry: return self.default_entry.allowance(url) # agent not found ==> access granted return True
python
def can_fetch(self, useragent, url): if self.disallow_all: return False if self.allow_all: return True # search for given user agent matches # the first match counts parsed_url = urllib.parse.urlparse(urllib.parse.unquote(url)) url = urllib.parse.urlunparse(('','',parsed_url.path, parsed_url.params,parsed_url.query, parsed_url.fragment)) url = urllib.parse.quote(url) if not url: url = "/" for entry in self.entries: if entry.applies_to(useragent): return entry.allowance(url) # try the default entry last if self.default_entry: return self.default_entry.allowance(url) # agent not found ==> access granted return True
[ "def", "can_fetch", "(", "self", ",", "useragent", ",", "url", ")", ":", "if", "self", ".", "disallow_all", ":", "return", "False", "if", "self", ".", "allow_all", ":", "return", "True", "# search for given user agent matches", "# the first match counts", "parsed_...
using the parsed robots.txt decide if useragent can fetch url
[ "using", "the", "parsed", "robots", ".", "txt", "decide", "if", "useragent", "can", "fetch", "url" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/robotparser.py#L133-L154
224,725
PythonCharmers/python-future
src/future/backports/misc.py
recursive_repr
def recursive_repr(fillvalue='...'): 'Decorator to make a repr function return fillvalue for a recursive call' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) return wrapper return decorating_function
python
def recursive_repr(fillvalue='...'): 'Decorator to make a repr function return fillvalue for a recursive call' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) return wrapper return decorating_function
[ "def", "recursive_repr", "(", "fillvalue", "=", "'...'", ")", ":", "def", "decorating_function", "(", "user_function", ")", ":", "repr_running", "=", "set", "(", ")", "def", "wrapper", "(", "self", ")", ":", "key", "=", "id", "(", "self", ")", ",", "ge...
Decorator to make a repr function return fillvalue for a recursive call
[ "Decorator", "to", "make", "a", "repr", "function", "return", "fillvalue", "for", "a", "recursive", "call" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/misc.py#L57-L81
224,726
PythonCharmers/python-future
src/future/backports/misc.py
_count_elements
def _count_elements(mapping, iterable): 'Tally elements from the iterable.' mapping_get = mapping.get for elem in iterable: mapping[elem] = mapping_get(elem, 0) + 1
python
def _count_elements(mapping, iterable): 'Tally elements from the iterable.' mapping_get = mapping.get for elem in iterable: mapping[elem] = mapping_get(elem, 0) + 1
[ "def", "_count_elements", "(", "mapping", ",", "iterable", ")", ":", "mapping_get", "=", "mapping", ".", "get", "for", "elem", "in", "iterable", ":", "mapping", "[", "elem", "]", "=", "mapping_get", "(", "elem", ",", "0", ")", "+", "1" ]
Tally elements from the iterable.
[ "Tally", "elements", "from", "the", "iterable", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/misc.py#L314-L318
224,727
PythonCharmers/python-future
src/future/backports/misc.py
Counter._keep_positive
def _keep_positive(self): '''Internal method to strip elements with a negative or zero count''' nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self
python
def _keep_positive(self): '''Internal method to strip elements with a negative or zero count''' nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self
[ "def", "_keep_positive", "(", "self", ")", ":", "nonpositive", "=", "[", "elem", "for", "elem", ",", "count", "in", "self", ".", "items", "(", ")", "if", "not", "count", ">", "0", "]", "for", "elem", "in", "nonpositive", ":", "del", "self", "[", "e...
Internal method to strip elements with a negative or zero count
[ "Internal", "method", "to", "strip", "elements", "with", "a", "negative", "or", "zero", "count" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/misc.py#L634-L639
224,728
PythonCharmers/python-future
src/future/backports/email/generator.py
Generator.flatten
def flatten(self, msg, unixfrom=False, linesep=None): r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy. """ # We use the _XXX constants for operating on data that comes directly # from the msg, and _encoded_XXX constants for operating on data that # has already been converted (to bytes in the BytesGenerator) and # inserted into a temporary buffer. policy = msg.policy if self.policy is None else self.policy if linesep is not None: policy = policy.clone(linesep=linesep) if self.maxheaderlen is not None: policy = policy.clone(max_line_length=self.maxheaderlen) self._NL = policy.linesep self._encoded_NL = self._encode(self._NL) self._EMPTY = '' self._encoded_EMTPY = self._encode('') # Because we use clone (below) when we recursively process message # subparts, and because clone uses the computed policy (not None), # submessages will automatically get set to the computed policy when # they are processed by this code. old_gen_policy = self.policy old_msg_policy = msg.policy try: self.policy = policy msg.policy = policy if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) self.write(ufrom + self._NL) self._write(msg) finally: self.policy = old_gen_policy msg.policy = old_msg_policy
python
def flatten(self, msg, unixfrom=False, linesep=None): r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy. """ # We use the _XXX constants for operating on data that comes directly # from the msg, and _encoded_XXX constants for operating on data that # has already been converted (to bytes in the BytesGenerator) and # inserted into a temporary buffer. policy = msg.policy if self.policy is None else self.policy if linesep is not None: policy = policy.clone(linesep=linesep) if self.maxheaderlen is not None: policy = policy.clone(max_line_length=self.maxheaderlen) self._NL = policy.linesep self._encoded_NL = self._encode(self._NL) self._EMPTY = '' self._encoded_EMTPY = self._encode('') # Because we use clone (below) when we recursively process message # subparts, and because clone uses the computed policy (not None), # submessages will automatically get set to the computed policy when # they are processed by this code. old_gen_policy = self.policy old_msg_policy = msg.policy try: self.policy = policy msg.policy = policy if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) self.write(ufrom + self._NL) self._write(msg) finally: self.policy = old_gen_policy msg.policy = old_msg_policy
[ "def", "flatten", "(", "self", ",", "msg", ",", "unixfrom", "=", "False", ",", "linesep", "=", "None", ")", ":", "# We use the _XXX constants for operating on data that comes directly", "# from the msg, and _encoded_XXX constants for operating on data that", "# has already been c...
r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy.
[ "r", "Print", "the", "message", "object", "tree", "rooted", "at", "msg", "to", "the", "output", "file", "specified", "when", "the", "Generator", "instance", "was", "created", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/generator.py#L76-L121
224,729
PythonCharmers/python-future
src/future/backports/email/generator.py
Generator.clone
def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, None, # Use policy setting, which we've adjusted policy=self.policy)
python
def clone(self, fp): return self.__class__(fp, self._mangle_from_, None, # Use policy setting, which we've adjusted policy=self.policy)
[ "def", "clone", "(", "self", ",", "fp", ")", ":", "return", "self", ".", "__class__", "(", "fp", ",", "self", ".", "_mangle_from_", ",", "None", ",", "# Use policy setting, which we've adjusted", "policy", "=", "self", ".", "policy", ")" ]
Clone this generator with the exact same options.
[ "Clone", "this", "generator", "with", "the", "exact", "same", "options", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/generator.py#L123-L128
224,730
PythonCharmers/python-future
src/future/backports/urllib/request.py
urlretrieve
def urlretrieve(url, filename=None, reporthook=None, data=None): """ Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The data argument should be valid URL encoded data. If a filename is passed and the URL points to a local resource, the result is a copy from local file to new file. Returns a tuple containing the path to the newly created data file as well as the resulting HTTPMessage object. """ url_type, path = splittype(url) with contextlib.closing(urlopen(url, data)) as fp: headers = fp.info() # Just return the local path and the "headers" for file:// # URLs. No sense in performing a copy unless requested. if url_type == "file" and not filename: return os.path.normpath(path), headers # Handle temporary file setup. if filename: tfp = open(filename, 'wb') else: tfp = tempfile.NamedTemporaryFile(delete=False) filename = tfp.name _url_tempfiles.append(filename) with tfp: result = filename, headers bs = 1024*8 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, bs, size) while True: block = fp.read(bs) if not block: break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) if size >= 0 and read < size: raise ContentTooShortError( "retrieval incomplete: got only %i out of %i bytes" % (read, size), result) return result
python
def urlretrieve(url, filename=None, reporthook=None, data=None): url_type, path = splittype(url) with contextlib.closing(urlopen(url, data)) as fp: headers = fp.info() # Just return the local path and the "headers" for file:// # URLs. No sense in performing a copy unless requested. if url_type == "file" and not filename: return os.path.normpath(path), headers # Handle temporary file setup. if filename: tfp = open(filename, 'wb') else: tfp = tempfile.NamedTemporaryFile(delete=False) filename = tfp.name _url_tempfiles.append(filename) with tfp: result = filename, headers bs = 1024*8 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, bs, size) while True: block = fp.read(bs) if not block: break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) if size >= 0 and read < size: raise ContentTooShortError( "retrieval incomplete: got only %i out of %i bytes" % (read, size), result) return result
[ "def", "urlretrieve", "(", "url", ",", "filename", "=", "None", ",", "reporthook", "=", "None", ",", "data", "=", "None", ")", ":", "url_type", ",", "path", "=", "splittype", "(", "url", ")", "with", "contextlib", ".", "closing", "(", "urlopen", "(", ...
Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The data argument should be valid URL encoded data. If a filename is passed and the URL points to a local resource, the result is a copy from local file to new file. Returns a tuple containing the path to the newly created data file as well as the resulting HTTPMessage object.
[ "Retrieve", "a", "URL", "into", "a", "temporary", "location", "on", "disk", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L178-L239
224,731
PythonCharmers/python-future
src/future/backports/urllib/request.py
build_opener
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ def isclass(obj): return isinstance(obj, type) or hasattr(obj, "__bases__") opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(http_client, "HTTPSConnection"): default_classes.append(HTTPSHandler) skip = set() for klass in default_classes: for check in handlers: if isclass(check): if issubclass(check, klass): skip.add(klass) elif isinstance(check, klass): skip.add(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isclass(h): h = h() opener.add_handler(h) return opener
python
def build_opener(*handlers): def isclass(obj): return isinstance(obj, type) or hasattr(obj, "__bases__") opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(http_client, "HTTPSConnection"): default_classes.append(HTTPSHandler) skip = set() for klass in default_classes: for check in handlers: if isclass(check): if issubclass(check, klass): skip.add(klass) elif isinstance(check, klass): skip.add(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isclass(h): h = h() opener.add_handler(h) return opener
[ "def", "build_opener", "(", "*", "handlers", ")", ":", "def", "isclass", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "type", ")", "or", "hasattr", "(", "obj", ",", "\"__bases__\"", ")", "opener", "=", "OpenerDirector", "(", ")", "def...
Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used.
[ "Create", "an", "opener", "object", "from", "a", "list", "of", "handlers", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L544-L580
224,732
PythonCharmers/python-future
src/future/backports/urllib/request.py
parse_keqv_list
def parse_keqv_list(l): """Parse list of key=value strings where keys are not duplicated.""" parsed = {} for elt in l: k, v = elt.split('=', 1) if v[0] == '"' and v[-1] == '"': v = v[1:-1] parsed[k] = v return parsed
python
def parse_keqv_list(l): parsed = {} for elt in l: k, v = elt.split('=', 1) if v[0] == '"' and v[-1] == '"': v = v[1:-1] parsed[k] = v return parsed
[ "def", "parse_keqv_list", "(", "l", ")", ":", "parsed", "=", "{", "}", "for", "elt", "in", "l", ":", "k", ",", "v", "=", "elt", ".", "split", "(", "'='", ",", "1", ")", "if", "v", "[", "0", "]", "==", "'\"'", "and", "v", "[", "-", "1", "]...
Parse list of key=value strings where keys are not duplicated.
[ "Parse", "list", "of", "key", "=", "value", "strings", "where", "keys", "are", "not", "duplicated", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1355-L1363
224,733
PythonCharmers/python-future
src/future/backports/urllib/request.py
thishost
def thishost(): """Return the IP addresses of the current host.""" global _thishost if _thishost is None: try: _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2]) except socket.gaierror: _thishost = tuple(socket.gethostbyname_ex('localhost')[2]) return _thishost
python
def thishost(): global _thishost if _thishost is None: try: _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2]) except socket.gaierror: _thishost = tuple(socket.gethostbyname_ex('localhost')[2]) return _thishost
[ "def", "thishost", "(", ")", ":", "global", "_thishost", "if", "_thishost", "is", "None", ":", "try", ":", "_thishost", "=", "tuple", "(", "socket", ".", "gethostbyname_ex", "(", "socket", ".", "gethostname", "(", ")", ")", "[", "2", "]", ")", "except"...
Return the IP addresses of the current host.
[ "Return", "the", "IP", "addresses", "of", "the", "current", "host", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2271-L2279
224,734
PythonCharmers/python-future
src/future/backports/urllib/request.py
getproxies_environment
def getproxies_environment(): """Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. """ proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
python
def getproxies_environment(): proxies = {} for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value return proxies
[ "def", "getproxies_environment", "(", ")", ":", "proxies", "=", "{", "}", "for", "name", ",", "value", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "if", "value", "and", "name", "[", "-", "...
Return a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named <scheme>_proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor.
[ "Return", "a", "dictionary", "of", "scheme", "-", ">", "proxy", "server", "URL", "mappings", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2395-L2409
224,735
PythonCharmers/python-future
src/future/backports/urllib/request.py
proxy_bypass_environment
def proxy_bypass_environment(host): """Test if proxies should not be used for a particular host. Checks the environment for a variable named no_proxy, which should be a list of DNS suffixes separated by commas, or '*' for all hosts. """ no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '') # '*' is special case for always bypass if no_proxy == '*': return 1 # strip port off host hostonly, port = splitport(host) # check if the host ends with any of the DNS suffixes no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')] for name in no_proxy_list: if name and (hostonly.endswith(name) or host.endswith(name)): return 1 # otherwise, don't bypass return 0
python
def proxy_bypass_environment(host): no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '') # '*' is special case for always bypass if no_proxy == '*': return 1 # strip port off host hostonly, port = splitport(host) # check if the host ends with any of the DNS suffixes no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')] for name in no_proxy_list: if name and (hostonly.endswith(name) or host.endswith(name)): return 1 # otherwise, don't bypass return 0
[ "def", "proxy_bypass_environment", "(", "host", ")", ":", "no_proxy", "=", "os", ".", "environ", ".", "get", "(", "'no_proxy'", ",", "''", ")", "or", "os", ".", "environ", ".", "get", "(", "'NO_PROXY'", ",", "''", ")", "# '*' is special case for always bypas...
Test if proxies should not be used for a particular host. Checks the environment for a variable named no_proxy, which should be a list of DNS suffixes separated by commas, or '*' for all hosts.
[ "Test", "if", "proxies", "should", "not", "be", "used", "for", "a", "particular", "host", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2411-L2429
224,736
PythonCharmers/python-future
src/future/backports/urllib/request.py
_proxy_bypass_macosx_sysconf
def _proxy_bypass_macosx_sysconf(host, proxy_settings): """ Return True iff this host shouldn't be accessed using a proxy This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: { 'exclude_simple': bool, 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] } """ from fnmatch import fnmatch hostonly, port = splitport(host) def ip2num(ipAddr): parts = ipAddr.split('.') parts = list(map(int, parts)) if len(parts) != 4: parts = (parts + [0, 0, 0, 0])[:4] return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] # Check for simple host names: if '.' not in host: if proxy_settings['exclude_simple']: return True hostIP = None for value in proxy_settings.get('exceptions', ()): # Items in the list are strings like these: *.local, 169.254/16 if not value: continue m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value) if m is not None: if hostIP is None: try: hostIP = socket.gethostbyname(hostonly) hostIP = ip2num(hostIP) except socket.error: continue base = ip2num(m.group(1)) mask = m.group(2) if mask is None: mask = 8 * (m.group(1).count('.') + 1) else: mask = int(mask[1:]) mask = 32 - mask if (hostIP >> mask) == (base >> mask): return True elif fnmatch(host, value): return True return False
python
def _proxy_bypass_macosx_sysconf(host, proxy_settings): from fnmatch import fnmatch hostonly, port = splitport(host) def ip2num(ipAddr): parts = ipAddr.split('.') parts = list(map(int, parts)) if len(parts) != 4: parts = (parts + [0, 0, 0, 0])[:4] return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3] # Check for simple host names: if '.' not in host: if proxy_settings['exclude_simple']: return True hostIP = None for value in proxy_settings.get('exceptions', ()): # Items in the list are strings like these: *.local, 169.254/16 if not value: continue m = re.match(r"(\d+(?:\.\d+)*)(/\d+)?", value) if m is not None: if hostIP is None: try: hostIP = socket.gethostbyname(hostonly) hostIP = ip2num(hostIP) except socket.error: continue base = ip2num(m.group(1)) mask = m.group(2) if mask is None: mask = 8 * (m.group(1).count('.') + 1) else: mask = int(mask[1:]) mask = 32 - mask if (hostIP >> mask) == (base >> mask): return True elif fnmatch(host, value): return True return False
[ "def", "_proxy_bypass_macosx_sysconf", "(", "host", ",", "proxy_settings", ")", ":", "from", "fnmatch", "import", "fnmatch", "hostonly", ",", "port", "=", "splitport", "(", "host", ")", "def", "ip2num", "(", "ipAddr", ")", ":", "parts", "=", "ipAddr", ".", ...
Return True iff this host shouldn't be accessed using a proxy This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: { 'exclude_simple': bool, 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] }
[ "Return", "True", "iff", "this", "host", "shouldn", "t", "be", "accessed", "using", "a", "proxy" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2434-L2491
224,737
PythonCharmers/python-future
src/future/backports/urllib/request.py
OpenerDirector.open
def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): """ Accept a URL or a Request object Python-Future: if the URL is passed as a byte-string, decode it first. """ if isinstance(fullurl, bytes): fullurl = fullurl.decode() if isinstance(fullurl, str): req = Request(fullurl, data) else: req = fullurl if data is not None: req.data = data req.timeout = timeout protocol = req.type # pre-process request meth_name = protocol+"_request" for processor in self.process_request.get(protocol, []): meth = getattr(processor, meth_name) req = meth(req) response = self._open(req, data) # post-process response meth_name = protocol+"_response" for processor in self.process_response.get(protocol, []): meth = getattr(processor, meth_name) response = meth(req, response) return response
python
def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if isinstance(fullurl, bytes): fullurl = fullurl.decode() if isinstance(fullurl, str): req = Request(fullurl, data) else: req = fullurl if data is not None: req.data = data req.timeout = timeout protocol = req.type # pre-process request meth_name = protocol+"_request" for processor in self.process_request.get(protocol, []): meth = getattr(processor, meth_name) req = meth(req) response = self._open(req, data) # post-process response meth_name = protocol+"_response" for processor in self.process_response.get(protocol, []): meth = getattr(processor, meth_name) response = meth(req, response) return response
[ "def", "open", "(", "self", ",", "fullurl", ",", "data", "=", "None", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ")", ":", "if", "isinstance", "(", "fullurl", ",", "bytes", ")", ":", "fullurl", "=", "fullurl", ".", "decode", "(", ")...
Accept a URL or a Request object Python-Future: if the URL is passed as a byte-string, decode it first.
[ "Accept", "a", "URL", "or", "a", "Request", "object" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L470-L502
224,738
PythonCharmers/python-future
src/future/backports/urllib/request.py
HTTPRedirectHandler.redirect_request
def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should take place, return a new Request to allow http_error_30x to perform the redirect. Otherwise, raise HTTPError if no-one else should try to handle this url. Return None if you can't but another Handler might. """ m = req.get_method() if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (301, 302, 303) and m == "POST")): raise HTTPError(req.full_url, code, msg, headers, fp) # Strictly (according to RFC 2616), 301 or 302 in response to # a POST MUST NOT cause a redirection without confirmation # from the user (of urllib.request, in this case). In practice, # essentially all clients do redirect in this case, so we do # the same. # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') CONTENT_HEADERS = ("content-length", "content-type") newheaders = dict((k, v) for k, v in req.headers.items() if k.lower() not in CONTENT_HEADERS) return Request(newurl, headers=newheaders, origin_req_host=req.origin_req_host, unverifiable=True)
python
def redirect_request(self, req, fp, code, msg, headers, newurl): m = req.get_method() if (not (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (301, 302, 303) and m == "POST")): raise HTTPError(req.full_url, code, msg, headers, fp) # Strictly (according to RFC 2616), 301 or 302 in response to # a POST MUST NOT cause a redirection without confirmation # from the user (of urllib.request, in this case). In practice, # essentially all clients do redirect in this case, so we do # the same. # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') CONTENT_HEADERS = ("content-length", "content-type") newheaders = dict((k, v) for k, v in req.headers.items() if k.lower() not in CONTENT_HEADERS) return Request(newurl, headers=newheaders, origin_req_host=req.origin_req_host, unverifiable=True)
[ "def", "redirect_request", "(", "self", ",", "req", ",", "fp", ",", "code", ",", "msg", ",", "headers", ",", "newurl", ")", ":", "m", "=", "req", ".", "get_method", "(", ")", "if", "(", "not", "(", "code", "in", "(", "301", ",", "302", ",", "30...
Return a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should take place, return a new Request to allow http_error_30x to perform the redirect. Otherwise, raise HTTPError if no-one else should try to handle this url. Return None if you can't but another Handler might.
[ "Return", "a", "Request", "or", "None", "in", "response", "to", "a", "redirect", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L630-L658
224,739
PythonCharmers/python-future
src/future/backports/urllib/request.py
HTTPPasswordMgr.reduce_uri
def reduce_uri(self, uri, default_port=True): """Accept authority or URI and extract only the authority and path.""" # note HTTP URLs do not have a userinfo component parts = urlsplit(uri) if parts[1]: # URI scheme = parts[0] authority = parts[1] path = parts[2] or '/' else: # host or host:port scheme = None authority = uri path = '/' host, port = splitport(authority) if default_port and port is None and scheme is not None: dport = {"http": 80, "https": 443, }.get(scheme) if dport is not None: authority = "%s:%d" % (host, dport) return authority, path
python
def reduce_uri(self, uri, default_port=True): # note HTTP URLs do not have a userinfo component parts = urlsplit(uri) if parts[1]: # URI scheme = parts[0] authority = parts[1] path = parts[2] or '/' else: # host or host:port scheme = None authority = uri path = '/' host, port = splitport(authority) if default_port and port is None and scheme is not None: dport = {"http": 80, "https": 443, }.get(scheme) if dport is not None: authority = "%s:%d" % (host, dport) return authority, path
[ "def", "reduce_uri", "(", "self", ",", "uri", ",", "default_port", "=", "True", ")", ":", "# note HTTP URLs do not have a userinfo component", "parts", "=", "urlsplit", "(", "uri", ")", "if", "parts", "[", "1", "]", ":", "# URI", "scheme", "=", "parts", "[",...
Accept authority or URI and extract only the authority and path.
[ "Accept", "authority", "or", "URI", "and", "extract", "only", "the", "authority", "and", "path", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L866-L887
224,740
PythonCharmers/python-future
src/future/backports/urllib/request.py
HTTPPasswordMgr.is_suburi
def is_suburi(self, base, test): """Check if test is below base in a URI tree Both args must be URIs in reduced form. """ if base == test: return True if base[0] != test[0]: return False common = posixpath.commonprefix((base[1], test[1])) if len(common) == len(base[1]): return True return False
python
def is_suburi(self, base, test): if base == test: return True if base[0] != test[0]: return False common = posixpath.commonprefix((base[1], test[1])) if len(common) == len(base[1]): return True return False
[ "def", "is_suburi", "(", "self", ",", "base", ",", "test", ")", ":", "if", "base", "==", "test", ":", "return", "True", "if", "base", "[", "0", "]", "!=", "test", "[", "0", "]", ":", "return", "False", "common", "=", "posixpath", ".", "commonprefix...
Check if test is below base in a URI tree Both args must be URIs in reduced form.
[ "Check", "if", "test", "is", "below", "base", "in", "a", "URI", "tree" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L889-L901
224,741
PythonCharmers/python-future
src/future/backports/urllib/request.py
AbstractHTTPHandler.do_open
def do_open(self, http_class, req, **http_conn_args): """Return an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. """ host = req.host if not host: raise URLError('no host given') # will parse host:port h = http_class(host, timeout=req.timeout, **http_conn_args) headers = dict(req.unredirected_hdrs) headers.update(dict((k, v) for k, v in req.headers.items() if k not in headers)) # TODO(jhylton): Should this be redesigned to handle # persistent connections? # We want to make an HTTP/1.1 request, but the addinfourl # class isn't prepared to deal with a persistent connection. # It will try to read all remaining data from the socket, # which will block while the server waits for the next request. # So make sure the connection gets closed after the (only) # request. headers["Connection"] = "close" headers = dict((name.title(), val) for name, val in headers.items()) if req._tunnel_host: tunnel_headers = {} proxy_auth_hdr = "Proxy-Authorization" if proxy_auth_hdr in headers: tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr] # Proxy-Authorization should not be sent to origin # server. del headers[proxy_auth_hdr] h.set_tunnel(req._tunnel_host, headers=tunnel_headers) try: h.request(req.get_method(), req.selector, req.data, headers) except socket.error as err: # timeout error h.close() raise URLError(err) else: r = h.getresponse() # If the server does not send us a 'Connection: close' header, # HTTPConnection assumes the socket should be left open. Manually # mark the socket to be closed when this response object goes away. if h.sock: h.sock.close() h.sock = None r.url = req.get_full_url() # This line replaces the .msg attribute of the HTTPResponse # with .headers, because urllib clients expect the response to # have the reason in .msg. It would be good to mark this # attribute is deprecated and get then to use info() or # .headers. r.msg = r.reason return r
python
def do_open(self, http_class, req, **http_conn_args): host = req.host if not host: raise URLError('no host given') # will parse host:port h = http_class(host, timeout=req.timeout, **http_conn_args) headers = dict(req.unredirected_hdrs) headers.update(dict((k, v) for k, v in req.headers.items() if k not in headers)) # TODO(jhylton): Should this be redesigned to handle # persistent connections? # We want to make an HTTP/1.1 request, but the addinfourl # class isn't prepared to deal with a persistent connection. # It will try to read all remaining data from the socket, # which will block while the server waits for the next request. # So make sure the connection gets closed after the (only) # request. headers["Connection"] = "close" headers = dict((name.title(), val) for name, val in headers.items()) if req._tunnel_host: tunnel_headers = {} proxy_auth_hdr = "Proxy-Authorization" if proxy_auth_hdr in headers: tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr] # Proxy-Authorization should not be sent to origin # server. del headers[proxy_auth_hdr] h.set_tunnel(req._tunnel_host, headers=tunnel_headers) try: h.request(req.get_method(), req.selector, req.data, headers) except socket.error as err: # timeout error h.close() raise URLError(err) else: r = h.getresponse() # If the server does not send us a 'Connection: close' header, # HTTPConnection assumes the socket should be left open. Manually # mark the socket to be closed when this response object goes away. if h.sock: h.sock.close() h.sock = None r.url = req.get_full_url() # This line replaces the .msg attribute of the HTTPResponse # with .headers, because urllib clients expect the response to # have the reason in .msg. It would be good to mark this # attribute is deprecated and get then to use info() or # .headers. r.msg = r.reason return r
[ "def", "do_open", "(", "self", ",", "http_class", ",", "req", ",", "*", "*", "http_conn_args", ")", ":", "host", "=", "req", ".", "host", "if", "not", "host", ":", "raise", "URLError", "(", "'no host given'", ")", "# will parse host:port", "h", "=", "htt...
Return an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client.
[ "Return", "an", "HTTPResponse", "object", "for", "the", "request", "using", "http_class", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1245-L1305
224,742
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener._open_generic_http
def _open_generic_http(self, connection_factory, url, data): """Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTTPConnection instance. - url is the url to retrieval or a host, relative-path pair. - data is payload for a POST request or None. """ user_passwd = None proxy_passwd= None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url # check whether the proxy contains authorization information proxy_passwd, host = splituser(host) # now we proceed with the url we want to obtain urltype, rest = splittype(selector) url = rest user_passwd = None if urltype.lower() != 'http': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) if proxy_bypass(realhost): host = realhost if not host: raise IOError('http error', 'no host given') if proxy_passwd: proxy_passwd = unquote(proxy_passwd) proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii') else: proxy_auth = None if user_passwd: user_passwd = unquote(user_passwd) auth = base64.b64encode(user_passwd.encode()).decode('ascii') else: auth = None http_conn = connection_factory(host) headers = {} if proxy_auth: headers["Proxy-Authorization"] = "Basic %s" % proxy_auth if auth: headers["Authorization"] = "Basic %s" % auth if realhost: headers["Host"] = realhost # Add Connection:close as we don't support persistent connections yet. # This helps in closing the socket and avoiding ResourceWarning headers["Connection"] = "close" for header, value in self.addheaders: headers[header] = value if data is not None: headers["Content-Type"] = "application/x-www-form-urlencoded" http_conn.request("POST", selector, data, headers) else: http_conn.request("GET", selector, headers=headers) try: response = http_conn.getresponse() except http_client.BadStatusLine: # something went wrong with the HTTP status line raise URLError("http protocol error: bad status line") # According to RFC 2616, "2xx" code indicates that the client's # request was successfully received, understood, and accepted. if 200 <= response.status < 300: return addinfourl(response, response.msg, "http:" + url, response.status) else: return self.http_error( url, response.fp, response.status, response.reason, response.msg, data)
python
def _open_generic_http(self, connection_factory, url, data): user_passwd = None proxy_passwd= None if isinstance(url, str): host, selector = splithost(url) if host: user_passwd, host = splituser(host) host = unquote(host) realhost = host else: host, selector = url # check whether the proxy contains authorization information proxy_passwd, host = splituser(host) # now we proceed with the url we want to obtain urltype, rest = splittype(selector) url = rest user_passwd = None if urltype.lower() != 'http': realhost = None else: realhost, rest = splithost(rest) if realhost: user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) if proxy_bypass(realhost): host = realhost if not host: raise IOError('http error', 'no host given') if proxy_passwd: proxy_passwd = unquote(proxy_passwd) proxy_auth = base64.b64encode(proxy_passwd.encode()).decode('ascii') else: proxy_auth = None if user_passwd: user_passwd = unquote(user_passwd) auth = base64.b64encode(user_passwd.encode()).decode('ascii') else: auth = None http_conn = connection_factory(host) headers = {} if proxy_auth: headers["Proxy-Authorization"] = "Basic %s" % proxy_auth if auth: headers["Authorization"] = "Basic %s" % auth if realhost: headers["Host"] = realhost # Add Connection:close as we don't support persistent connections yet. # This helps in closing the socket and avoiding ResourceWarning headers["Connection"] = "close" for header, value in self.addheaders: headers[header] = value if data is not None: headers["Content-Type"] = "application/x-www-form-urlencoded" http_conn.request("POST", selector, data, headers) else: http_conn.request("GET", selector, headers=headers) try: response = http_conn.getresponse() except http_client.BadStatusLine: # something went wrong with the HTTP status line raise URLError("http protocol error: bad status line") # According to RFC 2616, "2xx" code indicates that the client's # request was successfully received, understood, and accepted. if 200 <= response.status < 300: return addinfourl(response, response.msg, "http:" + url, response.status) else: return self.http_error( url, response.fp, response.status, response.reason, response.msg, data)
[ "def", "_open_generic_http", "(", "self", ",", "connection_factory", ",", "url", ",", "data", ")", ":", "user_passwd", "=", "None", "proxy_passwd", "=", "None", "if", "isinstance", "(", "url", ",", "str", ")", ":", "host", ",", "selector", "=", "splithost"...
Make an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTTPConnection instance. - url is the url to retrieval or a host, relative-path pair. - data is payload for a POST request or None.
[ "Make", "an", "HTTP", "connection", "using", "connection_class", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1782-L1872
224,743
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.open_http
def open_http(self, url, data=None): """Use HTTP protocol.""" return self._open_generic_http(http_client.HTTPConnection, url, data)
python
def open_http(self, url, data=None): return self._open_generic_http(http_client.HTTPConnection, url, data)
[ "def", "open_http", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "return", "self", ".", "_open_generic_http", "(", "http_client", ".", "HTTPConnection", ",", "url", ",", "data", ")" ]
Use HTTP protocol.
[ "Use", "HTTP", "protocol", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1874-L1876
224,744
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.http_error
def http_error(self, url, fp, errcode, errmsg, headers, data=None): """Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.""" # First check if there's a specific handler for this error name = 'http_error_%d' % errcode if hasattr(self, name): method = getattr(self, name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers)
python
def http_error(self, url, fp, errcode, errmsg, headers, data=None): # First check if there's a specific handler for this error name = 'http_error_%d' % errcode if hasattr(self, name): method = getattr(self, name) if data is None: result = method(url, fp, errcode, errmsg, headers) else: result = method(url, fp, errcode, errmsg, headers, data) if result: return result return self.http_error_default(url, fp, errcode, errmsg, headers)
[ "def", "http_error", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "# First check if there's a specific handler for this error", "name", "=", "'http_error_%d'", "%", "errcode", "if", "hasat...
Handle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.
[ "Handle", "http", "errors", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1878-L1892
224,745
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.open_file
def open_file(self, url): """Use local file or FTP depending on form of URL.""" if not isinstance(url, str): raise URLError('file error: proxy support for file protocol currently not implemented') if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': raise ValueError("file:// scheme is supported only on localhost") else: return self.open_local_file(url)
python
def open_file(self, url): if not isinstance(url, str): raise URLError('file error: proxy support for file protocol currently not implemented') if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/': raise ValueError("file:// scheme is supported only on localhost") else: return self.open_local_file(url)
[ "def", "open_file", "(", "self", ",", "url", ")", ":", "if", "not", "isinstance", "(", "url", ",", "str", ")", ":", "raise", "URLError", "(", "'file error: proxy support for file protocol currently not implemented'", ")", "if", "url", "[", ":", "2", "]", "==",...
Use local file or FTP depending on form of URL.
[ "Use", "local", "file", "or", "FTP", "depending", "on", "form", "of", "URL", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1909-L1916
224,746
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.open_local_file
def open_local_file(self, url): """Use local file.""" import future.backports.email.utils as email_utils import mimetypes host, file = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError as e: raise URLError(e.strerror, e.filename) size = stats.st_size modified = email_utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = email.message_from_string( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if (not port and socket.gethostbyname(host) in ((localhost(),) + thishost())): urlfile = file if file[:1] == '/': urlfile = 'file://' + file elif file[:2] == './': raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url) return addinfourl(open(localname, 'rb'), headers, urlfile) raise URLError('local file error: not on local host')
python
def open_local_file(self, url): import future.backports.email.utils as email_utils import mimetypes host, file = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError as e: raise URLError(e.strerror, e.filename) size = stats.st_size modified = email_utils.formatdate(stats.st_mtime, usegmt=True) mtype = mimetypes.guess_type(url)[0] headers = email.message_from_string( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified)) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if (not port and socket.gethostbyname(host) in ((localhost(),) + thishost())): urlfile = file if file[:1] == '/': urlfile = 'file://' + file elif file[:2] == './': raise ValueError("local file url may start with / or file:. Unknown url of type: %s" % url) return addinfourl(open(localname, 'rb'), headers, urlfile) raise URLError('local file error: not on local host')
[ "def", "open_local_file", "(", "self", ",", "url", ")", ":", "import", "future", ".", "backports", ".", "email", ".", "utils", "as", "email_utils", "import", "mimetypes", "host", ",", "file", "=", "splithost", "(", "url", ")", "localname", "=", "url2pathna...
Use local file.
[ "Use", "local", "file", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1918-L1948
224,747
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.open_ftp
def open_ftp(self, url): """Use FTP protocol.""" if not isinstance(url, str): raise URLError('ftp error: proxy support for ftp protocol currently not implemented') import mimetypes host, path = splithost(url) if not host: raise URLError('ftp error: no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '') host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT else: port = int(port) path, attrs = splitattr(path) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] if dirs and not dirs[0]: dirs[0] = '/' key = user, host, port, '/'.join(dirs) # XXX thread unsafe! if len(self.ftpcache) > MAXFTPCACHE: # Prune the cache, rather arbitrarily for k in self.ftpcache.keys(): if k != key: v = self.ftpcache[k] del self.ftpcache[k] v.close() try: if key not in self.ftpcache: self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() (fp, retrlen) = self.ftpcache[key].retrfile(file, type) mtype = mimetypes.guess_type("ftp:" + url)[0] headers = "" if mtype: headers += "Content-Type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-Length: %d\n" % retrlen headers = email.message_from_string(headers) return addinfourl(fp, headers, "ftp:" + url) except ftperrors() as exp: raise_with_traceback(URLError('ftp error %r' % exp))
python
def open_ftp(self, url): if not isinstance(url, str): raise URLError('ftp error: proxy support for ftp protocol currently not implemented') import mimetypes host, path = splithost(url) if not host: raise URLError('ftp error: no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '') host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT else: port = int(port) path, attrs = splitattr(path) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] if dirs and not dirs[0]: dirs[0] = '/' key = user, host, port, '/'.join(dirs) # XXX thread unsafe! if len(self.ftpcache) > MAXFTPCACHE: # Prune the cache, rather arbitrarily for k in self.ftpcache.keys(): if k != key: v = self.ftpcache[k] del self.ftpcache[k] v.close() try: if key not in self.ftpcache: self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() (fp, retrlen) = self.ftpcache[key].retrfile(file, type) mtype = mimetypes.guess_type("ftp:" + url)[0] headers = "" if mtype: headers += "Content-Type: %s\n" % mtype if retrlen is not None and retrlen >= 0: headers += "Content-Length: %d\n" % retrlen headers = email.message_from_string(headers) return addinfourl(fp, headers, "ftp:" + url) except ftperrors() as exp: raise_with_traceback(URLError('ftp error %r' % exp))
[ "def", "open_ftp", "(", "self", ",", "url", ")", ":", "if", "not", "isinstance", "(", "url", ",", "str", ")", ":", "raise", "URLError", "(", "'ftp error: proxy support for ftp protocol currently not implemented'", ")", "import", "mimetypes", "host", ",", "path", ...
Use FTP protocol.
[ "Use", "FTP", "protocol", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L1950-L2006
224,748
PythonCharmers/python-future
src/future/backports/urllib/request.py
URLopener.open_data
def open_data(self, url, data=None): """Use "data" URL.""" if not isinstance(url, str): raise URLError('data error: proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value try: [type, data] = url.split(',', 1) except ValueError: raise IOError('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': # XXX is this encoding/decoding ok? data = base64.decodebytes(data.encode('ascii')).decode('latin-1') else: data = unquote(data) msg.append('Content-Length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) headers = email.message_from_string(msg) f = io.StringIO(msg) #f.fileno = None # needed for addinfourl return addinfourl(f, headers, url)
python
def open_data(self, url, data=None): if not isinstance(url, str): raise URLError('data error: proxy support for data protocol currently not implemented') # ignore POSTed data # # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" parameter ) # data := *urlchar # parameter := attribute "=" value try: [type, data] = url.split(',', 1) except ValueError: raise IOError('data error', 'bad data URL') if not type: type = 'text/plain;charset=US-ASCII' semi = type.rfind(';') if semi >= 0 and '=' not in type[semi:]: encoding = type[semi+1:] type = type[:semi] else: encoding = '' msg = [] msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(time.time()))) msg.append('Content-type: %s' % type) if encoding == 'base64': # XXX is this encoding/decoding ok? data = base64.decodebytes(data.encode('ascii')).decode('latin-1') else: data = unquote(data) msg.append('Content-Length: %d' % len(data)) msg.append('') msg.append(data) msg = '\n'.join(msg) headers = email.message_from_string(msg) f = io.StringIO(msg) #f.fileno = None # needed for addinfourl return addinfourl(f, headers, url)
[ "def", "open_data", "(", "self", ",", "url", ",", "data", "=", "None", ")", ":", "if", "not", "isinstance", "(", "url", ",", "str", ")", ":", "raise", "URLError", "(", "'data error: proxy support for data protocol currently not implemented'", ")", "# ignore POSTed...
Use "data" URL.
[ "Use", "data", "URL", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2008-L2047
224,749
PythonCharmers/python-future
src/future/backports/urllib/request.py
FancyURLopener.prompt_user_passwd
def prompt_user_passwd(self, host, realm): """Override this in a GUI environment!""" import getpass try: user = input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter password for %s in %s at %s: " % (user, realm, host)) return user, passwd except KeyboardInterrupt: print() return None, None
python
def prompt_user_passwd(self, host, realm): import getpass try: user = input("Enter username for %s at %s: " % (realm, host)) passwd = getpass.getpass("Enter password for %s in %s at %s: " % (user, realm, host)) return user, passwd except KeyboardInterrupt: print() return None, None
[ "def", "prompt_user_passwd", "(", "self", ",", "host", ",", "realm", ")", ":", "import", "getpass", "try", ":", "user", "=", "input", "(", "\"Enter username for %s at %s: \"", "%", "(", "realm", ",", "host", ")", ")", "passwd", "=", "getpass", ".", "getpas...
Override this in a GUI environment!
[ "Override", "this", "in", "a", "GUI", "environment!" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2247-L2257
224,750
PythonCharmers/python-future
src/libfuturize/fixes/fix_division_safe.py
FixDivisionSafe.match
def match(self, node): u""" Since the tree needs to be fixed once and only once if and only if it matches, we can start discarding matches after the first. """ if node.type == self.syms.term: div_idx = find_division(node) if div_idx is not False: # if expr1 or expr2 are obviously floats, we don't need to wrap in # old_div, as the behavior of division between any number and a float # should be the same in 2 or 3 if not is_floaty(node, div_idx): return clone_div_operands(node, div_idx) return False
python
def match(self, node): u""" Since the tree needs to be fixed once and only once if and only if it matches, we can start discarding matches after the first. """ if node.type == self.syms.term: div_idx = find_division(node) if div_idx is not False: # if expr1 or expr2 are obviously floats, we don't need to wrap in # old_div, as the behavior of division between any number and a float # should be the same in 2 or 3 if not is_floaty(node, div_idx): return clone_div_operands(node, div_idx) return False
[ "def", "match", "(", "self", ",", "node", ")", ":", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "term", ":", "div_idx", "=", "find_division", "(", "node", ")", "if", "div_idx", "is", "not", "False", ":", "# if expr1 or expr2 are obviously ...
u""" Since the tree needs to be fixed once and only once if and only if it matches, we can start discarding matches after the first.
[ "u", "Since", "the", "tree", "needs", "to", "be", "fixed", "once", "and", "only", "once", "if", "and", "only", "if", "it", "matches", "we", "can", "start", "discarding", "matches", "after", "the", "first", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libfuturize/fixes/fix_division_safe.py#L89-L102
224,751
PythonCharmers/python-future
src/future/backports/email/feedparser.py
BufferedSubFile.push
def push(self, data): """Push some new data into this object.""" # Handle any previous leftovers data, self._partial = self._partial + data, '' # Crack into lines, but preserve the newlines on the end of each parts = NLCRE_crack.split(data) # The *ahem* interesting behaviour of re.split when supplied grouping # parentheses is that the last element of the resulting list is the # data after the final RE. In the case of a NL/CR terminated string, # this is the empty string. self._partial = parts.pop() #GAN 29Mar09 bugs 1555570, 1721862 Confusion at 8K boundary ending with \r: # is there a \n to follow later? if not self._partial and parts and parts[-1].endswith('\r'): self._partial = parts.pop(-2)+parts.pop() # parts is a list of strings, alternating between the line contents # and the eol character(s). Gather up a list of lines after # re-attaching the newlines. lines = [] for i in range(len(parts) // 2): lines.append(parts[i*2] + parts[i*2+1]) self.pushlines(lines)
python
def push(self, data): # Handle any previous leftovers data, self._partial = self._partial + data, '' # Crack into lines, but preserve the newlines on the end of each parts = NLCRE_crack.split(data) # The *ahem* interesting behaviour of re.split when supplied grouping # parentheses is that the last element of the resulting list is the # data after the final RE. In the case of a NL/CR terminated string, # this is the empty string. self._partial = parts.pop() #GAN 29Mar09 bugs 1555570, 1721862 Confusion at 8K boundary ending with \r: # is there a \n to follow later? if not self._partial and parts and parts[-1].endswith('\r'): self._partial = parts.pop(-2)+parts.pop() # parts is a list of strings, alternating between the line contents # and the eol character(s). Gather up a list of lines after # re-attaching the newlines. lines = [] for i in range(len(parts) // 2): lines.append(parts[i*2] + parts[i*2+1]) self.pushlines(lines)
[ "def", "push", "(", "self", ",", "data", ")", ":", "# Handle any previous leftovers", "data", ",", "self", ".", "_partial", "=", "self", ".", "_partial", "+", "data", ",", "''", "# Crack into lines, but preserve the newlines on the end of each", "parts", "=", "NLCRE...
Push some new data into this object.
[ "Push", "some", "new", "data", "into", "this", "object", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/feedparser.py#L102-L123
224,752
PythonCharmers/python-future
src/future/backports/email/feedparser.py
FeedParser.close
def close(self): """Parse all remaining data and return the root message object.""" self._input.close() self._call_parse() root = self._pop_message() assert not self._msgstack # Look for final set of defects if root.get_content_maintype() == 'multipart' \ and not root.is_multipart(): defect = errors.MultipartInvariantViolationDefect() self.policy.handle_defect(root, defect) return root
python
def close(self): self._input.close() self._call_parse() root = self._pop_message() assert not self._msgstack # Look for final set of defects if root.get_content_maintype() == 'multipart' \ and not root.is_multipart(): defect = errors.MultipartInvariantViolationDefect() self.policy.handle_defect(root, defect) return root
[ "def", "close", "(", "self", ")", ":", "self", ".", "_input", ".", "close", "(", ")", "self", ".", "_call_parse", "(", ")", "root", "=", "self", ".", "_pop_message", "(", ")", "assert", "not", "self", ".", "_msgstack", "# Look for final set of defects", ...
Parse all remaining data and return the root message object.
[ "Parse", "all", "remaining", "data", "and", "return", "the", "root", "message", "object", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/feedparser.py#L185-L196
224,753
PythonCharmers/python-future
src/future/builtins/newround.py
from_float_26
def from_float_26(f): """Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625. >>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(-float('inf')) Decimal('-Infinity') >>> Decimal.from_float(-0.0) Decimal('-0') """ import math as _math from decimal import _dec_from_triple # only available on Py2.6 and Py2.7 (not 3.3) if isinstance(f, (int, long)): # handle integer inputs return Decimal(f) if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float return Decimal(repr(f)) if _math.copysign(1.0, f) == 1.0: sign = 0 else: sign = 1 n, d = abs(f).as_integer_ratio() # int.bit_length() method doesn't exist on Py2.6: def bit_length(d): if d != 0: return len(bin(abs(d))) - 2 else: return 0 k = bit_length(d) - 1 result = _dec_from_triple(sign, str(n*5**k), -k) return result
python
def from_float_26(f): import math as _math from decimal import _dec_from_triple # only available on Py2.6 and Py2.7 (not 3.3) if isinstance(f, (int, long)): # handle integer inputs return Decimal(f) if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float return Decimal(repr(f)) if _math.copysign(1.0, f) == 1.0: sign = 0 else: sign = 1 n, d = abs(f).as_integer_ratio() # int.bit_length() method doesn't exist on Py2.6: def bit_length(d): if d != 0: return len(bin(abs(d))) - 2 else: return 0 k = bit_length(d) - 1 result = _dec_from_triple(sign, str(n*5**k), -k) return result
[ "def", "from_float_26", "(", "f", ")", ":", "import", "math", "as", "_math", "from", "decimal", "import", "_dec_from_triple", "# only available on Py2.6 and Py2.7 (not 3.3)", "if", "isinstance", "(", "f", ",", "(", "int", ",", "long", ")", ")", ":", "# handle in...
Converts a float to a decimal number, exactly. Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. The exact equivalent of the value in decimal is 0.1000000000000000055511151231257827021181583404541015625. >>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(-float('inf')) Decimal('-Infinity') >>> Decimal.from_float(-0.0) Decimal('-0')
[ "Converts", "a", "float", "to", "a", "decimal", "number", "exactly", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/builtins/newround.py#L55-L96
224,754
PythonCharmers/python-future
src/libpasteurize/fixes/fix_annotations.py
FixAnnotations.transform
def transform(self, node, results): u""" This just strips annotations from the funcdef completely. """ params = results.get(u"params") ret = results.get(u"ret") if ret is not None: assert ret.prev_sibling.type == token.RARROW, u"Invalid return annotation" self.warn_once(node, reason=warning_text) ret.prev_sibling.remove() ret.remove() if params is None: return if params.type == syms.typedargslist: # more than one param in a typedargslist for param in params.children: if param.type == syms.tname: self.warn_once(node, reason=warning_text) param.replace(param_without_annotations(param)) elif params.type == syms.tname: # one param self.warn_once(node, reason=warning_text) params.replace(param_without_annotations(params))
python
def transform(self, node, results): u""" This just strips annotations from the funcdef completely. """ params = results.get(u"params") ret = results.get(u"ret") if ret is not None: assert ret.prev_sibling.type == token.RARROW, u"Invalid return annotation" self.warn_once(node, reason=warning_text) ret.prev_sibling.remove() ret.remove() if params is None: return if params.type == syms.typedargslist: # more than one param in a typedargslist for param in params.children: if param.type == syms.tname: self.warn_once(node, reason=warning_text) param.replace(param_without_annotations(param)) elif params.type == syms.tname: # one param self.warn_once(node, reason=warning_text) params.replace(param_without_annotations(params))
[ "def", "transform", "(", "self", ",", "node", ",", "results", ")", ":", "params", "=", "results", ".", "get", "(", "u\"params\"", ")", "ret", "=", "results", ".", "get", "(", "u\"ret\"", ")", "if", "ret", "is", "not", "None", ":", "assert", "ret", ...
u""" This just strips annotations from the funcdef completely.
[ "u", "This", "just", "strips", "annotations", "from", "the", "funcdef", "completely", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/libpasteurize/fixes/fix_annotations.py#L27-L48
224,755
PythonCharmers/python-future
src/future/types/newint.py
newint.to_bytes
def to_bytes(self, length, byteorder='big', signed=False): """ Return an array of bytes representing an integer. The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. """ if length < 0: raise ValueError("length argument must be non-negative") if length == 0 and self == 0: return newbytes() if signed and self < 0: bits = length * 8 num = (2**bits) + self if num <= 0: raise OverflowError("int too smal to convert") else: if self < 0: raise OverflowError("can't convert negative int to unsigned") num = self if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") h = b'%x' % num s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex')) if signed: high_set = s[0] & 0x80 if self > 0 and high_set: raise OverflowError("int too big to convert") if self < 0 and not high_set: raise OverflowError("int too small to convert") if len(s) > length: raise OverflowError("int too big to convert") return s if byteorder == 'big' else s[::-1]
python
def to_bytes(self, length, byteorder='big', signed=False): if length < 0: raise ValueError("length argument must be non-negative") if length == 0 and self == 0: return newbytes() if signed and self < 0: bits = length * 8 num = (2**bits) + self if num <= 0: raise OverflowError("int too smal to convert") else: if self < 0: raise OverflowError("can't convert negative int to unsigned") num = self if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") h = b'%x' % num s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex')) if signed: high_set = s[0] & 0x80 if self > 0 and high_set: raise OverflowError("int too big to convert") if self < 0 and not high_set: raise OverflowError("int too small to convert") if len(s) > length: raise OverflowError("int too big to convert") return s if byteorder == 'big' else s[::-1]
[ "def", "to_bytes", "(", "self", ",", "length", ",", "byteorder", "=", "'big'", ",", "signed", "=", "False", ")", ":", "if", "length", "<", "0", ":", "raise", "ValueError", "(", "\"length argument must be non-negative\"", ")", "if", "length", "==", "0", "an...
Return an array of bytes representing an integer. The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
[ "Return", "an", "array", "of", "bytes", "representing", "an", "integer", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newint.py#L290-L333
224,756
PythonCharmers/python-future
src/future/types/newint.py
newint.from_bytes
def from_bytes(cls, mybytes, byteorder='big', signed=False): """ Return the integer represented by the given array of bytes. The mybytes argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument indicates whether two's complement is used to represent the integer. """ if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") if isinstance(mybytes, unicode): raise TypeError("cannot convert unicode objects to bytes") # mybytes can also be passed as a sequence of integers on Py3. # Test for this: elif isinstance(mybytes, collections.Iterable): mybytes = newbytes(mybytes) b = mybytes if byteorder == 'big' else mybytes[::-1] if len(b) == 0: b = b'\x00' # The encode() method has been disabled by newbytes, but Py2's # str has it: num = int(native(b).encode('hex'), 16) if signed and (b[0] & 0x80): num = num - (2 ** (len(b)*8)) return cls(num)
python
def from_bytes(cls, mybytes, byteorder='big', signed=False): if byteorder not in ('little', 'big'): raise ValueError("byteorder must be either 'little' or 'big'") if isinstance(mybytes, unicode): raise TypeError("cannot convert unicode objects to bytes") # mybytes can also be passed as a sequence of integers on Py3. # Test for this: elif isinstance(mybytes, collections.Iterable): mybytes = newbytes(mybytes) b = mybytes if byteorder == 'big' else mybytes[::-1] if len(b) == 0: b = b'\x00' # The encode() method has been disabled by newbytes, but Py2's # str has it: num = int(native(b).encode('hex'), 16) if signed and (b[0] & 0x80): num = num - (2 ** (len(b)*8)) return cls(num)
[ "def", "from_bytes", "(", "cls", ",", "mybytes", ",", "byteorder", "=", "'big'", ",", "signed", "=", "False", ")", ":", "if", "byteorder", "not", "in", "(", "'little'", ",", "'big'", ")", ":", "raise", "ValueError", "(", "\"byteorder must be either 'little' ...
Return the integer represented by the given array of bytes. The mybytes argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. The byteorder argument determines the byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. The signed keyword-only argument indicates whether two's complement is used to represent the integer.
[ "Return", "the", "integer", "represented", "by", "the", "given", "array", "of", "bytes", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newint.py#L336-L369
224,757
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
parsedate_tz
def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ res = _parsedate_tz(data) if not res: return if res[9] is None: res[9] = 0 return tuple(res)
python
def parsedate_tz(data): res = _parsedate_tz(data) if not res: return if res[9] is None: res[9] = 0 return tuple(res)
[ "def", "parsedate_tz", "(", "data", ")", ":", "res", "=", "_parsedate_tz", "(", "data", ")", "if", "not", "res", ":", "return", "if", "res", "[", "9", "]", "is", "None", ":", "res", "[", "9", "]", "=", "0", "return", "tuple", "(", "res", ")" ]
Convert a date string to a time tuple. Accounts for military timezones.
[ "Convert", "a", "date", "string", "to", "a", "time", "tuple", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L51-L61
224,758
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
parsedate
def parsedate(data): """Convert a time string to a time tuple.""" t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t
python
def parsedate(data): t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t
[ "def", "parsedate", "(", "data", ")", ":", "t", "=", "parsedate_tz", "(", "data", ")", "if", "isinstance", "(", "t", ",", "tuple", ")", ":", "return", "t", "[", ":", "9", "]", "else", ":", "return", "t" ]
Convert a time string to a time tuple.
[ "Convert", "a", "time", "string", "to", "a", "time", "tuple", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L180-L186
224,759
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
AddrlistClass.gotonext
def gotonext(self): """Skip white space and extract comments.""" wslist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': if self.field[self.pos] not in '\n\r': wslist.append(self.field[self.pos]) self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break return EMPTYSTRING.join(wslist)
python
def gotonext(self): wslist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': if self.field[self.pos] not in '\n\r': wslist.append(self.field[self.pos]) self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break return EMPTYSTRING.join(wslist)
[ "def", "gotonext", "(", "self", ")", ":", "wslist", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "LWS", "+", "'\\n\\r'"...
Skip white space and extract comments.
[ "Skip", "white", "space", "and", "extract", "comments", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L238-L250
224,760
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
AddrlistClass.getaddrlist
def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
python
def getaddrlist(self): result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
[ "def", "getaddrlist", "(", "self", ")", ":", "result", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "ad", "=", "self", ".", "getaddress", "(", ")", "if", "ad", ":", "result", "+=", "ad", "else", "...
Parse all addresses. Returns a list containing all of the addresses.
[ "Parse", "all", "addresses", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L252-L264
224,761
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
AddrlistClass.getaddress
def getaddress(self): """Parse the next address.""" self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist
python
def getaddress(self): self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist
[ "def", "getaddress", "(", "self", ")", ":", "self", ".", "commentlist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "oldpos", "=", "self", ".", "pos", "oldcl", "=", "self", ".", "commentlist", "plist", "=", "self", ".", "getphraselist", "(", ")...
Parse the next address.
[ "Parse", "the", "next", "address", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L266-L323
224,762
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
AddrlistClass.getaddrspec
def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): preserve_ws = True if self.field[self.pos] == '.': if aslist and not aslist[-1].strip(): aslist.pop() aslist.append('.') self.pos += 1 preserve_ws = False elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: if aslist and not aslist[-1].strip(): aslist.pop() break else: aslist.append(self.getatom()) ws = self.gotonext() if preserve_ws and ws: aslist.append(ws) if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain()
python
def getaddrspec(self): aslist = [] self.gotonext() while self.pos < len(self.field): preserve_ws = True if self.field[self.pos] == '.': if aslist and not aslist[-1].strip(): aslist.pop() aslist.append('.') self.pos += 1 preserve_ws = False elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: if aslist and not aslist[-1].strip(): aslist.pop() break else: aslist.append(self.getatom()) ws = self.gotonext() if preserve_ws and ws: aslist.append(ws) if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain()
[ "def", "getaddrspec", "(", "self", ")", ":", "aslist", "=", "[", "]", "self", ".", "gotonext", "(", ")", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "preserve_ws", "=", "True", "if", "self", ".", "field", "[", "s...
Parse an RFC 2822 addr-spec.
[ "Parse", "an", "RFC", "2822", "addr", "-", "spec", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L357-L388
224,763
PythonCharmers/python-future
src/future/backports/email/_parseaddr.py
AddrlistClass.getatom
def getatom(self, atomends=None): """Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).""" atomlist = [''] if atomends is None: atomends = self.atomends while self.pos < len(self.field): if self.field[self.pos] in atomends: break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist)
python
def getatom(self, atomends=None): atomlist = [''] if atomends is None: atomends = self.atomends while self.pos < len(self.field): if self.field[self.pos] in atomends: break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist)
[ "def", "getatom", "(", "self", ",", "atomends", "=", "None", ")", ":", "atomlist", "=", "[", "''", "]", "if", "atomends", "is", "None", ":", "atomends", "=", "self", ".", "atomends", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field...
Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).
[ "Parse", "an", "RFC", "2822", "atom", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L458-L476
224,764
PythonCharmers/python-future
src/future/backports/email/header.py
decode_header
def decode_header(header): """Decode a message header value without converting charset. Returns a list of (string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. header may be a string that may or may not contain RFC2047 encoded words, or it may be a Header object. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). """ # If it is a Header object, we can just return the encoded chunks. if hasattr(header, '_chunks'): return [(_charset._encode(string, str(charset)), str(charset)) for string, charset in header._chunks] # If no encoding, just return the header with no charset. if not ecre.search(header): return [(header, None)] # First step is to parse all the encoded parts into triplets of the form # (encoded_string, encoding, charset). For unencoded strings, the last # two parts will be None. words = [] for line in header.splitlines(): parts = ecre.split(line) first = True while parts: unencoded = parts.pop(0) if first: unencoded = unencoded.lstrip() first = False if unencoded: words.append((unencoded, None, None)) if parts: charset = parts.pop(0).lower() encoding = parts.pop(0).lower() encoded = parts.pop(0) words.append((encoded, encoding, charset)) # Now loop over words and remove words that consist of whitespace # between two encoded strings. import sys droplist = [] for n, w in enumerate(words): if n>1 and w[1] and words[n-2][1] and words[n-1][0].isspace(): droplist.append(n-1) for d in reversed(droplist): del words[d] # The next step is to decode each encoded word by applying the reverse # base64 or quopri transformation. decoded_words is now a list of the # form (decoded_word, charset). decoded_words = [] for encoded_string, encoding, charset in words: if encoding is None: # This is an unencoded word. decoded_words.append((encoded_string, charset)) elif encoding == 'q': word = header_decode(encoded_string) decoded_words.append((word, charset)) elif encoding == 'b': paderr = len(encoded_string) % 4 # Postel's law: add missing padding if paderr: encoded_string += '==='[:4 - paderr] try: word = base64mime.decode(encoded_string) except binascii.Error: raise HeaderParseError('Base64 decoding error') else: decoded_words.append((word, charset)) else: raise AssertionError('Unexpected encoding: ' + encoding) # Now convert all words to bytes and collapse consecutive runs of # similarly encoded words. collapsed = [] last_word = last_charset = None for word, charset in decoded_words: if isinstance(word, str): word = bytes(word, 'raw-unicode-escape') if last_word is None: last_word = word last_charset = charset elif charset != last_charset: collapsed.append((last_word, last_charset)) last_word = word last_charset = charset elif last_charset is None: last_word += BSPACE + word else: last_word += word collapsed.append((last_word, last_charset)) return collapsed
python
def decode_header(header): # If it is a Header object, we can just return the encoded chunks. if hasattr(header, '_chunks'): return [(_charset._encode(string, str(charset)), str(charset)) for string, charset in header._chunks] # If no encoding, just return the header with no charset. if not ecre.search(header): return [(header, None)] # First step is to parse all the encoded parts into triplets of the form # (encoded_string, encoding, charset). For unencoded strings, the last # two parts will be None. words = [] for line in header.splitlines(): parts = ecre.split(line) first = True while parts: unencoded = parts.pop(0) if first: unencoded = unencoded.lstrip() first = False if unencoded: words.append((unencoded, None, None)) if parts: charset = parts.pop(0).lower() encoding = parts.pop(0).lower() encoded = parts.pop(0) words.append((encoded, encoding, charset)) # Now loop over words and remove words that consist of whitespace # between two encoded strings. import sys droplist = [] for n, w in enumerate(words): if n>1 and w[1] and words[n-2][1] and words[n-1][0].isspace(): droplist.append(n-1) for d in reversed(droplist): del words[d] # The next step is to decode each encoded word by applying the reverse # base64 or quopri transformation. decoded_words is now a list of the # form (decoded_word, charset). decoded_words = [] for encoded_string, encoding, charset in words: if encoding is None: # This is an unencoded word. decoded_words.append((encoded_string, charset)) elif encoding == 'q': word = header_decode(encoded_string) decoded_words.append((word, charset)) elif encoding == 'b': paderr = len(encoded_string) % 4 # Postel's law: add missing padding if paderr: encoded_string += '==='[:4 - paderr] try: word = base64mime.decode(encoded_string) except binascii.Error: raise HeaderParseError('Base64 decoding error') else: decoded_words.append((word, charset)) else: raise AssertionError('Unexpected encoding: ' + encoding) # Now convert all words to bytes and collapse consecutive runs of # similarly encoded words. collapsed = [] last_word = last_charset = None for word, charset in decoded_words: if isinstance(word, str): word = bytes(word, 'raw-unicode-escape') if last_word is None: last_word = word last_charset = charset elif charset != last_charset: collapsed.append((last_word, last_charset)) last_word = word last_charset = charset elif last_charset is None: last_word += BSPACE + word else: last_word += word collapsed.append((last_word, last_charset)) return collapsed
[ "def", "decode_header", "(", "header", ")", ":", "# If it is a Header object, we can just return the encoded chunks.", "if", "hasattr", "(", "header", ",", "'_chunks'", ")", ":", "return", "[", "(", "_charset", ".", "_encode", "(", "string", ",", "str", "(", "char...
Decode a message header value without converting charset. Returns a list of (string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. header may be a string that may or may not contain RFC2047 encoded words, or it may be a Header object. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception).
[ "Decode", "a", "message", "header", "value", "without", "converting", "charset", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/header.py#L62-L154
224,765
PythonCharmers/python-future
src/future/backports/email/header.py
Header.append
def append(self, s, charset=None, errors='strict'): """Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string. """ if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) if not isinstance(s, str): input_charset = charset.input_codec or 'us-ascii' if input_charset == _charset.UNKNOWN8BIT: s = s.decode('us-ascii', 'surrogateescape') else: s = s.decode(input_charset, errors) # Ensure that the bytes we're storing can be decoded to the output # character set, otherwise an early error is raised. output_charset = charset.output_codec or 'us-ascii' if output_charset != _charset.UNKNOWN8BIT: try: s.encode(output_charset, errors) except UnicodeEncodeError: if output_charset!='us-ascii': raise charset = UTF8 self._chunks.append((s, charset))
python
def append(self, s, charset=None, errors='strict'): if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) if not isinstance(s, str): input_charset = charset.input_codec or 'us-ascii' if input_charset == _charset.UNKNOWN8BIT: s = s.decode('us-ascii', 'surrogateescape') else: s = s.decode(input_charset, errors) # Ensure that the bytes we're storing can be decoded to the output # character set, otherwise an early error is raised. output_charset = charset.output_codec or 'us-ascii' if output_charset != _charset.UNKNOWN8BIT: try: s.encode(output_charset, errors) except UnicodeEncodeError: if output_charset!='us-ascii': raise charset = UTF8 self._chunks.append((s, charset))
[ "def", "append", "(", "self", ",", "s", ",", "charset", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "charset", "is", "None", ":", "charset", "=", "self", ".", "_charset", "elif", "not", "isinstance", "(", "charset", ",", "Charset", "...
Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is false), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In either case, when producing an RFC 2822 compliant header using RFC 2047 rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded to the output codec, a UnicodeError will be raised. Optional `errors' is passed as the errors argument to the decode call if s is a byte string.
[ "Append", "a", "string", "to", "the", "MIME", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/header.py#L268-L309
224,766
PythonCharmers/python-future
src/future/backports/email/header.py
Header.encode
def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'): r"""Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed. """ self._normalize() if maxlinelen is None: maxlinelen = self._maxlinelen # A maxlinelen of 0 means don't wrap. For all practical purposes, # choosing a huge number here accomplishes that and makes the # _ValueFormatter algorithm much simpler. if maxlinelen == 0: maxlinelen = 1000000 formatter = _ValueFormatter(self._headerlen, maxlinelen, self._continuation_ws, splitchars) lastcs = None hasspace = lastspace = None for string, charset in self._chunks: if hasspace is not None: hasspace = string and self._nonctext(string[0]) import sys if lastcs not in (None, 'us-ascii'): if not hasspace or charset not in (None, 'us-ascii'): formatter.add_transition() elif charset not in (None, 'us-ascii') and not lastspace: formatter.add_transition() lastspace = string and self._nonctext(string[-1]) lastcs = charset hasspace = False lines = string.splitlines() if lines: formatter.feed('', lines[0], charset) else: formatter.feed('', '', charset) for line in lines[1:]: formatter.newline() if charset.header_encoding is not None: formatter.feed(self._continuation_ws, ' ' + line.lstrip(), charset) else: sline = line.lstrip() fws = line[:len(line)-len(sline)] formatter.feed(fws, sline, charset) if len(lines) > 1: formatter.newline() if self._chunks: formatter.add_transition() value = formatter._str(linesep) if _embeded_header.search(value): raise HeaderParseError("header value appears to contain " "an embedded header: {!r}".format(value)) return value
python
def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'): r"""Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed. """ self._normalize() if maxlinelen is None: maxlinelen = self._maxlinelen # A maxlinelen of 0 means don't wrap. For all practical purposes, # choosing a huge number here accomplishes that and makes the # _ValueFormatter algorithm much simpler. if maxlinelen == 0: maxlinelen = 1000000 formatter = _ValueFormatter(self._headerlen, maxlinelen, self._continuation_ws, splitchars) lastcs = None hasspace = lastspace = None for string, charset in self._chunks: if hasspace is not None: hasspace = string and self._nonctext(string[0]) import sys if lastcs not in (None, 'us-ascii'): if not hasspace or charset not in (None, 'us-ascii'): formatter.add_transition() elif charset not in (None, 'us-ascii') and not lastspace: formatter.add_transition() lastspace = string and self._nonctext(string[-1]) lastcs = charset hasspace = False lines = string.splitlines() if lines: formatter.feed('', lines[0], charset) else: formatter.feed('', '', charset) for line in lines[1:]: formatter.newline() if charset.header_encoding is not None: formatter.feed(self._continuation_ws, ' ' + line.lstrip(), charset) else: sline = line.lstrip() fws = line[:len(line)-len(sline)] formatter.feed(fws, sline, charset) if len(lines) > 1: formatter.newline() if self._chunks: formatter.add_transition() value = formatter._str(linesep) if _embeded_header.search(value): raise HeaderParseError("header value appears to contain " "an embedded header: {!r}".format(value)) return value
[ "def", "encode", "(", "self", ",", "splitchars", "=", "';, \\t'", ",", "maxlinelen", "=", "None", ",", "linesep", "=", "'\\n'", ")", ":", "self", ".", "_normalize", "(", ")", "if", "maxlinelen", "is", "None", ":", "maxlinelen", "=", "self", ".", "_maxl...
r"""Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encode (with Base64 or quoted-printable) header strings. In addition, there is a 75-character length limit on any given encoded header field, so line-wrapping must be performed, even with double-byte character sets. Optional maxlinelen specifies the maximum length of each generated line, exclusive of the linesep string. Individual lines may be longer than maxlinelen if a folding point cannot be found. The first line will be shorter by the length of the header name plus ": " if a header name was specified at Header construction time. The default value for maxlinelen is determined at header construction time. Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822's `higher level syntactic breaks': split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 encoded lines. Optional linesep is a string to be used to separate the lines of the value. The default value is the most useful for typical Python applications, but it can be set to \r\n to produce RFC-compliant line separators when needed.
[ "r", "Encode", "a", "message", "header", "into", "an", "RFC", "-", "compliant", "format", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/header.py#L316-L395
224,767
PythonCharmers/python-future
src/future/backports/email/message.py
_formatparam
def _formatparam(param, value=None, quote=True): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. If it contains non-ascii characters it will likewise be encoded according to RFC2231 rules, using the utf-8 charset and a null language. """ if value is not None and len(value) > 0: # A tuple is used for RFC 2231 encoded parameter values where items # are (charset, language, value). charset is a string, not a Charset # instance. RFC 2231 encoded values are never quoted, per RFC. if isinstance(value, tuple): # Encode as per RFC 2231 param += '*' value = utils.encode_rfc2231(value[2], value[0], value[1]) return '%s=%s' % (param, value) else: try: value.encode('ascii') except UnicodeEncodeError: param += '*' value = utils.encode_rfc2231(value, 'utf-8', '') return '%s=%s' % (param, value) # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
python
def _formatparam(param, value=None, quote=True): if value is not None and len(value) > 0: # A tuple is used for RFC 2231 encoded parameter values where items # are (charset, language, value). charset is a string, not a Charset # instance. RFC 2231 encoded values are never quoted, per RFC. if isinstance(value, tuple): # Encode as per RFC 2231 param += '*' value = utils.encode_rfc2231(value[2], value[0], value[1]) return '%s=%s' % (param, value) else: try: value.encode('ascii') except UnicodeEncodeError: param += '*' value = utils.encode_rfc2231(value, 'utf-8', '') return '%s=%s' % (param, value) # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
[ "def", "_formatparam", "(", "param", ",", "value", "=", "None", ",", "quote", "=", "True", ")", ":", "if", "value", "is", "not", "None", "and", "len", "(", "value", ")", ">", "0", ":", "# A tuple is used for RFC 2231 encoded parameter values where items", "# a...
Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. If it contains non-ascii characters it will likewise be encoded according to RFC2231 rules, using the utf-8 charset and a null language.
[ "Convenience", "function", "to", "format", "and", "return", "a", "key", "=", "value", "pair", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L44-L76
224,768
PythonCharmers/python-future
src/future/backports/email/message.py
Message.attach
def attach(self, payload): """Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. """ if self._payload is None: self._payload = [payload] else: self._payload.append(payload)
python
def attach(self, payload): if self._payload is None: self._payload = [payload] else: self._payload.append(payload)
[ "def", "attach", "(", "self", ",", "payload", ")", ":", "if", "self", ".", "_payload", "is", "None", ":", "self", ".", "_payload", "=", "[", "payload", "]", "else", ":", "self", ".", "_payload", ".", "append", "(", "payload", ")" ]
Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead.
[ "Add", "the", "given", "payload", "to", "the", "current", "payload", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L174-L184
224,769
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_payload
def get_payload(self, i=None, decode=False): """Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. """ # Here is the logic table for this code, based on the email5.0.0 code: # i decode is_multipart result # ------ ------ ------------ ------------------------------ # None True True None # i True True None # None False True _payload (a list) # i False True _payload element i (a Message) # i False False error (not a list) # i True False error (not a list) # None False False _payload # None True False _payload decoded (bytes) # Note that Barry planned to factor out the 'decode' case, but that # isn't so easy now that we handle the 8 bit data, which needs to be # converted in both the decode and non-decode path. if self.is_multipart(): if decode: return None if i is None: return self._payload else: return self._payload[i] # For backward compatibility, Use isinstance and this error message # instead of the more logical is_multipart test. if i is not None and not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) payload = self._payload # cte might be a Header, so for now stringify it. cte = str(self.get('content-transfer-encoding', '')).lower() # payload may be bytes here. if isinstance(payload, str): payload = str(payload) # for Python-Future, so surrogateescape works if utils._has_surrogates(payload): bpayload = payload.encode('ascii', 'surrogateescape') if not decode: try: payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace') except LookupError: payload = bpayload.decode('ascii', 'replace') elif decode: try: bpayload = payload.encode('ascii') except UnicodeError: # This won't happen for RFC compliant messages (messages # containing only ASCII codepoints in the unicode input). # If it does happen, turn the string into bytes in a way # guaranteed not to fail. bpayload = payload.encode('raw-unicode-escape') if not decode: return payload if cte == 'quoted-printable': return utils._qdecode(bpayload) elif cte == 'base64': # XXX: this is a bit of a hack; decode_b should probably be factored # out somewhere, but I haven't figured out where yet. value, defects = decode_b(b''.join(bpayload.splitlines())) for defect in defects: self.policy.handle_defect(self, defect) return value elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): in_file = BytesIO(bpayload) out_file = BytesIO() try: uu.decode(in_file, out_file, quiet=True) return out_file.getvalue() except uu.Error: # Some decoding problem return bpayload if isinstance(payload, str): return bpayload return payload
python
def get_payload(self, i=None, decode=False): # Here is the logic table for this code, based on the email5.0.0 code: # i decode is_multipart result # ------ ------ ------------ ------------------------------ # None True True None # i True True None # None False True _payload (a list) # i False True _payload element i (a Message) # i False False error (not a list) # i True False error (not a list) # None False False _payload # None True False _payload decoded (bytes) # Note that Barry planned to factor out the 'decode' case, but that # isn't so easy now that we handle the 8 bit data, which needs to be # converted in both the decode and non-decode path. if self.is_multipart(): if decode: return None if i is None: return self._payload else: return self._payload[i] # For backward compatibility, Use isinstance and this error message # instead of the more logical is_multipart test. if i is not None and not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) payload = self._payload # cte might be a Header, so for now stringify it. cte = str(self.get('content-transfer-encoding', '')).lower() # payload may be bytes here. if isinstance(payload, str): payload = str(payload) # for Python-Future, so surrogateescape works if utils._has_surrogates(payload): bpayload = payload.encode('ascii', 'surrogateescape') if not decode: try: payload = bpayload.decode(self.get_param('charset', 'ascii'), 'replace') except LookupError: payload = bpayload.decode('ascii', 'replace') elif decode: try: bpayload = payload.encode('ascii') except UnicodeError: # This won't happen for RFC compliant messages (messages # containing only ASCII codepoints in the unicode input). # If it does happen, turn the string into bytes in a way # guaranteed not to fail. bpayload = payload.encode('raw-unicode-escape') if not decode: return payload if cte == 'quoted-printable': return utils._qdecode(bpayload) elif cte == 'base64': # XXX: this is a bit of a hack; decode_b should probably be factored # out somewhere, but I haven't figured out where yet. value, defects = decode_b(b''.join(bpayload.splitlines())) for defect in defects: self.policy.handle_defect(self, defect) return value elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): in_file = BytesIO(bpayload) out_file = BytesIO() try: uu.decode(in_file, out_file, quiet=True) return out_file.getvalue() except uu.Error: # Some decoding problem return bpayload if isinstance(payload, str): return bpayload return payload
[ "def", "get_payload", "(", "self", ",", "i", "=", "None", ",", "decode", "=", "False", ")", ":", "# Here is the logic table for this code, based on the email5.0.0 code:", "# i decode is_multipart result", "# ------ ------ ------------ ------------------------------", "# ...
Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned.
[ "Return", "a", "reference", "to", "the", "payload", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L186-L275
224,770
PythonCharmers/python-future
src/future/backports/email/message.py
Message.set_payload
def set_payload(self, payload, charset=None): """Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. """ self._payload = payload if charset is not None: self.set_charset(charset)
python
def set_payload(self, payload, charset=None): self._payload = payload if charset is not None: self.set_charset(charset)
[ "def", "set_payload", "(", "self", ",", "payload", ",", "charset", "=", "None", ")", ":", "self", ".", "_payload", "=", "payload", "if", "charset", "is", "not", "None", ":", "self", ".", "set_charset", "(", "charset", ")" ]
Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details.
[ "Set", "the", "payload", "to", "the", "given", "value", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L277-L285
224,771
PythonCharmers/python-future
src/future/backports/email/message.py
Message.set_charset
def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. """ if charset is None: self.del_param('charset') self._charset = None return if not isinstance(charset, Charset): charset = Charset(charset) self._charset = charset if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if charset != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
python
def set_charset(self, charset): if charset is None: self.del_param('charset') self._charset = None return if not isinstance(charset, Charset): charset = Charset(charset) self._charset = charset if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if charset != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
[ "def", "set_charset", "(", "self", ",", "charset", ")", ":", "if", "charset", "is", "None", ":", "self", ".", "del_param", "(", "'charset'", ")", "self", ".", "_charset", "=", "None", "return", "if", "not", "isinstance", "(", "charset", ",", "Charset", ...
Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed.
[ "Set", "the", "charset", "of", "the", "payload", "to", "a", "given", "character", "set", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L287-L323
224,772
PythonCharmers/python-future
src/future/backports/email/message.py
Message.values
def values(self): """Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [self.policy.header_fetch_parse(k, v) for k, v in self._headers]
python
def values(self): return [self.policy.header_fetch_parse(k, v) for k, v in self._headers]
[ "def", "values", "(", "self", ")", ":", "return", "[", "self", ".", "policy", ".", "header_fetch_parse", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", "]" ]
Return a list of all the message's header values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.
[ "Return", "a", "list", "of", "all", "the", "message", "s", "header", "values", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L395-L404
224,773
PythonCharmers/python-future
src/future/backports/email/message.py
Message.items
def items(self): """Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. """ return [(k, self.policy.header_fetch_parse(k, v)) for k, v in self._headers]
python
def items(self): return [(k, self.policy.header_fetch_parse(k, v)) for k, v in self._headers]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "k", ",", "self", ".", "policy", ".", "header_fetch_parse", "(", "k", ",", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", "]" ]
Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list.
[ "Get", "all", "the", "message", "s", "header", "fields", "and", "values", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L406-L415
224,774
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get
def get(self, name, failobj=None): """Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. """ name = name.lower() for k, v in self._headers: if k.lower() == name: return self.policy.header_fetch_parse(k, v) return failobj
python
def get(self, name, failobj=None): name = name.lower() for k, v in self._headers: if k.lower() == name: return self.policy.header_fetch_parse(k, v) return failobj
[ "def", "get", "(", "self", ",", "name", ",", "failobj", "=", "None", ")", ":", "name", "=", "name", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", ":", "if", "k", ".", "lower", "(", ")", "==", "name", ":", "retur...
Get a header value. Like __getitem__() but return failobj instead of None when the field is missing.
[ "Get", "a", "header", "value", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L417-L427
224,775
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_all
def get_all(self, name, failobj=None): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). """ values = [] name = name.lower() for k, v in self._headers: if k.lower() == name: values.append(self.policy.header_fetch_parse(k, v)) if not values: return failobj return values
python
def get_all(self, name, failobj=None): values = [] name = name.lower() for k, v in self._headers: if k.lower() == name: values.append(self.policy.header_fetch_parse(k, v)) if not values: return failobj return values
[ "def", "get_all", "(", "self", ",", "name", ",", "failobj", "=", "None", ")", ":", "values", "=", "[", "]", "name", "=", "name", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", ":", "if", "k", ".", "lower", "(", "...
Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None).
[ "Return", "a", "list", "of", "all", "the", "values", "for", "the", "named", "field", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L452-L468
224,776
PythonCharmers/python-future
src/future/backports/email/message.py
Message.add_header
def add_header(self, _name, _value, **_params): """Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it can be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Otherwise it will be encoded using the utf-8 charset and a language of ''. Examples: msg.add_header('content-disposition', 'attachment', filename='bud.gif') msg.add_header('content-disposition', 'attachment', filename=('utf-8', '', 'Fußballer.ppt')) msg.add_header('content-disposition', 'attachment', filename='Fußballer.ppt')) """ parts = [] for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) if _value is not None: parts.insert(0, _value) self[_name] = SEMISPACE.join(parts)
python
def add_header(self, _name, _value, **_params): parts = [] for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) if _value is not None: parts.insert(0, _value) self[_name] = SEMISPACE.join(parts)
[ "def", "add_header", "(", "self", ",", "_name", ",", "_value", ",", "*", "*", "_params", ")", ":", "parts", "=", "[", "]", "for", "k", ",", "v", "in", "_params", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "parts", ".", "append",...
Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it can be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Otherwise it will be encoded using the utf-8 charset and a language of ''. Examples: msg.add_header('content-disposition', 'attachment', filename='bud.gif') msg.add_header('content-disposition', 'attachment', filename=('utf-8', '', 'Fußballer.ppt')) msg.add_header('content-disposition', 'attachment', filename='Fußballer.ppt'))
[ "Extended", "header", "setting", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L470-L498
224,777
PythonCharmers/python-future
src/future/backports/email/message.py
Message.replace_header
def replace_header(self, _name, _value): """Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised. """ _name = _name.lower() for i, (k, v) in zip(range(len(self._headers)), self._headers): if k.lower() == _name: self._headers[i] = self.policy.header_store_parse(k, _value) break else: raise KeyError(_name)
python
def replace_header(self, _name, _value): _name = _name.lower() for i, (k, v) in zip(range(len(self._headers)), self._headers): if k.lower() == _name: self._headers[i] = self.policy.header_store_parse(k, _value) break else: raise KeyError(_name)
[ "def", "replace_header", "(", "self", ",", "_name", ",", "_value", ")", ":", "_name", "=", "_name", ".", "lower", "(", ")", "for", "i", ",", "(", "k", ",", "v", ")", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_headers", ")", ")",...
Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised.
[ "Replace", "a", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L500-L513
224,778
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_content_type
def get_content_type(self): """Return the message's content type. The returned string is coerced to lower case of the form `maintype/subtype'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. """ missing = object() value = self.get('content-type', missing) if value is missing: # This should have no parameters return self.get_default_type() ctype = _splitparam(value)[0].lower() # RFC 2045, section 5.2 says if its invalid, use text/plain if ctype.count('/') != 1: return 'text/plain' return ctype
python
def get_content_type(self): missing = object() value = self.get('content-type', missing) if value is missing: # This should have no parameters return self.get_default_type() ctype = _splitparam(value)[0].lower() # RFC 2045, section 5.2 says if its invalid, use text/plain if ctype.count('/') != 1: return 'text/plain' return ctype
[ "def", "get_content_type", "(", "self", ")", ":", "missing", "=", "object", "(", ")", "value", "=", "self", ".", "get", "(", "'content-type'", ",", "missing", ")", "if", "value", "is", "missing", ":", "# This should have no parameters", "return", "self", "."...
Return the message's content type. The returned string is coerced to lower case of the form `maintype/subtype'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822.
[ "Return", "the", "message", "s", "content", "type", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L519-L541
224,779
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_params
def get_params(self, failobj=None, header='content-type', unquote=True): """Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted. """ missing = object() params = self._get_params_preserve(missing, header) if params is missing: return failobj if unquote: return [(k, _unquotevalue(v)) for k, v in params] else: return params
python
def get_params(self, failobj=None, header='content-type', unquote=True): missing = object() params = self._get_params_preserve(missing, header) if params is missing: return failobj if unquote: return [(k, _unquotevalue(v)) for k, v in params] else: return params
[ "def", "get_params", "(", "self", ",", "failobj", "=", "None", ",", "header", "=", "'content-type'", ",", "unquote", "=", "True", ")", ":", "missing", "=", "object", "(", ")", "params", "=", "self", ".", "_get_params_preserve", "(", "missing", ",", "head...
Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted.
[ "Return", "the", "message", "s", "Content", "-", "Type", "parameters", "as", "a", "list", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L600-L620
224,780
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_param
def get_param(self, param, failobj=None, header='content-type', unquote=True): """Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. The parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. If your application doesn't care whether the parameter was RFC 2231 encoded, it can turn the return value into a string as follows: param = msg.get_param('foo') param = email.utils.collapse_rfc2231_value(rawparam) """ if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): if unquote: return _unquotevalue(v) else: return v return failobj
python
def get_param(self, param, failobj=None, header='content-type', unquote=True): if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): if unquote: return _unquotevalue(v) else: return v return failobj
[ "def", "get_param", "(", "self", ",", "param", ",", "failobj", "=", "None", ",", "header", "=", "'content-type'", ",", "unquote", "=", "True", ")", ":", "if", "header", "not", "in", "self", ":", "return", "failobj", "for", "k", ",", "v", "in", "self"...
Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. The parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. If your application doesn't care whether the parameter was RFC 2231 encoded, it can turn the return value into a string as follows: param = msg.get_param('foo') param = email.utils.collapse_rfc2231_value(rawparam)
[ "Return", "the", "parameter", "value", "if", "found", "in", "the", "Content", "-", "Type", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L622-L654
224,781
PythonCharmers/python-future
src/future/backports/email/message.py
Message.set_param
def set_param(self, param, value, header='Content-Type', requote=True, charset=None, language=''): """Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. """ if not isinstance(value, tuple) and charset: value = (charset, language, value) if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) if not self.get_param(param, header=header): if not ctype: ctype = _formatparam(param, value, requote) else: ctype = SEMISPACE.join( [ctype, _formatparam(param, value, requote)]) else: ctype = '' for old_param, old_value in self.get_params(header=header, unquote=requote): append_param = '' if old_param.lower() == param.lower(): append_param = _formatparam(param, value, requote) else: append_param = _formatparam(old_param, old_value, requote) if not ctype: ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) if ctype != self.get(header): del self[header] self[header] = ctype
python
def set_param(self, param, value, header='Content-Type', requote=True, charset=None, language=''): if not isinstance(value, tuple) and charset: value = (charset, language, value) if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) if not self.get_param(param, header=header): if not ctype: ctype = _formatparam(param, value, requote) else: ctype = SEMISPACE.join( [ctype, _formatparam(param, value, requote)]) else: ctype = '' for old_param, old_value in self.get_params(header=header, unquote=requote): append_param = '' if old_param.lower() == param.lower(): append_param = _formatparam(param, value, requote) else: append_param = _formatparam(old_param, old_value, requote) if not ctype: ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) if ctype != self.get(header): del self[header] self[header] = ctype
[ "def", "set_param", "(", "self", ",", "param", ",", "value", ",", "header", "=", "'Content-Type'", ",", "requote", "=", "True", ",", "charset", "=", "None", ",", "language", "=", "''", ")", ":", "if", "not", "isinstance", "(", "value", ",", "tuple", ...
Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings.
[ "Set", "a", "parameter", "in", "the", "Content", "-", "Type", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L656-L702
224,782
PythonCharmers/python-future
src/future/backports/email/message.py
Message.del_param
def del_param(self, param, header='content-type', requote=True): """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. """ if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if new_ctype != self.get(header): del self[header] self[header] = new_ctype
python
def del_param(self, param, header='content-type', requote=True): if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if new_ctype != self.get(header): del self[header] self[header] = new_ctype
[ "def", "del_param", "(", "self", ",", "param", ",", "header", "=", "'content-type'", ",", "requote", "=", "True", ")", ":", "if", "header", "not", "in", "self", ":", "return", "new_ctype", "=", "''", "for", "p", ",", "v", "in", "self", ".", "get_para...
Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header.
[ "Remove", "the", "given", "parameter", "completely", "from", "the", "Content", "-", "Type", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L704-L724
224,783
PythonCharmers/python-future
src/future/backports/email/message.py
Message.set_type
def set_type(self, type, header='Content-Type', requote=True): """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header. """ # BAW: should we be strict? if not type.count('/') == 1: raise ValueError # Set the Content-Type, you get a MIME-Version if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type # Skip the first param; it's the old type. for p, v in params[1:]: self.set_param(p, v, header, requote)
python
def set_type(self, type, header='Content-Type', requote=True): # BAW: should we be strict? if not type.count('/') == 1: raise ValueError # Set the Content-Type, you get a MIME-Version if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type # Skip the first param; it's the old type. for p, v in params[1:]: self.set_param(p, v, header, requote)
[ "def", "set_type", "(", "self", ",", "type", ",", "header", "=", "'Content-Type'", ",", "requote", "=", "True", ")", ":", "# BAW: should we be strict?", "if", "not", "type", ".", "count", "(", "'/'", ")", "==", "1", ":", "raise", "ValueError", "# Set the C...
Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header.
[ "Set", "the", "main", "type", "and", "subtype", "for", "the", "Content", "-", "Type", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L726-L756
224,784
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_filename
def get_filename(self, failobj=None): """Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. """ missing = object() filename = self.get_param('filename', missing, 'content-disposition') if filename is missing: filename = self.get_param('name', missing, 'content-type') if filename is missing: return failobj return utils.collapse_rfc2231_value(filename).strip()
python
def get_filename(self, failobj=None): missing = object() filename = self.get_param('filename', missing, 'content-disposition') if filename is missing: filename = self.get_param('name', missing, 'content-type') if filename is missing: return failobj return utils.collapse_rfc2231_value(filename).strip()
[ "def", "get_filename", "(", "self", ",", "failobj", "=", "None", ")", ":", "missing", "=", "object", "(", ")", "filename", "=", "self", ".", "get_param", "(", "'filename'", ",", "missing", ",", "'content-disposition'", ")", "if", "filename", "is", "missing...
Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter.
[ "Return", "the", "filename", "associated", "with", "the", "payload", "if", "present", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L758-L772
224,785
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_boundary
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. """ missing = object() boundary = self.get_param('boundary', missing) if boundary is missing: return failobj # RFC 2046 says that boundaries may begin but not end in w/s return utils.collapse_rfc2231_value(boundary).rstrip()
python
def get_boundary(self, failobj=None): missing = object() boundary = self.get_param('boundary', missing) if boundary is missing: return failobj # RFC 2046 says that boundaries may begin but not end in w/s return utils.collapse_rfc2231_value(boundary).rstrip()
[ "def", "get_boundary", "(", "self", ",", "failobj", "=", "None", ")", ":", "missing", "=", "object", "(", ")", "boundary", "=", "self", ".", "get_param", "(", "'boundary'", ",", "missing", ")", "if", "boundary", "is", "missing", ":", "return", "failobj",...
Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted.
[ "Return", "the", "boundary", "associated", "with", "the", "payload", "if", "present", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L774-L785
224,786
PythonCharmers/python-future
src/future/backports/email/message.py
Message.set_boundary
def set_boundary(self, boundary): """Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. """ missing = object() params = self._get_params_preserve(missing, 'content-type') if params is missing: # There was no Content-Type header, and we don't know what type # to set it to, so raise an exception. raise errors.HeaderParseError('No Content-Type header found') newparams = list() foundp = False for pk, pv in params: if pk.lower() == 'boundary': newparams.append(('boundary', '"%s"' % boundary)) foundp = True else: newparams.append((pk, pv)) if not foundp: # The original Content-Type header had no boundary attribute. # Tack one on the end. BAW: should we raise an exception # instead??? newparams.append(('boundary', '"%s"' % boundary)) # Replace the existing Content-Type header with the new value newheaders = list() for h, v in self._headers: if h.lower() == 'content-type': parts = list() for k, v in newparams: if v == '': parts.append(k) else: parts.append('%s=%s' % (k, v)) val = SEMISPACE.join(parts) newheaders.append(self.policy.header_store_parse(h, val)) else: newheaders.append((h, v)) self._headers = newheaders
python
def set_boundary(self, boundary): missing = object() params = self._get_params_preserve(missing, 'content-type') if params is missing: # There was no Content-Type header, and we don't know what type # to set it to, so raise an exception. raise errors.HeaderParseError('No Content-Type header found') newparams = list() foundp = False for pk, pv in params: if pk.lower() == 'boundary': newparams.append(('boundary', '"%s"' % boundary)) foundp = True else: newparams.append((pk, pv)) if not foundp: # The original Content-Type header had no boundary attribute. # Tack one on the end. BAW: should we raise an exception # instead??? newparams.append(('boundary', '"%s"' % boundary)) # Replace the existing Content-Type header with the new value newheaders = list() for h, v in self._headers: if h.lower() == 'content-type': parts = list() for k, v in newparams: if v == '': parts.append(k) else: parts.append('%s=%s' % (k, v)) val = SEMISPACE.join(parts) newheaders.append(self.policy.header_store_parse(h, val)) else: newheaders.append((h, v)) self._headers = newheaders
[ "def", "set_boundary", "(", "self", ",", "boundary", ")", ":", "missing", "=", "object", "(", ")", "params", "=", "self", ".", "_get_params_preserve", "(", "missing", ",", "'content-type'", ")", "if", "params", "is", "missing", ":", "# There was no Content-Typ...
Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header.
[ "Set", "the", "boundary", "parameter", "in", "Content", "-", "Type", "to", "boundary", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L787-L831
224,787
PythonCharmers/python-future
src/future/backports/email/message.py
Message.get_content_charset
def get_content_charset(self, failobj=None): """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. """ missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. as_bytes = charset[2].encode('raw-unicode-escape') charset = str(as_bytes, pcharset) except (LookupError, UnicodeError): charset = charset[2] # charset characters must be in us-ascii range try: charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower()
python
def get_content_charset(self, failobj=None): missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. as_bytes = charset[2].encode('raw-unicode-escape') charset = str(as_bytes, pcharset) except (LookupError, UnicodeError): charset = charset[2] # charset characters must be in us-ascii range try: charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower()
[ "def", "get_content_charset", "(", "self", ",", "failobj", "=", "None", ")", ":", "missing", "=", "object", "(", ")", "charset", "=", "self", ".", "get_param", "(", "'charset'", ",", "missing", ")", "if", "charset", "is", "missing", ":", "return", "failo...
Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.
[ "Return", "the", "charset", "parameter", "of", "the", "Content", "-", "Type", "header", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/message.py#L833-L861
224,788
PythonCharmers/python-future
src/future/backports/socket.py
getfqdn
def getfqdn(name=''): """Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. """ name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name
python
def getfqdn(name=''): name = name.strip() if not name or name == '0.0.0.0': name = gethostname() try: hostname, aliases, ipaddrs = gethostbyaddr(name) except error: pass else: aliases.insert(0, hostname) for name in aliases: if '.' in name: break else: name = hostname return name
[ "def", "getfqdn", "(", "name", "=", "''", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "if", "not", "name", "or", "name", "==", "'0.0.0.0'", ":", "name", "=", "gethostname", "(", ")", "try", ":", "hostname", ",", "aliases", ",", "ipaddrs"...
Get fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned.
[ "Get", "fully", "qualified", "domain", "name", "from", "name", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/socket.py#L387-L410
224,789
PythonCharmers/python-future
docs/other/auto2to3.py
maybe_2to3
def maybe_2to3(filename, modname=None): """Returns a python3 version of filename.""" need_2to3 = False filename = os.path.abspath(filename) if any(filename.startswith(d) for d in DIRS): need_2to3 = True elif modname is not None and any(modname.startswith(p) for p in PACKAGES): need_2to3 = True if not need_2to3: return filename outfilename = '/_auto2to3_'.join(os.path.split(filename)) if (not os.path.exists(outfilename) or os.stat(filename).st_mtime > os.stat(outfilename).st_mtime): try: with open(filename) as file: contents = file.read() contents = rt.refactor_docstring(contents, filename) tree = rt.refactor_string(contents, filename) except Exception as err: raise ImportError("2to3 couldn't convert %r" % filename) outfile = open(outfilename, 'wb') outfile.write(str(tree).encode('utf8')) outfile.close() return outfilename
python
def maybe_2to3(filename, modname=None): need_2to3 = False filename = os.path.abspath(filename) if any(filename.startswith(d) for d in DIRS): need_2to3 = True elif modname is not None and any(modname.startswith(p) for p in PACKAGES): need_2to3 = True if not need_2to3: return filename outfilename = '/_auto2to3_'.join(os.path.split(filename)) if (not os.path.exists(outfilename) or os.stat(filename).st_mtime > os.stat(outfilename).st_mtime): try: with open(filename) as file: contents = file.read() contents = rt.refactor_docstring(contents, filename) tree = rt.refactor_string(contents, filename) except Exception as err: raise ImportError("2to3 couldn't convert %r" % filename) outfile = open(outfilename, 'wb') outfile.write(str(tree).encode('utf8')) outfile.close() return outfilename
[ "def", "maybe_2to3", "(", "filename", ",", "modname", "=", "None", ")", ":", "need_2to3", "=", "False", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "any", "(", "filename", ".", "startswith", "(", "d", ")", "for", "...
Returns a python3 version of filename.
[ "Returns", "a", "python3", "version", "of", "filename", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/docs/other/auto2to3.py#L39-L62
224,790
PythonCharmers/python-future
src/future/backports/email/iterators.py
walk
def walk(self): """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield subsubpart
python
def walk(self): yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield subsubpart
[ "def", "walk", "(", "self", ")", ":", "yield", "self", "if", "self", ".", "is_multipart", "(", ")", ":", "for", "subpart", "in", "self", ".", "get_payload", "(", ")", ":", "for", "subsubpart", "in", "subpart", ".", "walk", "(", ")", ":", "yield", "...
Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator.
[ "Walk", "over", "the", "message", "tree", "yielding", "each", "subpart", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/iterators.py#L23-L33
224,791
PythonCharmers/python-future
src/future/backports/email/iterators.py
body_line_iterator
def body_line_iterator(msg, decode=False): """Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). """ for subpart in msg.walk(): payload = subpart.get_payload(decode=decode) if isinstance(payload, str): for line in StringIO(payload): yield line
python
def body_line_iterator(msg, decode=False): for subpart in msg.walk(): payload = subpart.get_payload(decode=decode) if isinstance(payload, str): for line in StringIO(payload): yield line
[ "def", "body_line_iterator", "(", "msg", ",", "decode", "=", "False", ")", ":", "for", "subpart", "in", "msg", ".", "walk", "(", ")", ":", "payload", "=", "subpart", ".", "get_payload", "(", "decode", "=", "decode", ")", "if", "isinstance", "(", "paylo...
Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload().
[ "Iterate", "over", "the", "parts", "returning", "string", "payloads", "line", "-", "by", "-", "line", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/iterators.py#L37-L46
224,792
PythonCharmers/python-future
src/future/backports/email/iterators.py
typed_subpart_iterator
def typed_subpart_iterator(msg, maintype='text', subtype=None): """Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched. """ for subpart in msg.walk(): if subpart.get_content_maintype() == maintype: if subtype is None or subpart.get_content_subtype() == subtype: yield subpart
python
def typed_subpart_iterator(msg, maintype='text', subtype=None): for subpart in msg.walk(): if subpart.get_content_maintype() == maintype: if subtype is None or subpart.get_content_subtype() == subtype: yield subpart
[ "def", "typed_subpart_iterator", "(", "msg", ",", "maintype", "=", "'text'", ",", "subtype", "=", "None", ")", ":", "for", "subpart", "in", "msg", ".", "walk", "(", ")", ":", "if", "subpart", ".", "get_content_maintype", "(", ")", "==", "maintype", ":", ...
Iterate over the subparts with a given MIME type. Use `maintype' as the main MIME type to match against; this defaults to "text". Optional `subtype' is the MIME subtype to match against; if omitted, only the main type is matched.
[ "Iterate", "over", "the", "subparts", "with", "a", "given", "MIME", "type", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/iterators.py#L49-L59
224,793
PythonCharmers/python-future
src/future/backports/email/iterators.py
_structure
def _structure(msg, fp=None, level=0, include_default=False): """A handy debugging aid""" if fp is None: fp = sys.stdout tab = ' ' * (level * 4) print(tab + msg.get_content_type(), end='', file=fp) if include_default: print(' [%s]' % msg.get_default_type(), file=fp) else: print(file=fp) if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default)
python
def _structure(msg, fp=None, level=0, include_default=False): if fp is None: fp = sys.stdout tab = ' ' * (level * 4) print(tab + msg.get_content_type(), end='', file=fp) if include_default: print(' [%s]' % msg.get_default_type(), file=fp) else: print(file=fp) if msg.is_multipart(): for subpart in msg.get_payload(): _structure(subpart, fp, level+1, include_default)
[ "def", "_structure", "(", "msg", ",", "fp", "=", "None", ",", "level", "=", "0", ",", "include_default", "=", "False", ")", ":", "if", "fp", "is", "None", ":", "fp", "=", "sys", ".", "stdout", "tab", "=", "' '", "*", "(", "level", "*", "4", ")"...
A handy debugging aid
[ "A", "handy", "debugging", "aid" ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/iterators.py#L62-L74
224,794
PythonCharmers/python-future
src/future/backports/email/charset.py
add_charset
def add_charset(charset, header_enc=None, body_enc=None, output_charset=None): """Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. """ if body_enc == SHORTEST: raise ValueError('SHORTEST not allowed for body_enc') CHARSETS[charset] = (header_enc, body_enc, output_charset)
python
def add_charset(charset, header_enc=None, body_enc=None, output_charset=None): if body_enc == SHORTEST: raise ValueError('SHORTEST not allowed for body_enc') CHARSETS[charset] = (header_enc, body_enc, output_charset)
[ "def", "add_charset", "(", "charset", ",", "header_enc", "=", "None", ",", "body_enc", "=", "None", ",", "output_charset", "=", "None", ")", ":", "if", "body_enc", "==", "SHORTEST", ":", "raise", "ValueError", "(", "'SHORTEST not allowed for body_enc'", ")", "...
Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information.
[ "Add", "character", "set", "properties", "to", "the", "global", "registry", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L110-L135
224,795
PythonCharmers/python-future
src/future/backports/email/charset.py
Charset.get_body_encoding
def get_body_encoding(self): """Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns conversion function otherwise. """ assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: return 'base64' else: return encode_7or8bit
python
def get_body_encoding(self): assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: return 'base64' else: return encode_7or8bit
[ "def", "get_body_encoding", "(", "self", ")", ":", "assert", "self", ".", "body_encoding", "!=", "SHORTEST", "if", "self", ".", "body_encoding", "==", "QP", ":", "return", "'quoted-printable'", "elif", "self", ".", "body_encoding", "==", "BASE64", ":", "return...
Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns conversion function otherwise.
[ "Return", "the", "content", "-", "transfer", "-", "encoding", "used", "for", "body", "encoding", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L255-L274
224,796
PythonCharmers/python-future
src/future/backports/email/charset.py
Charset.body_encode
def body_encode(self, string): """Body-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the ascii codec produces the correct string version of the content. """ if not string: return string if self.body_encoding is BASE64: if isinstance(string, str): string = string.encode(self.output_charset) return email.base64mime.body_encode(string) elif self.body_encoding is QP: # quopromime.body_encode takes a string, but operates on it as if # it were a list of byte codes. For a (minimal) history on why # this is so, see changeset 0cf700464177. To correctly encode a # character set, then, we must turn it into pseudo bytes via the # latin1 charset, which will encode any byte as a single code point # between 0 and 255, which is what body_encode is expecting. if isinstance(string, str): string = string.encode(self.output_charset) string = string.decode('latin1') return email.quoprimime.body_encode(string) else: if isinstance(string, str): string = string.encode(self.output_charset).decode('ascii') return string
python
def body_encode(self, string): if not string: return string if self.body_encoding is BASE64: if isinstance(string, str): string = string.encode(self.output_charset) return email.base64mime.body_encode(string) elif self.body_encoding is QP: # quopromime.body_encode takes a string, but operates on it as if # it were a list of byte codes. For a (minimal) history on why # this is so, see changeset 0cf700464177. To correctly encode a # character set, then, we must turn it into pseudo bytes via the # latin1 charset, which will encode any byte as a single code point # between 0 and 255, which is what body_encode is expecting. if isinstance(string, str): string = string.encode(self.output_charset) string = string.decode('latin1') return email.quoprimime.body_encode(string) else: if isinstance(string, str): string = string.encode(self.output_charset).decode('ascii') return string
[ "def", "body_encode", "(", "self", ",", "string", ")", ":", "if", "not", "string", ":", "return", "string", "if", "self", ".", "body_encoding", "is", "BASE64", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "string", "=", "string", ".", ...
Body-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the ascii codec produces the correct string version of the content.
[ "Body", "-", "encode", "a", "string", "by", "converting", "it", "first", "to", "bytes", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L380-L409
224,797
PythonCharmers/python-future
src/future/backports/xmlrpc/server.py
SimpleXMLRPCDispatcher.register_instance
def register_instance(self, instance, allow_dotted_names=False): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. """ self.instance = instance self.allow_dotted_names = allow_dotted_names
python
def register_instance(self, instance, allow_dotted_names=False): self.instance = instance self.allow_dotted_names = allow_dotted_names
[ "def", "register_instance", "(", "self", ",", "instance", ",", "allow_dotted_names", "=", "False", ")", ":", "self", ".", "instance", "=", "instance", "self", ".", "allow_dotted_names", "=", "allow_dotted_names" ]
Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches a XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.
[ "Registers", "an", "instance", "to", "respond", "to", "XML", "-", "RPC", "requests", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L177-L211
224,798
PythonCharmers/python-future
src/future/backports/xmlrpc/server.py
SimpleXMLRPCDispatcher.register_introspection_functions
def register_introspection_functions(self): """Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html """ self.funcs.update({'system.listMethods' : self.system_listMethods, 'system.methodSignature' : self.system_methodSignature, 'system.methodHelp' : self.system_methodHelp})
python
def register_introspection_functions(self): self.funcs.update({'system.listMethods' : self.system_listMethods, 'system.methodSignature' : self.system_methodSignature, 'system.methodHelp' : self.system_methodHelp})
[ "def", "register_introspection_functions", "(", "self", ")", ":", "self", ".", "funcs", ".", "update", "(", "{", "'system.listMethods'", ":", "self", ".", "system_listMethods", ",", "'system.methodSignature'", ":", "self", ".", "system_methodSignature", ",", "'syste...
Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html
[ "Registers", "the", "XML", "-", "RPC", "introspection", "methods", "in", "the", "system", "namespace", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L224-L233
224,799
PythonCharmers/python-future
src/future/backports/xmlrpc/server.py
SimpleXMLRPCDispatcher._dispatch
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ func = None try: # check to see if a matching function has been registered func = self.funcs[method] except KeyError: if self.instance is not None: # check for a _dispatch method if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: # call instance method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass if func is not None: return func(*params) else: raise Exception('method "%s" is not supported' % method)
python
def _dispatch(self, method, params): func = None try: # check to see if a matching function has been registered func = self.funcs[method] except KeyError: if self.instance is not None: # check for a _dispatch method if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: # call instance method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass if func is not None: return func(*params) else: raise Exception('method "%s" is not supported' % method)
[ "def", "_dispatch", "(", "self", ",", "method", ",", "params", ")", ":", "func", "=", "None", "try", ":", "# check to see if a matching function has been registered", "func", "=", "self", ".", "funcs", "[", "method", "]", "except", "KeyError", ":", "if", "self...
Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called.
[ "Dispatches", "the", "XML", "-", "RPC", "method", "." ]
c423752879acc05eebc29b0bb9909327bd5c7308
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L374-L418