code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def b32encode(s): """Encode a string using Base32. s is the string to encode. The encoded string is returned. """ parts = [] quanta, leftover = divmod(len(s), 5) # Pad the last quantum with zero bits if necessary if leftover: s += ('\0' * (5 - leftover)) quanta += 1 for i in range(quanta): # c1 and c2 are 16 bits wide, c3 is 8 bits wide. The intent of this # code is to process the 40 bits in units of 5 bits. So we take the 1 # leftover bit of c1 and tack it onto c2. Then we take the 2 leftover # bits of c2 and tack them onto c3. The shifts and masks are intended # to give us values of exactly 5 bits in width. c1, c2, c3 = struct.unpack('!HHB', s[i*5:(i+1)*5]) c2 += (c1 & 1) << 16 # 17 bits wide c3 += (c2 & 3) << 8 # 10 bits wide parts.extend([_b32tab[c1 >> 11], # bits 1 - 5 _b32tab[(c1 >> 6) & 0x1f], # bits 6 - 10 _b32tab[(c1 >> 1) & 0x1f], # bits 11 - 15 _b32tab[c2 >> 12], # bits 16 - 20 (1 - 5) _b32tab[(c2 >> 7) & 0x1f], # bits 21 - 25 (6 - 10) _b32tab[(c2 >> 2) & 0x1f], # bits 26 - 30 (11 - 15) _b32tab[c3 >> 5], # bits 31 - 35 (1 - 5) _b32tab[c3 & 0x1f], # bits 36 - 40 (1 - 5) ]) encoded = EMPTYSTRING.join(parts) # Adjust for any leftover partial quanta if leftover == 1: return encoded[:-6] + '======' elif leftover == 2: return encoded[:-4] + '====' elif leftover == 3: return encoded[:-3] + '===' elif leftover == 4: return encoded[:-1] + '=' return encoded
Encode a string using Base32. s is the string to encode. The encoded string is returned.
b32encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT
def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The decoded string is returned. A TypeError is raised if s were incorrectly padded or if there are non-alphabet characters present in the string. """ quanta, leftover = divmod(len(s), 8) if leftover: raise TypeError('Incorrect padding') # Handle section 2.4 zero and one mapping. The flag map01 will be either # False, or the character to map the digit 1 (one) to. It should be # either L (el) or I (eye). if map01: s = s.translate(string.maketrans(b'01', b'O' + map01)) if casefold: s = s.upper() # Strip off pad characters from the right. We need to count the pad # characters because this will tell us how many null bytes to remove from # the end of the decoded string. padchars = 0 mo = re.search('(?P<pad>[=]*)$', s) if mo: padchars = len(mo.group('pad')) if padchars > 0: s = s[:-padchars] # Now decode the full quanta parts = [] acc = 0 shift = 35 for c in s: val = _b32rev.get(c) if val is None: raise TypeError('Non-base32 digit found') acc += _b32rev[c] << shift shift -= 5 if shift < 0: parts.append(binascii.unhexlify('%010x' % acc)) acc = 0 shift = 35 # Process the last, partial quanta last = binascii.unhexlify('%010x' % acc) if padchars == 0: last = '' # No characters elif padchars == 1: last = last[:-1] elif padchars == 3: last = last[:-2] elif padchars == 4: last = last[:-3] elif padchars == 6: last = last[:-4] else: raise TypeError('Incorrect padding') parts.append(last) return EMPTYSTRING.join(parts)
Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye) or letter L (el). The optional argument map01 when not None, specifies which letter the digit 1 should be mapped to (when map01 is not None, the digit 0 is always mapped to the letter O). For security purposes the default is None, so that 0 and 1 are not allowed in the input. The decoded string is returned. A TypeError is raised if s were incorrectly padded or if there are non-alphabet characters present in the string.
b32decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT
def b16decode(s, casefold=False): """Decode a Base16 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded string is returned. A TypeError is raised if s is incorrectly padded or if there are non-alphabet characters present in the string. """ if casefold: s = s.upper() if re.search('[^0-9A-F]', s): raise TypeError('Non-base16 digit found') return binascii.unhexlify(s)
Decode a Base16 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. The decoded string is returned. A TypeError is raised if s is incorrectly padded or if there are non-alphabet characters present in the string.
b16decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT
def encodestring(s): """Encode a string into multiple lines of base-64 data.""" pieces = [] for i in range(0, len(s), MAXBINSIZE): chunk = s[i : i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return "".join(pieces)
Encode a string into multiple lines of base-64 data.
encodestring
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/base64.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/base64.py
MIT
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
Override server_bind to store the server name.
server_bind
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def parse_request(self): """Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back. """ self.command = None # set in case of error on the first line self.request_version = version = self.default_request_version self.close_connection = 1 requestline = self.raw_requestline requestline = requestline.rstrip('\r\n') self.requestline = requestline words = requestline.split() if len(words) == 3: command, path, version = words if version[:5] != 'HTTP/': self.send_error(400, "Bad request version (%r)" % version) return False try: base_version_number = version.split('/', 1)[1] version_number = base_version_number.split(".") # RFC 2145 section 3.1 says there can be only one "." and # - major and minor numbers MUST be treated as # separate integers; # - HTTP/2.4 is a lower version than HTTP/2.13, which in # turn is lower than HTTP/12.3; # - Leading zeros MUST be ignored by recipients. if len(version_number) != 2: raise ValueError version_number = int(version_number[0]), int(version_number[1]) except (ValueError, IndexError): self.send_error(400, "Bad request version (%r)" % version) return False if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1": self.close_connection = 0 if version_number >= (2, 0): self.send_error(505, "Invalid HTTP Version (%s)" % base_version_number) return False elif len(words) == 2: command, path = words self.close_connection = 1 if command != 'GET': self.send_error(400, "Bad HTTP/0.9 request type (%r)" % command) return False elif not words: return False else: self.send_error(400, "Bad request syntax (%r)" % requestline) return False self.command, self.path, self.request_version = command, path, version # Examine the headers and look for a Connection directive self.headers = self.MessageClass(self.rfile, 0) conntype = self.headers.get('Connection', "") if conntype.lower() == 'close': self.close_connection = 1 elif (conntype.lower() == 'keep-alive' and self.protocol_version >= "HTTP/1.1"): self.close_connection = 0 return True
Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.
parse_request
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def handle_one_request(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ try: self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) return if not self.raw_requestline: self.close_connection = 1 return if not self.parse_request(): # An error code has been sent, just exit return mname = 'do_' + self.command if not hasattr(self, mname): self.send_error(501, "Unsupported method (%r)" % self.command) return method = getattr(self, mname) method() self.wfile.flush() #actually send the response if not already done. except socket.timeout, e: #a read or a write timed out. Discard this connection self.log_error("Request timed out: %r", e) self.close_connection = 1 return
Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.
handle_one_request
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def send_error(self, code, message=None): """Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. """ try: short, long = self.responses[code] except KeyError: short, long = '???', '???' if message is None: message = short explain = long self.log_error("code %d, message %s", code, message) self.send_response(code, message) self.send_header('Connection', 'close') # Message body is omitted for cases described in: # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified) # - RFC7231: 6.3.6. 205(Reset Content) content = None if code >= 200 and code not in (204, 205, 304): # HTML encode to prevent Cross Site Scripting attacks # (see bug #1100201) content = (self.error_message_format % { 'code': code, 'message': _quote_html(message), 'explain': explain }) self.send_header("Content-Type", self.error_content_type) self.end_headers() if self.command != 'HEAD' and content: self.wfile.write(content)
Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.
send_error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def send_response(self, code, message=None): """Send the response header and log the response code. Also send two standard headers with the server software version and the current date. """ self.log_request(code) if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code, message)) # print (self.protocol_version, code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
Send the response header and log the response code. Also send two standard headers with the server software version and the current date.
send_response
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def log_request(self, code='-', size='-'): """Log an accepted request. This is called by send_response(). """ self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
Log an accepted request. This is called by send_response().
log_request
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
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 address and current date/time are prefixed to every message. """ sys.stderr.write("%s - - [%s] %s\n" % (self.client_address[0], self.log_date_time_string(), 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 address and current date/time are prefixed to every message.
log_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def date_time_string(self, timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss) return s
Return the current date and time formatted for a message header.
date_time_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
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
Return the current time formatted for logging.
log_date_time_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def test(HandlerClass = BaseHTTPRequestHandler, ServerClass = HTTPServer, protocol="HTTP/1.0"): """Test the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument). """ if sys.argv[1:]: port = int(sys.argv[1]) else: port = 8000 server_address = ('', port) HandlerClass.protocol_version = protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
Test the HTTP request handler class. This runs an HTTP server on port 8000 (or the first command line argument).
test
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/BaseHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/BaseHTTPServer.py
MIT
def __init__(self, get, name): """Constructor. Arguments: get - a function that gets the attribute value (by name) name - a human-readable name for the original object (suggestion: use repr(object)) """ self._get_ = get self._name_ = name
Constructor. Arguments: get - a function that gets the attribute value (by name) name - a human-readable name for the original object (suggestion: use repr(object))
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/Bastion.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/Bastion.py
MIT
def __getattr__(self, name): """Get an as-yet undefined attribute value. This calls the get() function that was passed to the constructor. The result is stored as an instance variable so that the next time the same attribute is requested, __getattr__() won't be invoked. If the get() function raises an exception, this is simply passed on -- exceptions are not cached. """ attribute = self._get_(name) self.__dict__[name] = attribute return attribute
Get an as-yet undefined attribute value. This calls the get() function that was passed to the constructor. The result is stored as an instance variable so that the next time the same attribute is requested, __getattr__() won't be invoked. If the get() function raises an exception, this is simply passed on -- exceptions are not cached.
__getattr__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/Bastion.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/Bastion.py
MIT
def Bastion(object, filter = lambda name: name[:1] != '_', name=None, bastionclass=BastionClass): """Create a bastion for an object, using an optional filter. See the Bastion module's documentation for background. Arguments: object - the original object filter - a predicate that decides whether a function name is OK; by default all names are OK that don't start with '_' name - the name of the object; default repr(object) bastionclass - class used to create the bastion; default BastionClass """ raise RuntimeError, "This code is not secure in Python 2.2 and later" # Note: we define *two* ad-hoc functions here, get1 and get2. # Both are intended to be called in the same way: get(name). # It is clear that the real work (getting the attribute # from the object and calling the filter) is done in get1. # Why can't we pass get1 to the bastion? Because the user # would be able to override the filter argument! With get2, # overriding the default argument is no security loophole: # all it does is call it. # Also notice that we can't place the object and filter as # instance variables on the bastion object itself, since # the user has full access to all instance variables! def get1(name, object=object, filter=filter): """Internal function for Bastion(). See source comments.""" if filter(name): attribute = getattr(object, name) if type(attribute) == MethodType: return attribute raise AttributeError, name def get2(name, get1=get1): """Internal function for Bastion(). See source comments.""" return get1(name) if name is None: name = repr(object) return bastionclass(get2, name)
Create a bastion for an object, using an optional filter. See the Bastion module's documentation for background. Arguments: object - the original object filter - a predicate that decides whether a function name is OK; by default all names are OK that don't start with '_' name - the name of the object; default repr(object) bastionclass - class used to create the bastion; default BastionClass
Bastion
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/Bastion.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/Bastion.py
MIT
def get1(name, object=object, filter=filter): """Internal function for Bastion(). See source comments.""" if filter(name): attribute = getattr(object, name) if type(attribute) == MethodType: return attribute raise AttributeError, name
Internal function for Bastion(). See source comments.
get1
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/Bastion.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/Bastion.py
MIT
def set_step(self): """Stop after one line of code.""" # Issue #13183: pdb skips frames after hitting a breakpoint and running # step commands. # Restore the trace function in the caller (that may not have been set # for performance reasons) when returning from the current frame. if self.frame_returning: caller_frame = self.frame_returning.f_back if caller_frame and not caller_frame.f_trace: caller_frame.f_trace = self.trace_dispatch self._set_stopinfo(None, None)
Stop after one line of code.
set_step
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bdb.py
MIT
def set_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ if frame is None: frame = sys._getframe().f_back self.reset() while frame: frame.f_trace = self.trace_dispatch self.botframe = frame frame = frame.f_back self.set_step() sys.settrace(self.trace_dispatch)
Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame.
set_trace
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bdb.py
MIT
def checkfuncname(b, frame): """Check whether we should break here because of `b.funcname`.""" if not b.funcname: # Breakpoint was set via line number. if b.line != frame.f_lineno: # Breakpoint was set at a line with a def statement and the function # defined is called: don't break. return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False # We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True
Check whether we should break here because of `b.funcname`.
checkfuncname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bdb.py
MIT
def effective(file, line, frame): """Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a bpt at this location. Returns breakpoint that was triggered and a flag that indicates if it is ok to delete a temporary bp. """ possibles = Breakpoint.bplist[file,line] for i in range(0, len(possibles)): b = possibles[i] if b.enabled == 0: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits = b.hits + 1 if not b.cond: # If unconditional, and ignoring, # go on to next, else break if b.ignore > 0: b.ignore = b.ignore -1 continue else: # breakpoint and marker that's ok # to delete if temporary return (b,1) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.cond, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore = b.ignore -1 # continue else: return (b,1) # else: # continue except: # if eval fails, most conservative # thing is to stop on breakpoint # regardless of ignore count. # Don't delete temporary, # as another hint to user. return (b,0) return (None, None)
Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a bpt at this location. Returns breakpoint that was triggered and a flag that indicates if it is ok to delete a temporary bp.
effective
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bdb.py
MIT
def binhex(inp, out): """(infilename, outfilename) - Create binhex-encoded copy of a file""" finfo = getfileinfo(inp) ofp = BinHex(finfo, out) ifp = open(inp, 'rb') # XXXX Do textfile translation on non-mac systems while 1: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close_data() ifp.close() ifp = openrsrc(inp, 'rb') while 1: d = ifp.read(128000) if not d: break ofp.write_rsrc(d) ofp.close() ifp.close()
(infilename, outfilename) - Create binhex-encoded copy of a file
binhex
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/binhex.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/binhex.py
MIT
def read(self, totalwtd): """Read at least wtd bytes (or until EOF)""" decdata = '' wtd = totalwtd # # The loop here is convoluted, since we don't really now how # much to decode: there may be newlines in the incoming data. while wtd > 0: if self.eof: return decdata wtd = ((wtd+2)//3)*4 data = self.ifp.read(wtd) # # Next problem: there may not be a complete number of # bytes in what we pass to a2b. Solve by yet another # loop. # while 1: try: decdatacur, self.eof = \ binascii.a2b_hqx(data) break except binascii.Incomplete: pass newdata = self.ifp.read(1) if not newdata: raise Error, \ 'Premature EOF on binhex file' data = data + newdata decdata = decdata + decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error, 'Premature EOF on binhex file' return decdata
Read at least wtd bytes (or until EOF)
read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/binhex.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/binhex.py
MIT
def insort_right(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 a.insert(lo, x)
Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
insort_right
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bisect.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bisect.py
MIT
def bisect_right(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid]: hi = mid else: lo = mid+1 return lo
Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(x) will insert just after the rightmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
bisect_right
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bisect.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bisect.py
MIT
def insort_left(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid a.insert(lo, x)
Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the left of the leftmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
insort_left
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bisect.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bisect.py
MIT
def bisect_left(a, x, lo=0, hi=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo
Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e < x, and all e in a[i:] have e >= x. So if x already appears in the list, a.insert(x) will insert just before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
bisect_left
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/bisect.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/bisect.py
MIT
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
Return number of leap years in range [y1, y2). Assume y1 <= y2.
leapdays
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def monthrange(year, month): """Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.""" if not 1 <= month <= 12: raise IllegalMonthError(month) day1 = weekday(year, month, 1) ndays = mdays[month] + (month == February and isleap(year)) return day1, ndays
Return weekday (0-6 ~ Mon-Sun) and number of days (28-31) for year, month.
monthrange
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def itermonthdates(self, year, month): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ date = datetime.date(year, month, 1) # Go back to the beginning of the week days = (date.weekday() - self.firstweekday) % 7 date -= datetime.timedelta(days=days) oneday = datetime.timedelta(days=1) while True: yield date try: date += oneday except OverflowError: # Adding one day could fail after datetime.MAXYEAR break if date.month != month and date.weekday() == self.firstweekday: break
Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month.
itermonthdates
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def itermonthdays2(self, year, month): """ Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0. """ for date in self.itermonthdates(year, month): if date.month != month: yield (0, date.weekday()) else: yield (date.day, date.weekday())
Like itermonthdates(), but will yield (day number, weekday number) tuples. For days outside the specified month the day number is 0.
itermonthdays2
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def itermonthdays(self, year, month): """ Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0. """ for date in self.itermonthdates(year, month): if date.month != month: yield 0 else: yield date.day
Like itermonthdates(), but will yield day numbers. For days outside the specified month the day number is 0.
itermonthdays
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
monthdatescalendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def monthdays2calendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero. """ days = list(self.itermonthdays2(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ]
Return a matrix representing a month's calendar. Each row represents a week; week entries are (day number, weekday number) tuples. Day numbers outside this month are zero.
monthdays2calendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def monthdayscalendar(self, year, month): """ Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero. """ days = list(self.itermonthdays(year, month)) return [ days[i:i+7] for i in range(0, len(days), 7) ]
Return a matrix representing a month's calendar. Each row represents a week; days outside this month are zero.
monthdayscalendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def yeardatescalendar(self, year, width=3): """ Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ months = [ self.monthdatescalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects.
yeardatescalendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def yeardays2calendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero. """ months = [ self.monthdays2calendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are (day number, weekday number) tuples. Day numbers outside this month are zero.
yeardays2calendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def yeardayscalendar(self, year, width=3): """ Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero. """ months = [ self.monthdayscalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.
yeardayscalendar
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatmonth(self, theyear, themonth, w=0, l=0): """ Return a month's calendar string (multi-line). """ w = max(2, w) l = max(1, l) s = self.formatmonthname(theyear, themonth, 7 * (w + 1) - 1) s = s.rstrip() s += '\n' * l s += self.formatweekheader(w).rstrip() s += '\n' * l for week in self.monthdays2calendar(theyear, themonth): s += self.formatweek(week, w).rstrip() s += '\n' * l return s
Return a month's calendar string (multi-line).
formatmonth
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = range(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a('\n'*l) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in range(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
Returns a year's calendar as a multi-line string.
formatyear
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatweek(self, theweek): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd) for (d, wd) in theweek) return '<tr>%s</tr>' % s
Return a complete week as a table row.
formatweek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatweekheader(self): """ Return a header for a week as a table row. """ s = ''.join(self.formatweekday(i) for i in self.iterweekdays()) return '<tr>%s</tr>' % s
Return a header for a week as a table row.
formatweekheader
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="month">%s</th></tr>' % s
Return a month name as a table row.
formatmonthname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatyear(self, theyear, width=3): """ Return a formatted year as a table of tables. """ v = [] a = v.append width = max(width, 1) a('<table border="0" cellpadding="0" cellspacing="0" class="year">') a('\n') a('<tr><th colspan="%d" class="year">%s</th></tr>' % (width, theyear)) for i in range(January, January+12, width): # months in this row months = range(i, min(i+width, 13)) a('<tr>') for m in months: a('<td>') a(self.formatmonth(theyear, m, withyear=False)) a('</td>') a('</tr>') a('</table>') return ''.join(v)
Return a formatted year as a table of tables.
formatyear
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title>\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding, "xmlcharrefreplace")
Return a formatted year as a complete HTML page.
formatyearpage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def formatstring(cols, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from n strings, centered within n columns.""" spacing *= ' ' return spacing.join(c.center(colwidth) for c in cols)
Returns a string formatted from n strings, centered within n columns.
formatstring
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def timegm(tuple): """Unrelated but handy function to calculate Unix timestamp from GMT.""" year, month, day, hour, minute, second = tuple[:6] days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
Unrelated but handy function to calculate Unix timestamp from GMT.
timegm
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/calendar.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/calendar.py
MIT
def initlog(*allargs): """Write a log message, if there is a log file. Even though this function is called initlog(), you should always use log(); log is a variable that is set either to initlog (initially), to dolog (once the log file has been opened), or to nolog (when logging is disabled). The first argument is a format string; the remaining arguments (if any) are arguments to the % operator, so e.g. log("%s: %s", "a", "b") will write "a: b" to the log file, followed by a newline. If the global logfp is not None, it should be a file object to which log data is written. If the global logfp is None, the global logfile may be a string giving a filename to open, in append mode. This file should be world writable!!! If the file can't be opened, logging is silently disabled (since there is no safe place where we could send an error message). """ global logfp, log if logfile and not logfp: try: logfp = open(logfile, "a") except IOError: pass if not logfp: log = nolog else: log = dolog log(*allargs)
Write a log message, if there is a log file. Even though this function is called initlog(), you should always use log(); log is a variable that is set either to initlog (initially), to dolog (once the log file has been opened), or to nolog (when logging is disabled). The first argument is a format string; the remaining arguments (if any) are arguments to the % operator, so e.g. log("%s: %s", "a", "b") will write "a: b" to the log file, followed by a newline. If the global logfp is not None, it should be a file object to which log data is written. If the global logfp is None, the global logfile may be a string giving a filename to open, in append mode. This file should be world writable!!! If the file can't be opened, logging is silently disabled (since there is no safe place where we could send an error message).
initlog
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0): """Parse a query in the environment or from a file (default stdin) Arguments, all optional: fp : file pointer; default: sys.stdin environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ if fp is None: fp = sys.stdin if not 'REQUEST_METHOD' in environ: environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone if environ['REQUEST_METHOD'] == 'POST': ctype, pdict = parse_header(environ['CONTENT_TYPE']) if ctype == 'multipart/form-data': return parse_multipart(fp, pdict) elif ctype == 'application/x-www-form-urlencoded': clength = int(environ['CONTENT_LENGTH']) if maxlen and clength > maxlen: raise ValueError, 'Maximum content length exceeded' qs = fp.read(clength) else: qs = '' # Unknown content-type if 'QUERY_STRING' in environ: if qs: qs = qs + '&' qs = qs + environ['QUERY_STRING'] elif sys.argv[1:]: if qs: qs = qs + '&' qs = qs + sys.argv[1] environ['QUERY_STRING'] = qs # XXX Shouldn't, really elif 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] else: if sys.argv[1:]: qs = sys.argv[1] else: qs = "" environ['QUERY_STRING'] = qs # XXX Shouldn't, really return urlparse.parse_qs(qs, keep_blank_values, strict_parsing)
Parse a query in the environment or from a file (default stdin) Arguments, all optional: fp : file pointer; default: sys.stdin environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument.""" warn("cgi.parse_qs is deprecated, use urlparse.parse_qs instead", PendingDeprecationWarning, 2) return urlparse.parse_qs(qs, keep_blank_values, strict_parsing)
Parse a query given as a string argument.
parse_qs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument.""" warn("cgi.parse_qsl is deprecated, use urlparse.parse_qsl instead", PendingDeprecationWarning, 2) return urlparse.parse_qsl(qs, keep_blank_values, strict_parsing)
Parse a query given as a string argument.
parse_qsl
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = parts.next() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict
Parse a Content-type like header. Return the main content-type and a dictionary of options.
parse_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def __init__(self, name, value): """Constructor from field name and value.""" self.name = name self.value = value # self.file = StringIO(value)
Constructor from field name and value.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """ method = 'GET' self.keep_blank_values = keep_blank_values self.strict_parsing = strict_parsing if 'REQUEST_METHOD' in environ: method = environ['REQUEST_METHOD'].upper() self.qs_on_post = None if method == 'GET' or method == 'HEAD': if 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] elif sys.argv[1:]: qs = sys.argv[1] else: qs = "" fp = StringIO(qs) if headers is None: headers = {'content-type': "application/x-www-form-urlencoded"} if headers is None: headers = {} if method == 'POST': # Set default content-type for POST to what's traditional headers['content-type'] = "application/x-www-form-urlencoded" if 'CONTENT_TYPE' in environ: headers['content-type'] = environ['CONTENT_TYPE'] if 'QUERY_STRING' in environ: self.qs_on_post = environ['QUERY_STRING'] if 'CONTENT_LENGTH' in environ: headers['content-length'] = environ['CONTENT_LENGTH'] self.fp = fp or sys.stdin self.headers = headers self.outerboundary = outerboundary # Process content-disposition header cdisp, pdict = "", {} if 'content-disposition' in self.headers: cdisp, pdict = parse_header(self.headers['content-disposition']) self.disposition = cdisp self.disposition_options = pdict self.name = None if 'name' in pdict: self.name = pdict['name'] self.filename = None if 'filename' in pdict: self.filename = pdict['filename'] # Process content-type header # # Honor any existing content-type header. But if there is no # content-type header, use some sensible defaults. Assume # outerboundary is "" at the outer level, but something non-false # inside a multi-part. The default for an inner part is text/plain, # but for an outer part it should be urlencoded. This should catch # bogus clients which erroneously forget to include a content-type # header. # # See below for what we do if there does exist a content-type header, # but it happens to be something we don't understand. if 'content-type' in self.headers: ctype, pdict = parse_header(self.headers['content-type']) elif self.outerboundary or method != 'POST': ctype, pdict = "text/plain", {} else: ctype, pdict = 'application/x-www-form-urlencoded', {} self.type = ctype self.type_options = pdict self.innerboundary = "" if 'boundary' in pdict: self.innerboundary = pdict['boundary'] clen = -1 if 'content-length' in self.headers: try: clen = int(self.headers['content-length']) except ValueError: pass if maxlen and clen > maxlen: raise ValueError, 'Maximum content length exceeded' self.length = clen self.list = self.file = None self.done = 0 if ctype == 'application/x-www-form-urlencoded': self.read_urlencoded() elif ctype[:10] == 'multipart/': self.read_multi(environ, keep_blank_values, strict_parsing) else: self.read_single()
Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def getvalue(self, key, default=None): """Dictionary style get() method, including 'value' lookup.""" if key in self: value = self[key] if type(value) is type([]): return map(attrgetter('value'), value) else: return value.value else: return default
Dictionary style get() method, including 'value' lookup.
getvalue
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) if self.qs_on_post: qs += '&' + self.qs_on_post self.list = list = [] for key, value in urlparse.parse_qsl(qs, self.keep_blank_values, self.strict_parsing): list.append(MiniFieldStorage(key, value)) self.skip_lines()
Internal: read data in query string format.
read_urlencoded
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,) self.list = [] if self.qs_on_post: for key, value in urlparse.parse_qsl(self.qs_on_post, self.keep_blank_values, self.strict_parsing): self.list.append(MiniFieldStorage(key, value)) FieldStorageClass = None klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, ib, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
Internal: read a part that is itself multipart.
read_multi
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def read_lines(self): """Internal: read lines until EOF or outerboundary.""" self.file = self.__file = StringIO() if self.outerboundary: self.read_lines_to_outerboundary() else: self.read_lines_to_eof()
Internal: read lines until EOF or outerboundary.
read_lines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def skip_lines(self): """Internal: skip lines until outer boundary if defined.""" if not self.outerboundary or self.done: return next = "--" + self.outerboundary last = next + "--" last_line_lfend = True while 1: line = self.fp.readline(1<<16) if not line: self.done = -1 break if line[:2] == "--" and last_line_lfend: strippedline = line.strip() if strippedline == next: break if strippedline == last: self.done = 1 break last_line_lfend = line.endswith('\n')
Internal: skip lines until outer boundary if defined.
skip_lines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def test(environ=os.environ): """Robust test CGI script, usable as main program. Write minimal HTTP headers and dump all information provided to the script in HTML form. """ print "Content-type: text/html" print sys.stderr = sys.stdout try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) print_environ_usage() def f(): exec "testing print_exception() -- <I>italics?</I>" def g(f=f): f() print "<H3>What follows is a test, not an actual exception:</H3>" g() except: print_exception() print "<H1>Second try with a small maxlen...</H1>" global maxlen maxlen = 50 try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) except: print_exception()
Robust test CGI script, usable as main program. Write minimal HTTP headers and dump all information provided to the script in HTML form.
test
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def print_environ(environ=os.environ): """Dump the shell environment as HTML.""" keys = environ.keys() keys.sort() print print "<H3>Shell Environment:</H3>" print "<DL>" for key in keys: print "<DT>", escape(key), "<DD>", escape(environ[key]) print "</DL>" print
Dump the shell environment as HTML.
print_environ
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def print_form(form): """Dump the contents of a form as HTML.""" keys = form.keys() keys.sort() print print "<H3>Form Contents:</H3>" if not keys: print "<P>No form fields." print "<DL>" for key in keys: print "<DT>" + escape(key) + ":", value = form[key] print "<i>" + escape(repr(type(value))) + "</i>" print "<DD>" + escape(repr(value)) print "</DL>" print
Dump the contents of a form as HTML.
print_form
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def print_directory(): """Dump the current directory as HTML.""" print print "<H3>Current Working Directory:</H3>" try: pwd = os.getcwd() except os.error, msg: print "os.error:", escape(str(msg)) else: print escape(pwd) print
Dump the current directory as HTML.
print_directory
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def print_environ_usage(): """Dump a list of environment variables used by CGI as HTML.""" print """ <H3>These environment variables could have been set:</H3> <UL> <LI>AUTH_TYPE <LI>CONTENT_LENGTH <LI>CONTENT_TYPE <LI>DATE_GMT <LI>DATE_LOCAL <LI>DOCUMENT_NAME <LI>DOCUMENT_ROOT <LI>DOCUMENT_URI <LI>GATEWAY_INTERFACE <LI>LAST_MODIFIED <LI>PATH <LI>PATH_INFO <LI>PATH_TRANSLATED <LI>QUERY_STRING <LI>REMOTE_ADDR <LI>REMOTE_HOST <LI>REMOTE_IDENT <LI>REMOTE_USER <LI>REQUEST_METHOD <LI>SCRIPT_NAME <LI>SERVER_NAME <LI>SERVER_PORT <LI>SERVER_PROTOCOL <LI>SERVER_ROOT <LI>SERVER_SOFTWARE </UL> In addition, HTTP headers sent by the server may be passed in the environment as well. Here are some common variable names: <UL> <LI>HTTP_ACCEPT <LI>HTTP_CONNECTION <LI>HTTP_HOST <LI>HTTP_PRAGMA <LI>HTTP_REFERER <LI>HTTP_USER_AGENT </UL> """
Dump a list of environment variables used by CGI as HTML.
print_environ_usage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def escape(s, quote=None): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated.''' s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") return s
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated.
escape
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgi.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgi.py
MIT
def do_POST(self): """Serve a POST request. This is only implemented for CGI scripts. """ if self.is_cgi(): self.run_cgi() else: self.send_error(501, "Can only POST to CGI scripts")
Serve a POST request. This is only implemented for CGI scripts.
do_POST
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/CGIHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/CGIHTTPServer.py
MIT
def send_head(self): """Version of send_head that support CGI scripts""" if self.is_cgi(): return self.run_cgi() else: return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
Version of send_head that support CGI scripts
send_head
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/CGIHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/CGIHTTPServer.py
MIT
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
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).
is_cgi
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/CGIHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/CGIHTTPServer.py
MIT
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")
Test whether argument path is a Python script.
is_python
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/CGIHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/CGIHTTPServer.py
MIT
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(map(lambda x: x[2], pwd.getpwall())) return nobody
Internal routine to get nobody's uid
nobody_uid
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/CGIHTTPServer.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/CGIHTTPServer.py
MIT
def reset(): """Return a string that resets the CGI and browser to a known state.""" return '''<!--: spam Content-Type: text/html <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --> </font> </font> </font> </script> </object> </blockquote> </pre> </table> </table> </table> </table> </table> </font> </font> </font>'''
Return a string that resets the CGI and browser to a known state.
reset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgitb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgitb.py
MIT
def lookup(name, frame, locals): """Find the value for a given name in the given environment.""" if name in locals: return 'local', locals[name] if name in frame.f_globals: return 'global', frame.f_globals[name] if '__builtins__' in frame.f_globals: builtins = frame.f_globals['__builtins__'] if type(builtins) is type({}): if name in builtins: return 'builtin', builtins[name] else: if hasattr(builtins, name): return 'builtin', getattr(builtins, name) return None, __UNDEF__
Find the value for a given name in the given environment.
lookup
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgitb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgitb.py
MIT
def scanvars(reader, frame, locals): """Scan one logical line of Python and look up values of variables used.""" vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__ for ttype, token, start, end, line in tokenize.generate_tokens(reader): if ttype == tokenize.NEWLINE: break if ttype == tokenize.NAME and token not in keyword.kwlist: if lasttoken == '.': if parent is not __UNDEF__: value = getattr(parent, token, __UNDEF__) vars.append((prefix + token, prefix, value)) else: where, value = lookup(token, frame, locals) vars.append((token, where, value)) elif token == '.': prefix += lasttoken + '.' parent = value else: parent, prefix = None, '' lasttoken = token return vars
Scan one logical line of Python and look up values of variables used.
scanvars
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgitb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgitb.py
MIT
def html(einfo, context=5): """Return a nice HTML document describing a given traceback.""" etype, evalue, etb = einfo if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading( '<big><big>%s</big></big>' % strong(pydoc.html.escape(str(etype))), '#ffffff', '#6622aa', pyver + '<br>' + date) + ''' <p>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.</p>''' indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>' frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: if file: file = os.path.abspath(file) link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file)) else: file = link = '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in ' + strong(func) + \ inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value)) highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reader, frame, locals) rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' % ('<big>&nbsp;</big>', link, call)] if index is not None: i = lnum - index for line in lines: num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;' if i in highlight: line = '<tt>=&gt;%s%s</tt>' % (num, pydoc.html.preformat(line)) rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line) else: line = '<tt>&nbsp;&nbsp;%s%s</tt>' % (num, pydoc.html.preformat(line)) rows.append('<tr><td>%s</td></tr>' % grey(line)) i += 1 done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not __UNDEF__: if where in ('global', 'builtin'): name = ('<em>%s</em> ' % where) + strong(name) elif where == 'local': name = strong(name) else: name = where + strong(name.split('.')[-1]) dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value))) else: dump.append(name + ' <em>undefined</em>') rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump)))) frames.append(''' <table width="100%%" cellspacing=0 cellpadding=0 border=0> %s</table>''' % '\n'.join(rows)) exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))), pydoc.html.escape(str(evalue)))] if isinstance(evalue, BaseException): for name in dir(evalue): if name[:1] == '_': continue value = pydoc.html.repr(getattr(evalue, name)) exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value)) return head + ''.join(frames) + ''.join(exception) + ''' <!-- The above is a description of an error in a Python program, formatted for a Web browser because the 'cgitb' module was enabled. In case you are not reading this in a Web browser, here is the original traceback: %s --> ''' % pydoc.html.escape( ''.join(traceback.format_exception(etype, evalue, etb)))
Return a nice HTML document describing a given traceback.
html
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgitb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgitb.py
MIT
def text(einfo, context=5): """Return a plain text document describing a given traceback.""" etype, evalue, etb = einfo if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + ''' A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. ''' frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in ' + func + \ inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.text.repr(value)) highlight = {} def reader(lnum=[lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reader, frame, locals) rows = [' %s %s' % (file, call)] if index is not None: i = lnum - index for line in lines: num = '%5d ' % i rows.append(num+line.rstrip()) i += 1 done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not __UNDEF__: if where == 'global': name = 'global ' + name elif where != 'local': name = where + name.split('.')[-1] dump.append('%s = %s' % (name, pydoc.text.repr(value))) else: dump.append(name + ' undefined') rows.append('\n'.join(dump)) frames.append('\n%s\n' % '\n'.join(rows)) exception = ['%s: %s' % (str(etype), str(evalue))] if isinstance(evalue, BaseException): for name in dir(evalue): value = pydoc.text.repr(getattr(evalue, name)) exception.append('\n%s%s = %s' % (" "*4, name, value)) return head + ''.join(frames) + ''.join(exception) + ''' The above is a description of an error in a Python program. Here is the original traceback: %s ''' % ''.join(traceback.format_exception(etype, evalue, etb))
Return a plain text document describing a given traceback.
text
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cgitb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cgitb.py
MIT
def seek(self, pos, whence=0): """Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error. """ if self.closed: raise ValueError, "I/O operation on closed file" if not self.seekable: raise IOError, "cannot seek" if whence == 1: pos = pos + self.size_read elif whence == 2: pos = pos + self.chunksize if pos < 0 or pos > self.chunksize: raise RuntimeError self.file.seek(self.offset + pos, 0) self.size_read = pos
Seek to specified position into the chunk. Default position is 0 (start of chunk). If the file is not seekable, this will result in an error.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/chunk.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/chunk.py
MIT
def skip(self): """Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk. """ if self.closed: raise ValueError, "I/O operation on closed file" if self.seekable: try: n = self.chunksize - self.size_read # maybe fix alignment if self.align and (self.chunksize & 1): n = n + 1 self.file.seek(n, 1) self.size_read = self.size_read + n return except IOError: pass while self.size_read < self.chunksize: n = min(8192, self.chunksize - self.size_read) dummy = self.read(n) if not dummy: raise EOFError
Skip the rest of the chunk. If you are not interested in the contents of the chunk, this method should be called so that the file points to the start of the next chunk.
skip
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/chunk.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/chunk.py
MIT
def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ import sys if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey
Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except ImportError: pass try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
cmdloop
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def parseline(self, line): """Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """ line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed.
parseline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. """ cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if line == 'EOF' : self.lastcmd = '' if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg)
Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop.
onecmd
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: import readline origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped endidx = readline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None
Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions.
complete
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def do_help(self, arg): 'List available commands with "help" or detailed help with "help cmd".' if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, help.keys(),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
List available commands with "help" or detailed help with "help cmd".
do_help
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def columnize(self, list, displaywidth=80): """Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). """ if not list: self.stdout.write("<empty>\n") return nonstrings = [i for i in range(len(list)) if not isinstance(list[i], str)] if nonstrings: raise TypeError, ("list[i] not a string for i in %s" % ", ".join(map(str, nonstrings))) size = len(list) if size == 1: self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards for nrows in range(1, len(list)): ncols = (size+nrows-1) // nrows colwidths = [] totwidth = -2 for col in range(ncols): colwidth = 0 for row in range(nrows): i = row + nrows*col if i >= size: break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += colwidth + 2 if totwidth > displaywidth: break if totwidth <= displaywidth: break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = row + nrows*col if i >= size: x = "" else: x = list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write("%s\n"%str(" ".join(texts)))
Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).
columnize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/cmd.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/cmd.py
MIT
def __init__(self, locals=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. """ if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler()
Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def runsource(self, source, filename="<input>", symbol="single"): """Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line. """ try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False if code is None: # Case 2 return True # Case 3 self.runcode(code) return False
Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method. 2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens. 3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit). The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line.
runsource
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it. """ try: exec code in self.locals except SystemExit: raise except: self.showtraceback() else: if softspace(sys.stdout, 0): print
Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.
runcode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below. """ type, value, sys.last_traceback = sys.exc_info() sys.last_type = type sys.last_value = value if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value except: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value list = traceback.format_exception_only(type, value) map(self.write, list)
Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below.
showsyntaxerror
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def showtraceback(self): """Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below. """ try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] list = traceback.format_list(tblist) if list: list.insert(0, "Traceback (most recent call last):\n") list[len(list):] = traceback.format_exception_only(type, value) finally: tblist = tb = None map(self.write, list)
Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below.
showtraceback
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def __init__(self, locals=None, filename="<console>"): """Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks. """ InteractiveInterpreter.__init__(self, locals) self.filename = filename self.resetbuffer()
Constructor. The optional locals argument will be passed to the InteractiveInterpreter base class. The optional filename argument should specify the (file)name of the input stream; it will show up in tracebacks.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def interact(self, banner=None): """Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!). """ try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) else: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) # Can be None if sys.stdin was redefined encoding = getattr(sys.stdin, "encoding", None) if encoding and not isinstance(line, unicode): line = line.decode(encoding) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0
Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!).
interact
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def push(self, line): """Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()). """ self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more
Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).
push
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def interact(banner=None, readfunc=None, local=None): """Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__() """ console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner)
Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__()
interact
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/code.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/code.py
MIT
def __init__(self, errors='strict'): """ Creates an IncrementalEncoder instance. The IncrementalEncoder may use different error handling schemes by providing the errors keyword argument. See the module docstring for a list of possible values. """ self.errors = errors self.buffer = ""
Creates an IncrementalEncoder instance. The IncrementalEncoder may use different error handling schemes by providing the errors keyword argument. See the module docstring for a list of possible values.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT
def reset(self): """ Resets the encoder to the initial state. """
Resets the encoder to the initial state.
reset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT
def setstate(self, state): """ Set the current state of the encoder. state must have been returned by getstate(). """
Set the current state of the encoder. state must have been returned by getstate().
setstate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT
def reset(self): """ Resets the decoder to the initial state. """
Resets the decoder to the initial state.
reset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT
def setstate(self, state): """ Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset(). """
Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset().
setstate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT
def __init__(self, stream, errors='strict'): """ Creates a StreamWriter instance. stream must be a file-like object open for writing (binary) data. The StreamWriter may use different error handling schemes by providing the errors keyword argument. These parameters are predefined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'xmlcharrefreplace' - Replace with the appropriate XML character reference. 'backslashreplace' - Replace with backslashed escape sequences (only for encoding). The set of allowed parameter values can be extended via register_error. """ self.stream = stream self.errors = errors
Creates a StreamWriter instance. stream must be a file-like object open for writing (binary) data. The StreamWriter may use different error handling schemes by providing the errors keyword argument. These parameters are predefined: 'strict' - raise a ValueError (or a subclass) 'ignore' - ignore the character and continue with the next 'replace'- replace with a suitable replacement character 'xmlcharrefreplace' - Replace with the appropriate XML character reference. 'backslashreplace' - Replace with backslashed escape sequences (only for encoding). The set of allowed parameter values can be extended via register_error.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/codecs.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/codecs.py
MIT