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 setlocale(category, value=None): """ setlocale(integer,string=None) -> string. Activates/queries locale processing. """ if value not in (None, '', 'C'): raise Error, '_locale emulation only supports "C" locale' return 'C'
setlocale(integer,string=None) -> string. Activates/queries locale processing.
setlocale
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def format(percent, value, grouping=False, monetary=False, *additional): """Returns the locale-aware substitution of a %? specifier (percent). additional is for format strings which contain one or more '*' modifiers.""" # this is only for one-percent-specifier strings and this should be checked match = _percent_re.match(percent) if not match or len(match.group())!= len(percent): raise ValueError(("format() must be given exactly one %%char " "format specifier, %s not valid") % repr(percent)) return _format(percent, value, grouping, monetary, *additional)
Returns the locale-aware substitution of a %? specifier (percent). additional is for format strings which contain one or more '*' modifiers.
format
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def format_string(f, val, grouping=False): """Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.""" percents = list(_percent_re.finditer(f)) new_f = _percent_re.sub('%s', f) if operator.isMappingType(val): new_val = [] for perc in percents: if perc.group()[-1]=='%': new_val.append('%') else: new_val.append(format(perc.group(), val, grouping)) else: if not isinstance(val, tuple): val = (val,) new_val = [] i = 0 for perc in percents: if perc.group()[-1]=='%': new_val.append('%') else: starcount = perc.group('modifiers').count('*') new_val.append(_format(perc.group(), val[i], grouping, False, *val[i+1:i+1+starcount])) i += (1 + starcount) val = tuple(new_val) return new_f % val
Formats a string in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true.
format_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def currency(val, symbol=True, grouping=False, international=False): """Formats val according to the currency settings in the current locale.""" conv = localeconv() # check for illegal values digits = conv[international and 'int_frac_digits' or 'frac_digits'] if digits == 127: raise ValueError("Currency formatting is not possible using " "the 'C' locale.") s = format('%%.%if' % digits, abs(val), grouping, monetary=True) # '<' and '>' are markers if the sign must be inserted between symbol and value s = '<' + s + '>' if symbol: smb = conv[international and 'int_curr_symbol' or 'currency_symbol'] precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes'] separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space'] if precedes: s = smb + (separated and ' ' or '') + s else: s = s + (separated and ' ' or '') + smb sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn'] sign = conv[val<0 and 'negative_sign' or 'positive_sign'] if sign_pos == 0: s = '(' + s + ')' elif sign_pos == 1: s = sign + s elif sign_pos == 2: s = s + sign elif sign_pos == 3: s = s.replace('<', sign) elif sign_pos == 4: s = s.replace('>', sign) else: # the default if nothing specified; # this should be the most fitting sign position s = sign + s return s.replace('<', '').replace('>', '')
Formats val according to the currency settings in the current locale.
currency
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def atof(string, func=float): "Parses a string as a float according to the locale settings." #First, get rid of the grouping ts = localeconv()['thousands_sep'] if ts: string = string.replace(ts, '') #next, replace the decimal point with a dot dd = localeconv()['decimal_point'] if dd: string = string.replace(dd, '.') #finally, parse the string return func(string)
Parses a string as a float according to the locale settings.
atof
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def atoi(str): "Converts a string to an integer according to the locale settings." return atof(str, int)
Converts a string to an integer according to the locale settings.
atoi
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def normalize(localename): """ Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged. If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale() does. """ # Normalize the locale name and extract the encoding and modifier if isinstance(localename, _unicode): localename = localename.encode('ascii') code = localename.translate(_ascii_lower_map) if ':' in code: # ':' is sometimes used as encoding delimiter. code = code.replace(':', '.') if '@' in code: code, modifier = code.split('@', 1) else: modifier = '' if '.' in code: langname, encoding = code.split('.')[:2] else: langname = code encoding = '' # First lookup: fullname (possibly with encoding and modifier) lang_enc = langname if encoding: norm_encoding = encoding.replace('-', '') norm_encoding = norm_encoding.replace('_', '') lang_enc += '.' + norm_encoding lookup_name = lang_enc if modifier: lookup_name += '@' + modifier code = locale_alias.get(lookup_name, None) if code is not None: return code #print('first lookup failed') if modifier: # Second try: fullname without modifier (possibly with encoding) code = locale_alias.get(lang_enc, None) if code is not None: #print('lookup without modifier succeeded') if '@' not in code: return code + '@' + modifier if code.split('@', 1)[1].translate(_ascii_lower_map) == modifier: return code #print('second lookup failed') if encoding: # Third try: langname (without encoding, possibly with modifier) lookup_name = langname if modifier: lookup_name += '@' + modifier code = locale_alias.get(lookup_name, None) if code is not None: #print('lookup without encoding succeeded') if '@' not in code: return _replace_encoding(code, encoding) code, modifier = code.split('@', 1) return _replace_encoding(code, encoding) + '@' + modifier if modifier: # Fourth try: langname (without encoding and modifier) code = locale_alias.get(langname, None) if code is not None: #print('lookup without modifier and encoding succeeded') if '@' not in code: return _replace_encoding(code, encoding) + '@' + modifier code, defmod = code.split('@', 1) if defmod.translate(_ascii_lower_map) == modifier: return _replace_encoding(code, encoding) + '@' + defmod return localename
Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged. If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale() does.
normalize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def _parse_localename(localename): """ Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined or are unknown to this implementation. """ code = normalize(localename) if '@' in code: # Deal with locale modifiers code, modifier = code.split('@', 1) if modifier == 'euro' and '.' not in code: # Assume Latin-9 for @euro locales. This is bogus, # since some systems may use other encodings for these # locales. Also, we ignore other modifiers. return code, 'iso-8859-15' if '.' in code: return tuple(code.split('.')[:2]) elif code == 'C': return None, None raise ValueError, 'unknown locale: %s' % localename
Parses the locale code for localename and returns the result as tuple (language code, encoding). The localename is normalized and passed through the locale alias engine. A ValueError is raised in case the locale name cannot be parsed. The language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined or are unknown to this implementation.
_parse_localename
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def _build_localename(localetuple): """ Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place. """ language, encoding = localetuple if language is None: language = 'C' if encoding is None: return language else: return language + '.' + encoding
Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place.
_build_localename
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')): """ Tries to determine the default locale settings and returns them as tuple (language code, encoding). According to POSIX, a program which has not called setlocale(LC_ALL, "") runs using the portable 'C' locale. Calling setlocale(LC_ALL, "") lets it use the default locale as defined by the LANG variable. Since we don't want to interfere with the current locale setting we thus emulate the behavior in the way described above. To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. Except for the code 'C', the language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined. """ try: # check if it's supported by the _locale module import _locale code, encoding = _locale._getdefaultlocale() except (ImportError, AttributeError): pass else: # make sure the code/encoding values are valid if sys.platform == "win32" and code and code[:2] == "0x": # map windows language identifier to language name code = windows_locale.get(int(code, 0)) # ...add other platform-specific processing here, if # necessary... return code, encoding # fall back on POSIX behaviour import os lookup = os.environ.get for variable in envvars: localename = lookup(variable,None) if localename: if variable == 'LANGUAGE': localename = localename.split(':')[0] break else: localename = 'C' return _parse_localename(localename)
Tries to determine the default locale settings and returns them as tuple (language code, encoding). According to POSIX, a program which has not called setlocale(LC_ALL, "") runs using the portable 'C' locale. Calling setlocale(LC_ALL, "") lets it use the default locale as defined by the LANG variable. Since we don't want to interfere with the current locale setting we thus emulate the behavior in the way described above. To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. Except for the code 'C', the language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined.
getdefaultlocale
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def getlocale(category=LC_CTYPE): """ Returns the current setting for the given locale category as tuple (language code, encoding). category may be one of the LC_* value except LC_ALL. It defaults to LC_CTYPE. Except for the code 'C', the language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined. """ localename = _setlocale(category) if category == LC_ALL and ';' in localename: raise TypeError, 'category LC_ALL is not supported' return _parse_localename(localename)
Returns the current setting for the given locale category as tuple (language code, encoding). category may be one of the LC_* value except LC_ALL. It defaults to LC_CTYPE. Except for the code 'C', the language code corresponds to RFC 1766. code and encoding can be None in case the values cannot be determined.
getlocale
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def setlocale(category, locale=None): """ Set the locale for the given category. The locale can be a string, an iterable of two strings (language code and encoding), or None. Iterables are converted to strings using the locale aliasing engine. Locale strings are passed directly to the C lib. category may be given as one of the LC_* values. """ if locale and not isinstance(locale, (_str, _unicode)): # convert to string locale = normalize(_build_localename(locale)) return _setlocale(category, locale)
Set the locale for the given category. The locale can be a string, an iterable of two strings (language code and encoding), or None. Iterables are converted to strings using the locale aliasing engine. Locale strings are passed directly to the C lib. category may be given as one of the LC_* values.
setlocale
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def getpreferredencoding(do_setlocale = True): """Return the charset that the user is likely using, according to the system configuration.""" if do_setlocale: oldloc = setlocale(LC_CTYPE) try: setlocale(LC_CTYPE, "") except Error: pass result = nl_langinfo(CODESET) setlocale(LC_CTYPE, oldloc) return result else: return nl_langinfo(CODESET)
Return the charset that the user is likely using, according to the system configuration.
getpreferredencoding
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/locale.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/locale.py
MIT
def split(s): """Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.""" if ':' not in s: return '', s colon = 0 for i in range(len(s)): if s[i] == ':': colon = i + 1 path, file = s[:colon-1], s[colon:] if path and not ':' in path: path = path + ':' return path, file
Split a pathname into two parts: the directory leading up to the final bit, and the basename (the filename, without colons, in that directory). The result (s, t) is such that join(s, t) yields the original argument.
split
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macpath.py
MIT
def islink(s): """Return true if the pathname refers to a symbolic link.""" try: import Carbon.File return Carbon.File.ResolveAliasFile(s, 0)[2] except: return False
Return true if the pathname refers to a symbolic link.
islink
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macpath.py
MIT
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: st = os.lstat(path) except os.error: return False return True
Test whether a path exists. Returns True for broken symbolic links
lexists
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macpath.py
MIT
def normpath(s): """Normalize a pathname. Will return the same result for equivalent paths.""" if ":" not in s: return ":"+s comps = s.split(":") i = 1 while i < len(comps)-1: if comps[i] == "" and comps[i-1] != "": if i > 1: del comps[i-1:i+1] i = i - 1 else: # best way to handle this is to raise an exception raise norm_error, 'Cannot use :: immediately after volume name' else: i = i + 1 s = ":".join(comps) # remove trailing ":" except for ":" and "Volume:" if s[-1] == ":" and len(comps) > 2 and s != ":"*len(s): s = s[:-1] return s
Normalize a pathname. Will return the same result for equivalent paths.
normpath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macpath.py
MIT
def walk(top, func, arg): """Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.""" warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.", stacklevel=2) try: names = os.listdir(top) except os.error: return func(arg, top, names) for name in names: name = join(top, name) if isdir(name) and not islink(name): walk(name, func, arg)
Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common.
walk
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macpath.py
MIT
def url2pathname(pathname): """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" # # XXXX The .. handling should be fixed... # tp = urllib.splittype(pathname)[0] if tp and tp != 'file': raise RuntimeError, 'Cannot convert non-local URL to pathname' # Turn starting /// into /, an empty hostname means current host if pathname[:3] == '///': pathname = pathname[2:] elif pathname[:2] == '//': raise RuntimeError, 'Cannot convert non-local URL to pathname' components = pathname.split('/') # Remove . and embedded .. i = 0 while i < len(components): if components[i] == '.': del components[i] elif components[i] == '..' and i > 0 and \ components[i-1] not in ('', '..'): del components[i-1:i+1] i = i-1 elif components[i] == '' and i > 0 and components[i-1] != '': del components[i] else: i = i+1 if not components[0]: # Absolute unix path, don't start with colon rv = ':'.join(components[1:]) else: # relative unix path, start with colon. First replace # leading .. by empty strings (giving ::file) i = 0 while i < len(components) and components[i] == '..': components[i] = '' i = i + 1 rv = ':' + ':'.join(components) # and finally unquote slashes and other funny characters return urllib.unquote(rv)
OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.
url2pathname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macurl2path.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macurl2path.py
MIT
def pathname2url(pathname): """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.""" if '/' in pathname: raise RuntimeError, "Cannot convert pathname containing slashes" components = pathname.split(':') # Remove empty first and/or last component if components[0] == '': del components[0] if components[-1] == '': del components[-1] # Replace empty string ('::') by .. (will result in '/../' later) for i in range(len(components)): if components[i] == '': components[i] = '..' # Truncate names longer than 31 bytes components = map(_pncomp2url, components) if os.path.isabs(pathname): return '/' + '/'.join(components) else: return '/'.join(components)
OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.
pathname2url
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/macurl2path.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/macurl2path.py
MIT
def discard(self, key): """If the keyed message exists, remove it.""" try: self.remove(key) except KeyError: pass
If the keyed message exists, remove it.
discard
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get(self, key, default=None): """Return the keyed message, or default if it doesn't exist.""" try: return self.__getitem__(key) except KeyError: return default
Return the keyed message, or default if it doesn't exist.
get
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def __getitem__(self, key): """Return the keyed message; raise KeyError if it doesn't exist.""" if not self._factory: return self.get_message(key) else: return self._factory(self.get_file(key))
Return the keyed message; raise KeyError if it doesn't exist.
__getitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def itervalues(self): """Return an iterator over all messages.""" for key in self.iterkeys(): try: value = self[key] except KeyError: continue yield value
Return an iterator over all messages.
itervalues
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def iteritems(self): """Return an iterator over (key, message) tuples.""" for key in self.iterkeys(): try: value = self[key] except KeyError: continue yield (key, value)
Return an iterator over (key, message) tuples.
iteritems
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def pop(self, key, default=None): """Delete the keyed message and return it, or default.""" try: result = self[key] except KeyError: return default self.discard(key) return result
Delete the keyed message and return it, or default.
pop
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def popitem(self): """Delete an arbitrary (key, message) pair and return it.""" for key in self.iterkeys(): return (key, self.pop(key)) # This is only run once. else: raise KeyError('No messages in mailbox')
Delete an arbitrary (key, message) pair and return it.
popitem
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def update(self, arg=None): """Change the messages that correspond to certain keys.""" if hasattr(arg, 'iteritems'): source = arg.iteritems() elif hasattr(arg, 'items'): source = arg.items() else: source = arg bad_key = False for key, message in source: try: self[key] = message except KeyError: bad_key = True if bad_key: raise KeyError('No message with key(s)')
Change the messages that correspond to certain keys.
update
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _dump_message(self, message, target, mangle_from_=False): # Most files are opened in binary mode to allow predictable seeking. # To get native line endings on disk, the user-friendly \n line endings # used in strings and by email.Message are translated here. """Dump message contents to target file.""" if isinstance(message, email.message.Message): buffer = StringIO.StringIO() gen = email.generator.Generator(buffer, mangle_from_, 0) gen.flatten(message) buffer.seek(0) data = buffer.read().replace('\n', os.linesep) target.write(data) if self._append_newline and not data.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) elif isinstance(message, str): if mangle_from_: message = message.replace('\nFrom ', '\n>From ') message = message.replace('\n', os.linesep) target.write(message) if self._append_newline and not message.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) elif hasattr(message, 'read'): lastline = None while True: line = message.readline() if line == '': break if mangle_from_ and line.startswith('From '): line = '>From ' + line[5:] line = line.replace('\n', os.linesep) target.write(line) lastline = line if self._append_newline and lastline and not lastline.endswith(os.linesep): # Make sure the message ends with a newline target.write(os.linesep) else: raise TypeError('Invalid message type: %s' % type(message))
Dump message contents to target file.
_dump_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add(self, message): """Add message and return assigned key.""" tmp_file = self._create_tmp() try: self._dump_message(message, tmp_file) except BaseException: tmp_file.close() os.remove(tmp_file.name) raise _sync_close(tmp_file) if isinstance(message, MaildirMessage): subdir = message.get_subdir() suffix = self.colon + message.get_info() if suffix == self.colon: suffix = '' else: subdir = 'new' suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) if isinstance(message, MaildirMessage): os.utime(tmp_file.name, (os.path.getatime(tmp_file.name), message.get_date())) # No file modification should be done after the file is moved to its # final position in order to prevent race conditions with changes # from other programs try: if hasattr(os, 'link'): os.link(tmp_file.name, dest) os.remove(tmp_file.name) else: os.rename(tmp_file.name, dest) except OSError, e: os.remove(tmp_file.name) if e.errno == errno.EEXIST: raise ExternalClashError('Name clash with existing message: %s' % dest) else: raise return uniq
Add message and return assigned key.
add
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def discard(self, key): """If the keyed message exists, remove it.""" # This overrides an inapplicable implementation in the superclass. try: self.remove(key) except KeyError: pass except OSError, e: if e.errno != errno.ENOENT: raise
If the keyed message exists, remove it.
discard
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" old_subpath = self._lookup(key) temp_key = self.add(message) temp_subpath = self._lookup(temp_key) if isinstance(message, MaildirMessage): # temp's subdir and suffix were specified by message. dominant_subpath = temp_subpath else: # temp's subdir and suffix were defaults from add(). dominant_subpath = old_subpath subdir = os.path.dirname(dominant_subpath) if self.colon in dominant_subpath: suffix = self.colon + dominant_subpath.split(self.colon)[-1] else: suffix = '' self.discard(key) tmp_path = os.path.join(self._path, temp_subpath) new_path = os.path.join(self._path, subdir, key + suffix) if isinstance(message, MaildirMessage): os.utime(tmp_path, (os.path.getatime(tmp_path), message.get_date())) # No file modification should be done after the file is moved to its # final position in order to prevent race conditions with changes # from other programs os.rename(tmp_path, new_path)
Replace the keyed message; raise KeyError if it doesn't exist.
__setitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_message(self, key): """Return a Message representation or raise a KeyError.""" subpath = self._lookup(key) f = open(os.path.join(self._path, subpath), 'r') try: if self._factory: msg = self._factory(f) else: msg = MaildirMessage(f) finally: f.close() subdir, name = os.path.split(subpath) msg.set_subdir(subdir) if self.colon in name: msg.set_info(name.split(self.colon)[-1]) msg.set_date(os.path.getmtime(os.path.join(self._path, subpath))) return msg
Return a Message representation or raise a KeyError.
get_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_string(self, key): """Return a string representation or raise a KeyError.""" f = open(os.path.join(self._path, self._lookup(key)), 'r') try: return f.read() finally: f.close()
Return a string representation or raise a KeyError.
get_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def has_key(self, key): """Return True if the keyed message exists, False otherwise.""" self._refresh() return key in self._toc
Return True if the keyed message exists, False otherwise.
has_key
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def flush(self): """Write any pending changes to disk.""" # Maildir changes are always written immediately, so there's nothing # to do. pass
Write any pending changes to disk.
flush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add_folder(self, folder): """Create a folder and return a Maildir instance representing it.""" path = os.path.join(self._path, '.' + folder) result = Maildir(path, factory=self._factory) maildirfolder_path = os.path.join(path, 'maildirfolder') if not os.path.exists(maildirfolder_path): os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY, 0666)) return result
Create a folder and return a Maildir instance representing it.
add_folder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_folder(self, folder): """Delete the named folder, which must be empty.""" path = os.path.join(self._path, '.' + folder) for entry in os.listdir(os.path.join(path, 'new')) + \ os.listdir(os.path.join(path, 'cur')): if len(entry) < 1 or entry[0] != '.': raise NotEmptyError('Folder contains message(s): %s' % folder) for entry in os.listdir(path): if entry != 'new' and entry != 'cur' and entry != 'tmp' and \ os.path.isdir(os.path.join(path, entry)): raise NotEmptyError("Folder contains subdirectory '%s': %s" % (folder, entry)) for root, dirs, files in os.walk(path, topdown=False): for entry in files: os.remove(os.path.join(root, entry)) for entry in dirs: os.rmdir(os.path.join(root, entry)) os.rmdir(path)
Delete the named folder, which must be empty.
remove_folder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _create_tmp(self): """Create a file in the tmp subdirectory and open and return it.""" now = time.time() hostname = socket.gethostname() if '/' in hostname: hostname = hostname.replace('/', r'\057') if ':' in hostname: hostname = hostname.replace(':', r'\072') uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(), Maildir._count, hostname) path = os.path.join(self._path, 'tmp', uniq) try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: Maildir._count += 1 try: return _create_carefully(path) except OSError, e: if e.errno != errno.EEXIST: raise else: raise # Fall through to here if stat succeeded or open raised EEXIST. raise ExternalClashError('Name clash prevented file creation: %s' % path)
Create a file in the tmp subdirectory and open and return it.
_create_tmp
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _lookup(self, key): """Use TOC to return subpath for given key, or raise a KeyError.""" try: if os.path.exists(os.path.join(self._path, self._toc[key])): return self._toc[key] except KeyError: pass self._refresh() try: return self._toc[key] except KeyError: raise KeyError('No message with key: %s' % key)
Use TOC to return subpath for given key, or raise a KeyError.
_lookup
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def next(self): """Return the next message in a one-time iteration.""" if not hasattr(self, '_onetime_keys'): self._onetime_keys = self.iterkeys() while True: try: return self[self._onetime_keys.next()] except StopIteration: return None except KeyError: continue
Return the next message in a one-time iteration.
next
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add(self, message): """Add message and return assigned key.""" self._lookup() self._toc[self._next_key] = self._append_message(message) self._next_key += 1 # _append_message appends the message to the mailbox file. We # don't need a full rewrite + rename, sync is enough. self._pending_sync = True return self._next_key - 1
Add message and return assigned key.
add
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" self._lookup(key) del self._toc[key] self._pending = True
Remove the keyed message; raise KeyError if it doesn't exist.
remove
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" self._lookup(key) self._toc[key] = self._append_message(message) self._pending = True
Replace the keyed message; raise KeyError if it doesn't exist.
__setitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def has_key(self, key): """Return True if the keyed message exists, False otherwise.""" self._lookup() return key in self._toc
Return True if the keyed message exists, False otherwise.
has_key
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def unlock(self): """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) self._locked = False
Unlock the mailbox if it is locked.
unlock
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def flush(self): """Write any pending changes to disk.""" if not self._pending: if self._pending_sync: # Messages have only been added, so syncing the file # is enough. _sync_flush(self._file) self._pending_sync = False return # In order to be writing anything out at all, self._toc must # already have been generated (and presumably has been modified # by adding or deleting an item). assert self._toc is not None # Check length of self._file; if it's changed, some other process # has modified the mailbox since we scanned it. self._file.seek(0, 2) cur_len = self._file.tell() if cur_len != self._file_length: raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len)) new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_start = new_file.tell() while True: buffer = self._file.read(min(4096, stop - self._file.tell())) if buffer == '': break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) self._file_length = new_file.tell() except: new_file.close() os.remove(new_file.name) raise _sync_close(new_file) # self._file is about to get replaced, so no need to sync. self._file.close() # Make sure the new file's mode is the same as the old file's mode = os.stat(self._path).st_mode os.chmod(new_file.name, mode) try: os.rename(new_file.name, self._path) except OSError, e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) os.rename(new_file.name, self._path) else: raise self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False self._pending_sync = False if self._locked: _lock_file(self._file, dotlock=False)
Write any pending changes to disk.
flush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _lookup(self, key=None): """Return (start, stop) or raise KeyError.""" if self._toc is None: self._generate_toc() if key is not None: try: return self._toc[key] except KeyError: raise KeyError('No message with key: %s' % key)
Return (start, stop) or raise KeyError.
_lookup
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _append_message(self, message): """Append message to mailbox and return (start, stop) offsets.""" self._file.seek(0, 2) before = self._file.tell() if len(self._toc) == 0 and not self._pending: # This is the first message, and the _pre_mailbox_hook # hasn't yet been called. If self._pending is True, # messages have been removed, so _pre_mailbox_hook must # have been called already. self._pre_mailbox_hook(self._file) try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseException: self._file.truncate(before) raise self._file.flush() self._file_length = self._file.tell() # Record current length of mailbox return offsets
Append message to mailbox and return (start, stop) offsets.
_append_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) from_line = self._file.readline().replace(os.linesep, '') string = self._file.read(stop - self._file.tell()) msg = self._message_factory(string.replace(os.linesep, '\n')) msg.set_from(from_line[5:]) return msg
Return a Message representation or raise a KeyError.
get_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_string(self, key, from_=False): """Return a string representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) if not from_: self._file.readline() string = self._file.read(stop - self._file.tell()) return string.replace(os.linesep, '\n')
Return a string representation or raise a KeyError.
get_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_file(self, key, from_=False): """Return a file-like representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) if not from_: self._file.readline() return _PartialFile(self._file, self._file.tell(), stop)
Return a file-like representation or raise a KeyError.
get_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _install_message(self, message): """Format a message and blindly write to self._file.""" from_line = None if isinstance(message, str) and message.startswith('From '): newline = message.find('\n') if newline != -1: from_line = message[:newline] message = message[newline + 1:] else: from_line = message message = '' elif isinstance(message, _mboxMMDFMessage): from_line = 'From ' + message.get_from() elif isinstance(message, email.message.Message): from_line = message.get_unixfrom() # May be None. if from_line is None: from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime()) start = self._file.tell() self._file.write(from_line + os.linesep) self._dump_message(message, self._file, self._mangle_from_) stop = self._file.tell() return (start, stop)
Format a message and blindly write to self._file.
_install_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] last_was_empty = False self._file.seek(0) while True: line_pos = self._file.tell() line = self._file.readline() if line.startswith('From '): if len(stops) < len(starts): if last_was_empty: stops.append(line_pos - len(os.linesep)) else: # The last line before the "From " line wasn't # blank, but we consider it a start of a # message anyway. stops.append(line_pos) starts.append(line_pos) last_was_empty = False elif not line: if last_was_empty: stops.append(line_pos - len(os.linesep)) else: stops.append(line_pos) break elif line == os.linesep: last_was_empty = True else: last_was_empty = False self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file_length = self._file.tell()
Generate key-to-(start, stop) table of contents.
_generate_toc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line.startswith('\001\001\001\001' + os.linesep): starts.append(next_pos) while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\001\001\001\001' + os.linesep: stops.append(line_pos - len(os.linesep)) break elif line == '': stops.append(line_pos) break elif line == '': break self._toc = dict(enumerate(zip(starts, stops))) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell()
Generate key-to-(start, stop) table of contents.
_generate_toc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add(self, message): """Add message and return assigned key.""" keys = self.keys() if len(keys) == 0: new_key = 1 else: new_key = max(keys) + 1 new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False try: if self._locked: _lock_file(f) try: try: self._dump_message(message, f) except BaseException: # Unlock and close so it can be deleted on Windows if self._locked: _unlock_file(f) _sync_close(f) closed = True os.remove(new_path) raise if isinstance(message, MHMessage): self._dump_sequences(message, new_key) finally: if self._locked: _unlock_file(f) finally: if not closed: _sync_close(f) return new_key
Add message and return assigned key.
add
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise else: f.close() os.remove(path)
Remove the keyed message; raise KeyError if it doesn't exist.
remove
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) try: os.close(os.open(path, os.O_WRONLY | os.O_TRUNC)) self._dump_message(message, f) if isinstance(message, MHMessage): self._dump_sequences(message, key) finally: if self._locked: _unlock_file(f) finally: _sync_close(f)
Replace the keyed message; raise KeyError if it doesn't exist.
__setitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_message(self, key): """Return a Message representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) try: msg = MHMessage(f) finally: if self._locked: _unlock_file(f) finally: f.close() for name, key_list in self.get_sequences().iteritems(): if key in key_list: msg.add_sequence(name) return msg
Return a Message representation or raise a KeyError.
get_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_string(self, key): """Return a string representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise try: if self._locked: _lock_file(f) try: return f.read() finally: if self._locked: _unlock_file(f) finally: f.close()
Return a string representation or raise a KeyError.
get_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_file(self, key): """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise return _ProxyFile(f)
Return a file-like representation or raise a KeyError.
get_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def unlock(self): """Unlock the mailbox if it is locked.""" if self._locked: _unlock_file(self._file) _sync_close(self._file) del self._file self._locked = False
Unlock the mailbox if it is locked.
unlock
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_folder(self, folder): """Delete the named folder, which must be empty.""" path = os.path.join(self._path, folder) entries = os.listdir(path) if entries == ['.mh_sequences']: os.remove(os.path.join(path, '.mh_sequences')) elif entries == []: pass else: raise NotEmptyError('Folder not empty: %s' % self._path) os.rmdir(path)
Delete the named folder, which must be empty.
remove_folder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_sequences(self): """Return a name-to-key-list dictionary to define each sequence.""" results = {} f = open(os.path.join(self._path, '.mh_sequences'), 'r') try: all_keys = set(self.keys()) for line in f: try: name, contents = line.split(':') keys = set() for spec in contents.split(): if spec.isdigit(): keys.add(int(spec)) else: start, stop = (int(x) for x in spec.split('-')) keys.update(range(start, stop + 1)) results[name] = [key for key in sorted(keys) \ if key in all_keys] if len(results[name]) == 0: del results[name] except ValueError: raise FormatError('Invalid sequence specification: %s' % line.rstrip()) finally: f.close() return results
Return a name-to-key-list dictionary to define each sequence.
get_sequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def set_sequences(self, sequences): """Set sequences using the given name-to-key-list dictionary.""" f = open(os.path.join(self._path, '.mh_sequences'), 'r+') try: os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) for name, keys in sequences.iteritems(): if len(keys) == 0: continue f.write('%s:' % name) prev = None completing = False for key in sorted(set(keys)): if key - 1 == prev: if not completing: completing = True f.write('-') elif completing: completing = False f.write('%s %s' % (prev, key)) else: f.write(' %s' % key) prev = key if completing: f.write(str(prev) + '\n') else: f.write('\n') finally: _sync_close(f)
Set sequences using the given name-to-key-list dictionary.
set_sequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def pack(self): """Re-name messages to eliminate numbering gaps. Invalidates keys.""" sequences = self.get_sequences() prev = 0 changes = [] for key in self.iterkeys(): if key - 1 != prev: changes.append((key, prev + 1)) if hasattr(os, 'link'): os.link(os.path.join(self._path, str(key)), os.path.join(self._path, str(prev + 1))) os.unlink(os.path.join(self._path, str(key))) else: os.rename(os.path.join(self._path, str(key)), os.path.join(self._path, str(prev + 1))) prev += 1 self._next_key = prev + 1 if len(changes) == 0: return for name, key_list in sequences.items(): for old, new in changes: if old in key_list: key_list[key_list.index(old)] = new self.set_sequences(sequences)
Re-name messages to eliminate numbering gaps. Invalidates keys.
pack
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _dump_sequences(self, message, key): """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for name, key_list in all_sequences.iteritems(): if name in pending_sequences: key_list.append(key) elif key in key_list: del key_list[key_list.index(key)] for sequence in pending_sequences: if sequence not in all_sequences: all_sequences[sequence] = [key] self.set_sequences(all_sequences)
Inspect a new MHMessage and update sequences appropriately.
_dump_sequences
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add(self, message): """Add message and return assigned key.""" key = _singlefileMailbox.add(self, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels() return key
Add message and return assigned key.
add
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.remove(self, key) if key in self._labels: del self._labels[key]
Remove the keyed message; raise KeyError if it doesn't exist.
remove
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.__setitem__(self, key, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels()
Replace the keyed message; raise KeyError if it doesn't exist.
__setitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_message(self, key): """Return a Message representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip '1,' line specifying labels. original_headers = StringIO.StringIO() while True: line = self._file.readline() if line == '*** EOOH ***' + os.linesep or line == '': break original_headers.write(line.replace(os.linesep, '\n')) visible_headers = StringIO.StringIO() while True: line = self._file.readline() if line == os.linesep or line == '': break visible_headers.write(line.replace(os.linesep, '\n')) body = self._file.read(stop - self._file.tell()).replace(os.linesep, '\n') msg = BabylMessage(original_headers.getvalue() + body) msg.set_visible(visible_headers.getvalue()) if key in self._labels: msg.set_labels(self._labels[key]) return msg
Return a Message representation or raise a KeyError.
get_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_string(self, key): """Return a string representation or raise a KeyError.""" start, stop = self._lookup(key) self._file.seek(start) self._file.readline() # Skip '1,' line specifying labels. original_headers = StringIO.StringIO() while True: line = self._file.readline() if line == '*** EOOH ***' + os.linesep or line == '': break original_headers.write(line.replace(os.linesep, '\n')) while True: line = self._file.readline() if line == os.linesep or line == '': break return original_headers.getvalue() + \ self._file.read(stop - self._file.tell()).replace(os.linesep, '\n')
Return a string representation or raise a KeyError.
get_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_labels(self): """Return a list of user-defined labels in the mailbox.""" self._lookup() labels = set() for label_list in self._labels.values(): labels.update(label_list) labels.difference_update(self._special_labels) return list(labels)
Return a list of user-defined labels in the mailbox.
get_labels
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\037\014' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) starts.append(next_pos) labels = [label.strip() for label in self._file.readline()[1:].split(',') if label.strip() != ''] label_lists.append(labels) elif line == '\037' or line == '\037' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) elif line == '': stops.append(line_pos - len(os.linesep)) break self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell()
Generate key-to-(start, stop) table of contents.
_generate_toc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _pre_mailbox_hook(self, f): """Called before writing the mailbox to file f.""" f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' % (os.linesep, os.linesep, ','.join(self.get_labels()), os.linesep))
Called before writing the mailbox to file f.
_pre_mailbox_hook
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _install_message(self, message): """Write message contents and return (start, stop).""" start = self._file.tell() if isinstance(message, BabylMessage): special_labels = [] labels = [] for label in message.get_labels(): if label in self._special_labels: special_labels.append(label) else: labels.append(label) self._file.write('1') for label in special_labels: self._file.write(', ' + label) self._file.write(',,') for label in labels: self._file.write(' ' + label + ',') self._file.write(os.linesep) else: self._file.write('1,,' + os.linesep) if isinstance(message, email.message.Message): orig_buffer = StringIO.StringIO() orig_generator = email.generator.Generator(orig_buffer, False, 0) orig_generator.flatten(message) orig_buffer.seek(0) while True: line = orig_buffer.readline() self._file.write(line.replace('\n', os.linesep)) if line == '\n' or line == '': break self._file.write('*** EOOH ***' + os.linesep) if isinstance(message, BabylMessage): vis_buffer = StringIO.StringIO() vis_generator = email.generator.Generator(vis_buffer, False, 0) vis_generator.flatten(message.get_visible()) while True: line = vis_buffer.readline() self._file.write(line.replace('\n', os.linesep)) if line == '\n' or line == '': break else: orig_buffer.seek(0) while True: line = orig_buffer.readline() self._file.write(line.replace('\n', os.linesep)) if line == '\n' or line == '': break while True: buffer = orig_buffer.read(4096) # Buffer size is arbitrary. if buffer == '': break self._file.write(buffer.replace('\n', os.linesep)) elif isinstance(message, str): body_start = message.find('\n\n') + 2 if body_start - 2 != -1: self._file.write(message[:body_start].replace('\n', os.linesep)) self._file.write('*** EOOH ***' + os.linesep) self._file.write(message[:body_start].replace('\n', os.linesep)) self._file.write(message[body_start:].replace('\n', os.linesep)) else: self._file.write('*** EOOH ***' + os.linesep + os.linesep) self._file.write(message.replace('\n', os.linesep)) elif hasattr(message, 'readline'): original_pos = message.tell() first_pass = True while True: line = message.readline() self._file.write(line.replace('\n', os.linesep)) if line == '\n' or line == '': if first_pass: first_pass = False self._file.write('*** EOOH ***' + os.linesep) message.seek(original_pos) else: break while True: buffer = message.read(4096) # Buffer size is arbitrary. if buffer == '': break self._file.write(buffer.replace('\n', os.linesep)) else: raise TypeError('Invalid message type: %s' % type(message)) stop = self._file.tell() return (start, stop)
Write message contents and return (start, stop).
_install_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _become_message(self, message): """Assume the non-format-specific state of message.""" for name in ('_headers', '_unixfrom', '_payload', '_charset', 'preamble', 'epilogue', 'defects', '_default_type'): self.__dict__[name] = message.__dict__[name]
Assume the non-format-specific state of message.
_become_message
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _explain_to(self, message): """Copy format-specific state to message insofar as possible.""" if isinstance(message, Message): return # There's nothing format-specific to explain. else: raise TypeError('Cannot convert to specified type')
Copy format-specific state to message insofar as possible.
_explain_to
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def set_subdir(self, subdir): """Set subdir to 'new' or 'cur'.""" if subdir == 'new' or subdir == 'cur': self._subdir = subdir else: raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
Set subdir to 'new' or 'cur'.
set_subdir
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def get_flags(self): """Return as a string the flags that are set.""" if self._info.startswith('2,'): return self._info[2:] else: return ''
Return as a string the flags that are set.
get_flags
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if self.get_flags() != '': self.set_flags(''.join(set(self.get_flags()) - set(flag)))
Unset the given string flag(s) without changing others.
remove_flag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def set_date(self, date): """Set delivery date of message, in seconds since the epoch.""" try: self._date = float(date) except ValueError: raise TypeError("can't convert to float: %s" % date)
Set delivery date of message, in seconds since the epoch.
set_date
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _explain_to(self, message): """Copy Maildir-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): message.set_flags(self.get_flags()) message.set_subdir(self.get_subdir()) message.set_date(self.get_date()) elif isinstance(message, _mboxMMDFMessage): flags = set(self.get_flags()) if 'S' in flags: message.add_flag('R') if self.get_subdir() == 'cur': message.add_flag('O') if 'T' in flags: message.add_flag('D') if 'F' in flags: message.add_flag('F') if 'R' in flags: message.add_flag('A') message.set_from('MAILER-DAEMON', time.gmtime(self.get_date())) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if 'S' not in flags: message.add_sequence('unseen') if 'R' in flags: message.add_sequence('replied') if 'F' in flags: message.add_sequence('flagged') elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if 'S' not in flags: message.add_label('unseen') if 'T' in flags: message.add_label('deleted') if 'R' in flags: message.add_label('answered') if 'P' in flags: message.add_label('forwarded') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
Copy Maildir-specific state to message insofar as possible.
_explain_to
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def set_from(self, from_, time_=None): """Set "From " line, formatting and appending time_ if specified.""" if time_ is not None: if time_ is True: time_ = time.gmtime() from_ += ' ' + time.asctime(time_) self._from = from_
Set "From " line, formatting and appending time_ if specified.
set_from
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def set_flags(self, flags): """Set the given flags and unset all others.""" flags = set(flags) status_flags, xstatus_flags = '', '' for flag in ('R', 'O'): if flag in flags: status_flags += flag flags.remove(flag) for flag in ('D', 'F', 'A'): if flag in flags: xstatus_flags += flag flags.remove(flag) xstatus_flags += ''.join(sorted(flags)) try: self.replace_header('Status', status_flags) except KeyError: self.add_header('Status', status_flags) try: self.replace_header('X-Status', xstatus_flags) except KeyError: self.add_header('X-Status', xstatus_flags)
Set the given flags and unset all others.
set_flags
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if 'Status' in self or 'X-Status' in self: self.set_flags(''.join(set(self.get_flags()) - set(flag)))
Unset the given string flag(s) without changing others.
remove_flag
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _explain_to(self, message): """Copy mbox- or MMDF-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): flags = set(self.get_flags()) if 'O' in flags: message.set_subdir('cur') if 'F' in flags: message.add_flag('F') if 'A' in flags: message.add_flag('R') if 'R' in flags: message.add_flag('S') if 'D' in flags: message.add_flag('T') del message['status'] del message['x-status'] maybe_date = ' '.join(self.get_from().split()[-5:]) try: message.set_date(calendar.timegm(time.strptime(maybe_date, '%a %b %d %H:%M:%S %Y'))) except (ValueError, OverflowError): pass elif isinstance(message, _mboxMMDFMessage): message.set_flags(self.get_flags()) message.set_from(self.get_from()) elif isinstance(message, MHMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_sequence('unseen') if 'A' in flags: message.add_sequence('replied') if 'F' in flags: message.add_sequence('flagged') del message['status'] del message['x-status'] elif isinstance(message, BabylMessage): flags = set(self.get_flags()) if 'R' not in flags: message.add_label('unseen') if 'D' in flags: message.add_label('deleted') if 'A' in flags: message.add_label('answered') del message['status'] del message['x-status'] elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
Copy mbox- or MMDF-specific state to message insofar as possible.
_explain_to
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add_sequence(self, sequence): """Add sequence to list of sequences including the message.""" if isinstance(sequence, str): if not sequence in self._sequences: self._sequences.append(sequence) else: raise TypeError('sequence must be a string: %s' % type(sequence))
Add sequence to list of sequences including the message.
add_sequence
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_sequence(self, sequence): """Remove sequence from the list of sequences including the message.""" try: self._sequences.remove(sequence) except ValueError: pass
Remove sequence from the list of sequences including the message.
remove_sequence
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _explain_to(self, message): """Copy MH-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('R') elif isinstance(message, _mboxMMDFMessage): sequences = set(self.get_sequences()) if 'unseen' not in sequences: message.add_flag('RO') else: message.add_flag('O') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('A') elif isinstance(message, MHMessage): for sequence in self.get_sequences(): message.add_sequence(sequence) elif isinstance(message, BabylMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.add_label('unseen') if 'replied' in sequences: message.add_label('answered') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
Copy MH-specific state to message insofar as possible.
_explain_to
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def add_label(self, label): """Add label to list of labels on the message.""" if isinstance(label, str): if label not in self._labels: self._labels.append(label) else: raise TypeError('label must be a string: %s' % type(label))
Add label to list of labels on the message.
add_label
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def remove_label(self, label): """Remove label from the list of labels on the message.""" try: self._labels.remove(label) except ValueError: pass
Remove label from the list of labels on the message.
remove_label
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def update_visible(self): """Update and/or sensibly generate a set of visible headers.""" for header in self._visible.keys(): if header in self: self._visible.replace_header(header, self[header]) else: del self._visible[header] for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'): if header in self and header not in self._visible: self._visible[header] = self[header]
Update and/or sensibly generate a set of visible headers.
update_visible
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _explain_to(self, message): """Copy Babyl-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'forwarded' in labels or 'resent' in labels: message.add_flag('P') if 'answered' in labels: message.add_flag('R') if 'deleted' in labels: message.add_flag('T') elif isinstance(message, _mboxMMDFMessage): labels = set(self.get_labels()) if 'unseen' not in labels: message.add_flag('RO') else: message.add_flag('O') if 'deleted' in labels: message.add_flag('D') if 'answered' in labels: message.add_flag('A') elif isinstance(message, MHMessage): labels = set(self.get_labels()) if 'unseen' in labels: message.add_sequence('unseen') if 'answered' in labels: message.add_sequence('replied') elif isinstance(message, BabylMessage): message.set_visible(self.get_visible()) for label in self.get_labels(): message.add_label(label) elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
Copy Babyl-specific state to message insofar as possible.
_explain_to
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def seek(self, offset, whence=0): """Change position, possibly with respect to start or stop.""" if whence == 0: self._pos = self._start whence = 1 elif whence == 2: self._pos = self._stop whence = 1 _ProxyFile.seek(self, offset, whence)
Change position, possibly with respect to start or stop.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _read(self, size, read_method): """Read size bytes using read_method, honoring start and stop.""" remaining = self._stop - self._pos if remaining <= 0: return '' if size is None or size < 0 or size > remaining: size = remaining return _ProxyFile._read(self, size, read_method)
Read size bytes using read_method, honoring start and stop.
_read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _lock_file(f, dotlock=True): """Lock file f using lockf and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError, e: if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS): raise ExternalClashError('lockf: lock unavailable: %s' % f.name) else: raise if dotlock: try: pre_lock = _create_temporary(f.name + '.lock') pre_lock.close() except IOError, e: if e.errno in (errno.EACCES, errno.EROFS): return # Without write access, just skip dotlocking. else: raise try: if hasattr(os, 'link'): os.link(pre_lock.name, f.name + '.lock') dotlock_done = True os.unlink(pre_lock.name) else: os.rename(pre_lock.name, f.name + '.lock') dotlock_done = True except OSError, e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(pre_lock.name) raise ExternalClashError('dot lock unavailable: %s' % f.name) else: raise except: if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) if dotlock_done: os.remove(f.name + '.lock') raise
Lock file f using lockf and dot locking.
_lock_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _unlock_file(f): """Unlock file f using lockf and dot locking.""" if fcntl: fcntl.lockf(f, fcntl.LOCK_UN) if os.path.exists(f.name + '.lock'): os.remove(f.name + '.lock')
Unlock file f using lockf and dot locking.
_unlock_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _create_carefully(path): """Create a file if it doesn't exist and open for reading and writing.""" fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666) try: return open(path, 'rb+') finally: os.close(fd)
Create a file if it doesn't exist and open for reading and writing.
_create_carefully
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT
def _sync_flush(f): """Ensure changes to file f are physically on disk.""" f.flush() if hasattr(os, 'fsync'): os.fsync(f.fileno())
Ensure changes to file f are physically on disk.
_sync_flush
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/mailbox.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/mailbox.py
MIT