desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Initialize an instance.
Optional argument x controls seeding, as for Random.seed().'
| def __init__(self, x=None):
| self.seed(x)
self.gauss_next = None
|
'Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.'
| def seed(self, a=None):
| if (a is None):
try:
a = long(_hexlify(_urandom(2500)), 16)
except NotImplementedError:
import time
a = long((time.time() * 256))
super(Random, self).seed(a)
self.gauss_next = None
|
'Return internal state; can be passed to setstate() later.'
| def getstate(self):
| return (self.VERSION, super(Random, self).getstate(), self.gauss_next)
|
'Restore internal state from object returned by getstate().'
| def setstate(self, state):
| version = state[0]
if (version == 3):
(version, internalstate, self.gauss_next) = state
super(Random, self).setstate(internalstate)
elif (version == 2):
(version, internalstate, self.gauss_next) = state
try:
internalstate = tuple(((long(x) % (2 ** 32)) for x in in... |
'Change the internal state to one that is likely far away
from the current state. This method will not be in Py3.x,
so it is better to simply reseed.'
| def jumpahead(self, n):
| s = (repr(n) + repr(self.getstate()))
n = int(_hashlib.new('sha512', s).hexdigest(), 16)
super(Random, self).jumpahead(n)
|
'Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.'
| def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=(1L << BPF)):
| istart = _int(start)
if (istart != start):
raise ValueError, 'non-integer arg 1 for randrange()'
if (stop is None):
if (istart > 0):
if (istart >= _maxwidth):
return self._randbelow(istart)
return _int((self.random() * istart))
rais... |
'Return random integer in range [a, b], including both end points.'
| def randint(self, a, b):
| return self.randrange(a, (b + 1))
|
'Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator.'
| def _randbelow(self, n, _log=_log, _int=int, _maxwidth=(1L << BPF), _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
| try:
getrandbits = self.getrandbits
except AttributeError:
pass
else:
if ((type(self.random) is _BuiltinMethod) or (type(getrandbits) is _Method)):
k = _int((1.00001 + _log((n - 1), 2.0)))
r = getrandbits(k)
while (r >= n):
r = getr... |
'Choose a random element from a non-empty sequence.'
| def choice(self, seq):
| return seq[int((self.random() * len(seq)))]
|
'x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.'
| def shuffle(self, x, random=None):
| if (random is None):
random = self.random
_int = int
for i in reversed(xrange(1, len(x))):
j = _int((random() * (i + 1)))
(x[i], x[j]) = (x[j], x[i])
|
'Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be par... | def sample(self, population, k):
| n = len(population)
if (not (0 <= k <= n)):
raise ValueError('sample larger than population')
random = self.random
_int = int
result = ([None] * k)
setsize = 21
if (k > 5):
setsize += (4 ** _ceil(_log((k * 3), 4)))
if ((n <= setsize) or hasattr(population, 'keys'... |
'Get a random number in the range [a, b) or [a, b] depending on rounding.'
| def uniform(self, a, b):
| return (a + ((b - a) * self.random()))
|
'Triangular distribution.
Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.
http://en.wikipedia.org/wiki/Triangular_distribution'
| def triangular(self, low=0.0, high=1.0, mode=None):
| u = self.random()
try:
c = (0.5 if (mode is None) else ((mode - low) / (high - low)))
except ZeroDivisionError:
return low
if (u > c):
u = (1.0 - u)
c = (1.0 - c)
(low, high) = (high, low)
return (low + ((high - low) * ((u * c) ** 0.5)))
|
'Normal distribution.
mu is the mean, and sigma is the standard deviation.'
| def normalvariate(self, mu, sigma):
| random = self.random
while 1:
u1 = random()
u2 = (1.0 - random())
z = ((NV_MAGICCONST * (u1 - 0.5)) / u2)
zz = ((z * z) / 4.0)
if (zz <= (- _log(u2))):
break
return (mu + (z * sigma))
|
'Log normal distribution.
If you take the natural logarithm of this distribution, you\'ll get a
normal distribution with mean mu and standard deviation sigma.
mu can have any value, and sigma must be greater than zero.'
| def lognormvariate(self, mu, sigma):
| return _exp(self.normalvariate(mu, sigma))
|
'Exponential distribution.
lambd is 1.0 divided by the desired mean. It should be
nonzero. (The parameter would be called "lambda", but that is
a reserved word in Python.) Returned values range from 0 to
positive infinity if lambd is positive, and from negative
infinity to 0 if lambd is negative.'
| def expovariate(self, lambd):
| return ((- _log((1.0 - self.random()))) / lambd)
|
'Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.'
| def vonmisesvariate(self, mu, kappa):
| random = self.random
if (kappa <= 1e-06):
return (TWOPI * random())
s = (0.5 / kappa)
r = (s + _sqrt((1.0 + (s * s))))
while 1:
u1 = random()
z = _cos((_pi * u1))
d = (z / (r + z))
u2 = random()
if ((u2 < (1.0 - (d * d))) or (u2 <= ((1.0 - d) * _exp(d)... |
'Gamma distribution. Not the gamma function!
Conditions on the parameters are alpha > 0 and beta > 0.
The probability distribution function is:
x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) = --------------------------------------
math.gamma(alpha) * beta ** alpha'
| def gammavariate(self, alpha, beta):
| if ((alpha <= 0.0) or (beta <= 0.0)):
raise ValueError, 'gammavariate: alpha and beta must be > 0.0'
random = self.random
if (alpha > 1.0):
ainv = _sqrt(((2.0 * alpha) - 1.0))
bbb = (alpha - LOG4)
ccc = (alpha + ainv)
while 1:
u1 = ran... |
'Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.
Not thread-safe without a lock around calls.'
| def gauss(self, mu, sigma):
| random = self.random
z = self.gauss_next
self.gauss_next = None
if (z is None):
x2pi = (random() * TWOPI)
g2rad = _sqrt(((-2.0) * _log((1.0 - random()))))
z = (_cos(x2pi) * g2rad)
self.gauss_next = (_sin(x2pi) * g2rad)
return (mu + (z * sigma))
|
'Beta distribution.
Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.'
| def betavariate(self, alpha, beta):
| y = self.gammavariate(alpha, 1.0)
if (y == 0):
return 0.0
else:
return (y / (y + self.gammavariate(beta, 1.0)))
|
'Pareto distribution. alpha is the shape parameter.'
| def paretovariate(self, alpha):
| u = (1.0 - self.random())
return (1.0 / pow(u, (1.0 / alpha)))
|
'Weibull distribution.
alpha is the scale parameter and beta is the shape parameter.'
| def weibullvariate(self, alpha, beta):
| u = (1.0 - self.random())
return (alpha * pow((- _log(u)), (1.0 / beta)))
|
'Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclus... | def seed(self, a=None):
| if (a is None):
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long((time.time() * 256))
if (not isinstance(a, (int, long))):
a = hash(a)
(a, x) = divmod(a, 30268)
(a, y) = divmod(a, 30306)
(a, z) = di... |
'Get the next random number in the range [0.0, 1.0).'
| def random(self):
| (x, y, z) = self._seed
x = ((171 * x) % 30269)
y = ((172 * y) % 30307)
z = ((170 * z) % 30323)
self._seed = (x, y, z)
return ((((x / 30269.0) + (y / 30307.0)) + (z / 30323.0)) % 1.0)
|
'Return internal state; can be passed to setstate() later.'
| def getstate(self):
| return (self.VERSION, self._seed, self.gauss_next)
|
'Restore internal state from object returned by getstate().'
| def setstate(self, state):
| version = state[0]
if (version == 1):
(version, self._seed, self.gauss_next) = state
else:
raise ValueError(('state with version %s passed to Random.setstate() of version %s' % (version, self.VERSION)))
|
'Act as if n calls to random() were made, but quickly.
n is an int, greater than or equal to 0.
Example use: If you have 2 threads and know that each will
consume no more than a million random numbers, create two Random
objects r1 and r2, then do
r2.setstate(r1.getstate())
r2.jumpahead(1000000)
Then r1 and r2 will use... | def jumpahead(self, n):
| if (not (n >= 0)):
raise ValueError('n must be >= 0')
(x, y, z) = self._seed
x = (int((x * pow(171, n, 30269))) % 30269)
y = (int((y * pow(172, n, 30307))) % 30307)
z = (int((z * pow(170, n, 30323))) % 30323)
self._seed = (x, y, z)
|
'Set the Wichmann-Hill seed from (x, y, z).
These must be integers in the range [0, 256).'
| def __whseed(self, x=0, y=0, z=0):
| if (not (type(x) == type(y) == type(z) == int)):
raise TypeError('seeds must be integers')
if (not ((0 <= x < 256) and (0 <= y < 256) and (0 <= z < 256))):
raise ValueError('seeds must be in range(0, 256)')
if (0 == x == y == z):
import time
t = long((... |
'Seed from hashable object\'s hash code.
None or no argument seeds from current time. It is not guaranteed
that objects with distinct hash codes lead to distinct internal
states.
This is obsolete, provided for compatibility with the seed routine
used prior to Python 2.1. Use the .seed() method instead.'
| def whseed(self, a=None):
| if (a is None):
self.__whseed()
return
a = hash(a)
(a, x) = divmod(a, 256)
(a, y) = divmod(a, 256)
(a, z) = divmod(a, 256)
x = (((x + a) % 256) or 1)
y = (((y + a) % 256) or 1)
z = (((z + a) % 256) or 1)
self.__whseed(x, y, z)
|
'Get the next random number in the range [0.0, 1.0).'
| def random(self):
| return ((long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF)
|
'getrandbits(k) -> x. Generates a long int with k random bits.'
| def getrandbits(self, k):
| if (k <= 0):
raise ValueError('number of bits must be greater than zero')
if (k != int(k)):
raise TypeError('number of bits should be an integer')
bytes = ((k + 7) // 8)
x = long(_hexlify(_urandom(bytes)), 16)
return (x >> ((bytes * 8) - k))
|
'Stub method. Not used for a system random number generator.'
| def _stub(self, *args, **kwds):
| return None
|
'Method should not be called for a system random number generator.'
| def _notimplemented(self, *args, **kwds):
| raise NotImplementedError('System entropy source does not have state.')
|
'This method is called when there is the remote possibility
that we ever need to stop in this function.'
| def user_call(self, frame, argument_list):
| if self._wait_for_mainpyfile:
return
if self.stop_here(frame):
print >>self.stdout, '--Call--'
self.interaction(frame, None)
|
'This function is called when we stop or break at this line.'
| def user_line(self, frame):
| if self._wait_for_mainpyfile:
if ((self.mainpyfile != self.canonic(frame.f_code.co_filename)) or (frame.f_lineno <= 0)):
return
self._wait_for_mainpyfile = 0
if self.bp_commands(frame):
self.interaction(frame, None)
|
'Call every command that was set for the current active breakpoint
(if there is one).
Returns True if the normal interaction function must be called,
False otherwise.'
| def bp_commands(self, frame):
| if (getattr(self, 'currentbp', False) and (self.currentbp in self.commands)):
currentbp = self.currentbp
self.currentbp = 0
lastcmd_back = self.lastcmd
self.setup(frame, None)
for line in self.commands[currentbp]:
self.onecmd(line)
self.lastcmd = lastcmd_b... |
'This function is called when a return trap is set here.'
| def user_return(self, frame, return_value):
| if self._wait_for_mainpyfile:
return
frame.f_locals['__return__'] = return_value
print >>self.stdout, '--Return--'
self.interaction(frame, None)
|
'This function is called if an exception occurs,
but only if we are to stop at or just below this level.'
| def user_exception(self, frame, exc_info):
| if self._wait_for_mainpyfile:
return
(exc_type, exc_value, exc_traceback) = exc_info
frame.f_locals['__exception__'] = (exc_type, exc_value)
if (type(exc_type) == type('')):
exc_type_name = exc_type
else:
exc_type_name = exc_type.__name__
print >>self.stdout, (exc_type_na... |
'Custom displayhook for the exec in default(), which prevents
assignment of the _ variable in the builtins.'
| def displayhook(self, obj):
| if (obj is not None):
print repr(obj)
|
'Handle alias expansion and \';;\' separator.'
| def precmd(self, line):
| if (not line.strip()):
return line
args = line.split()
while (args[0] in self.aliases):
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = line.replace(('%' + str(ii)), tmpArg)
ii = (ii + 1)
line = line.replace('%*', ' '.join... |
'Interpret the argument as though it had been typed in response
to the prompt.
Checks whether this line is typed at the normal prompt or in
a breakpoint command list definition.'
| def onecmd(self, line):
| if (not self.commands_defining):
return cmd.Cmd.onecmd(self, line)
else:
return self.handle_command_def(line)
|
'Handles one command line during command list definition.'
| def handle_command_def(self, line):
| (cmd, arg, line) = self.parseline(line)
if (not cmd):
return
if (cmd == 'silent'):
self.commands_silent[self.commands_bnum] = True
return
elif (cmd == 'end'):
self.cmdqueue = []
return 1
cmdlist = self.commands[self.commands_bnum]
if arg:
cmdlist.a... |
'Defines a list of commands associated to a breakpoint.
Those commands will be executed whenever the breakpoint causes
the program to stop execution.'
| def do_commands(self, arg):
| if (not arg):
bnum = (len(bdb.Breakpoint.bpbynumber) - 1)
else:
try:
bnum = int(arg)
except:
print >>self.stdout, 'Usage : commands [bnum]\n ...\n end'
return
self.commands_bnum... |
'Produce a reasonable default.'
| def defaultFile(self):
| filename = self.curframe.f_code.co_filename
if ((filename == '<string>') and self.mainpyfile):
filename = self.mainpyfile
return filename
|
'Check whether specified line seems to be executable.
Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
line or EOF). Warning: testing is not comprehensive.'
| def checkline(self, filename, lineno):
| globs = (self.curframe.f_globals if hasattr(self, 'curframe') else None)
line = linecache.getline(filename, lineno, globs)
if (not line):
print >>self.stdout, 'End of file'
return 0
line = line.strip()
if ((not line) or (line[0] == '#') or (line[:3] == '"""') or (line[:3] == "'... |
'arg is bp number followed by ignore count.'
| def do_ignore(self, arg):
| args = arg.split()
try:
bpnum = int(args[0].strip())
except ValueError:
print >>self.stdout, ('Breakpoint index %r is not a number' % args[0])
return
try:
count = int(args[1].strip())
except:
count = 0
try:
bp = bdb.Breakpoint.bpb... |
'Three possibilities, tried in this order:
clear -> clear all breaks, ask for confirmation
clear file:lineno -> clear all breaks at file:lineno
clear bpno bpno ... -> clear breakpoints by number'
| def do_clear(self, arg):
| if (not arg):
try:
reply = raw_input('Clear all breaks? ')
except EOFError:
reply = 'no'
reply = reply.strip().lower()
if (reply in ('y', 'yes')):
self.clear_all_breaks()
return
if (':' in arg):
i = arg.rfind(':')
... |
'Restart program by raising an exception to be caught in the main
debugger loop. If arguments were given, set them in sys.argv.'
| def do_run(self, arg):
| if arg:
import shlex
argv0 = sys.argv[0:1]
sys.argv = shlex.split(arg)
sys.argv[:0] = argv0
raise Restart
|
'Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name.'
| def lookupmodule(self, filename):
| if (os.path.isabs(filename) and os.path.exists(filename)):
return filename
f = os.path.join(sys.path[0], filename)
if (os.path.exists(f) and (self.canonic(f) == self.mainpyfile)):
return f
(root, ext) = os.path.splitext(filename)
if (ext == ''):
filename = (filename + '.py')
... |
'Install this ImportManager into the specified namespace.'
| def install(self, namespace=vars(__builtin__)):
| if isinstance(namespace, _ModuleType):
namespace = vars(namespace)
self.previous_importer = namespace['__import__']
self.namespace = namespace
namespace['__import__'] = self._import_hook
|
'Restore the previous import mechanism.'
| def uninstall(self):
| self.namespace['__import__'] = self.previous_importer
|
'Python calls this hook to locate and import a module.'
| def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
| parts = fqname.split('.')
parent = self._determine_import_context(globals)
if parent:
module = parent.__importer__._do_import(parent, parts, fromlist)
if module:
return module
try:
top_module = sys.modules[parts[0]]
except KeyError:
top_module = self._impo... |
'Returns the context in which a module should be imported.
The context could be a loaded (package) module and the imported module
will be looked for within that package. The context could also be None,
meaning there is no context -- the module should be looked for as a
"top-level" module.'
| def _determine_import_context(self, globals):
| if ((not globals) or (not globals.get('__importer__'))):
return None
parent_fqname = globals['__name__']
if globals['__ispkg__']:
parent = sys.modules[parent_fqname]
assert (globals is parent.__dict__)
return parent
i = parent_fqname.rfind('.')
if (i == (-1)):
... |
'Python calls this hook to reload a module.'
| def _reload_hook(self, module):
| importer = module.__dict__.get('__importer__')
if (not importer):
pass
raise SystemError, 'reload not yet implemented'
|
'Import a top-level module.'
| def import_top(self, name):
| return self._import_one(None, name, name)
|
'Import a single module.'
| def _import_one(self, parent, modname, fqname):
| try:
return sys.modules[fqname]
except KeyError:
pass
result = self.get_code(parent, modname, fqname)
if (result is None):
return None
module = self._process_result(result, fqname)
if parent:
setattr(parent, modname, module)
return module
|
'Import the rest of the modules, down from the top-level module.
Returns the last module in the dotted list of modules.'
| def _load_tail(self, m, parts):
| for part in parts:
fqname = ('%s.%s' % (m.__name__, part))
m = self._import_one(m, part, fqname)
if (not m):
raise ImportError, ('No module named ' + fqname)
return m
|
'Import any sub-modules in the "from" list.'
| def _import_fromlist(self, package, fromlist):
| if ('*' in fromlist):
fromlist = (list(fromlist) + list(package.__dict__.get('__all__', [])))
for sub in fromlist:
if ((sub != '*') and (not hasattr(package, sub))):
subname = ('%s.%s' % (package.__name__, sub))
submod = self._import_one(package, sub, subname)
... |
'Attempt to import the module relative to parent.
This method is used when the import context specifies that <self>
imported the parent module.'
| def _do_import(self, parent, parts, fromlist):
| top_name = parts[0]
top_fqname = ((parent.__name__ + '.') + top_name)
top_module = self._import_one(parent, top_name, top_fqname)
if (not top_module):
return None
return self._finish_import(top_module, parts[1:], fromlist)
|
'Find and retrieve the code for the given module.
parent specifies a parent module to define a context for importing. It
may be None, indicating no particular context for the search.
modname specifies a single module (not dotted) within the parent.
fqname specifies the fully-qualified module name. This is a
(potentiall... | def get_code(self, parent, modname, fqname):
| raise RuntimeError, 'get_code not implemented'
|
'Compile a command and determine whether it is incomplete.
Arguments:
source -- the source string; may contain \n characters
filename -- optional filename from which source was read;
default "<input>"
symbol -- optional grammar start symbol; "single" (default) or
"eval"
Return value / exceptions raised:
- Return a code... | def __call__(self, source, filename='<input>', symbol='single'):
| return _maybe_compile(self.compiler, source, filename, symbol)
|
'Write the profile data to a file we know how to load back.'
| def dump_stats(self, filename):
| f = file(filename, 'wb')
try:
marshal.dump(self.stats, f)
finally:
f.close()
|
'Expand all abbreviations that are unique.'
| def get_sort_arg_defs(self):
| if (not self.sort_arg_dict):
self.sort_arg_dict = dict = {}
bad_list = {}
for (word, tup) in self.sort_arg_dict_default.iteritems():
fragment = word
while fragment:
if (not fragment):
break
if (fragment in dict):
... |
'Initialize a new instance.
If specified, `host\' is the name of the remote host to which to
connect. If specified, `port\' specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used. If a host is specified the
connect method is called, and if it returns anything other than a
success code an SMTPCo... | def __init__(self, host='', port=0, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
| self.timeout = timeout
self.esmtp_features = {}
if host:
(code, msg) = self.connect(host, port)
if (code != 220):
raise SMTPConnectError(code, msg)
if (local_hostname is not None):
self.local_hostname = local_hostname
else:
fqdn = socket.getfqdn()
... |
'Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server.'
| def set_debuglevel(self, debuglevel):
| self.debuglevel = debuglevel
|
'Connect to a host on a given port.
If the hostname ends with a colon (`:\') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.
Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.'
| def connect(self, host='localhost', port=0):
| if ((not port) and (host.find(':') == host.rfind(':'))):
i = host.rfind(':')
if (i >= 0):
(host, port) = (host[:i], host[(i + 1):])
try:
port = int(port)
except ValueError:
raise socket.error, 'nonnumeric port'
if (not port):... |
'Send `str\' to the server.'
| def send(self, str):
| if (self.debuglevel > 0):
print >>stderr, 'send:', repr(str)
if (hasattr(self, 'sock') and self.sock):
try:
self.sock.sendall(str)
except socket.error:
self.close()
raise SMTPServerDisconnected('Server not connected')
else:
raise SMTP... |
'Send a command to the server.'
| def putcmd(self, cmd, args=''):
| if (args == ''):
str = ('%s%s' % (cmd, CRLF))
else:
str = ('%s %s%s' % (cmd, args, CRLF))
self.send(str)
|
'Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. \'250\', or such, if all goes well)
Note: returns -1 if it can\'t read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisc... | def getreply(self):
| resp = []
if (self.file is None):
self.file = self.sock.makefile('rb')
while 1:
try:
line = self.file.readline((_MAXLINE + 1))
except socket.error as e:
self.close()
raise SMTPServerDisconnected(('Connection unexpectedly closed: ' + str(e)... |
'Send a command, and return its response code.'
| def docmd(self, cmd, args=''):
| self.putcmd(cmd, args)
return self.getreply()
|
'SMTP \'helo\' command.
Hostname to send for this command defaults to the FQDN of the local
host.'
| def helo(self, name=''):
| self.putcmd('helo', (name or self.local_hostname))
(code, msg) = self.getreply()
self.helo_resp = msg
return (code, msg)
|
'SMTP \'ehlo\' command.
Hostname to send for this command defaults to the FQDN of the local
host.'
| def ehlo(self, name=''):
| self.esmtp_features = {}
self.putcmd(self.ehlo_msg, (name or self.local_hostname))
(code, msg) = self.getreply()
if ((code == (-1)) and (len(msg) == 0)):
self.close()
raise SMTPServerDisconnected('Server not connected')
self.ehlo_resp = msg
if (code != 250):
return ... |
'Does the server support a given SMTP service extension?'
| def has_extn(self, opt):
| return (opt.lower() in self.esmtp_features)
|
'SMTP \'help\' command.
Returns help text from server.'
| def help(self, args=''):
| self.putcmd('help', args)
return self.getreply()[1]
|
'SMTP \'rset\' command -- resets session.'
| def rset(self):
| return self.docmd('rset')
|
'SMTP \'noop\' command -- doesn\'t do anything :>'
| def noop(self):
| return self.docmd('noop')
|
'SMTP \'mail\' command -- begins mail xfer session.'
| def mail(self, sender, options=[]):
| optionlist = ''
if (options and self.does_esmtp):
optionlist = (' ' + ' '.join(options))
self.putcmd('mail', ('FROM:%s%s' % (quoteaddr(sender), optionlist)))
return self.getreply()
|
'SMTP \'rcpt\' command -- indicates 1 recipient for this mail.'
| def rcpt(self, recip, options=[]):
| optionlist = ''
if (options and self.does_esmtp):
optionlist = (' ' + ' '.join(options))
self.putcmd('rcpt', ('TO:%s%s' % (quoteaddr(recip), optionlist)))
return self.getreply()
|
'SMTP \'DATA\' command -- sends message data to server.
Automatically quotes lines beginning with a period per rfc821.
Raises SMTPDataError if there is an unexpected reply to the
DATA command; the return value from this method is the final
response code received when the all data is sent.'
| def data(self, msg):
| self.putcmd('data')
(code, repl) = self.getreply()
if (self.debuglevel > 0):
print >>stderr, 'data:', (code, repl)
if (code != 354):
raise SMTPDataError(code, repl)
else:
q = quotedata(msg)
if (q[(-2):] != CRLF):
q = (q + CRLF)
q = ((q + '.') + CRL... |
'SMTP \'verify\' command -- checks for address validity.'
| def verify(self, address):
| self.putcmd('vrfy', _addr_only(address))
return self.getreply()
|
'SMTP \'expn\' command -- expands a mailing list.'
| def expn(self, address):
| self.putcmd('expn', _addr_only(address))
return self.getreply()
|
'Call self.ehlo() and/or self.helo() if needed.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method may raise the following exceptions:
SMTPHeloError The server didn\'t reply properly to
the helo greeting.'
| def ehlo_or_helo_if_needed(self):
| if ((self.helo_resp is None) and (self.ehlo_resp is None)):
if (not (200 <= self.ehlo()[0] <= 299)):
(code, resp) = self.helo()
if (not (200 <= code <= 299)):
raise SMTPHeloError(code, resp)
|
'Log in on an SMTP server that requires authentication.
The arguments are:
- user: The user name to authenticate with.
- password: The password for the authentication.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method will return normally if the authent... | def login(self, user, password):
| def encode_cram_md5(challenge, user, password):
challenge = base64.decodestring(challenge)
response = ((user + ' ') + hmac.HMAC(password, challenge).hexdigest())
return encode_base64(response, eol='')
def encode_plain(user, password):
return encode_base64(('\x00%s\x00%s' % (us... |
'Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and ... | def starttls(self, keyfile=None, certfile=None):
| self.ehlo_or_helo_if_needed()
if (not self.has_extn('starttls')):
raise SMTPException('STARTTLS extension not supported by server.')
(resp, reply) = self.docmd('STARTTLS')
if (resp == 220):
if (not _have_ssl):
raise RuntimeError('No SSL support include... |
'This command performs an entire mail transaction.
The arguments are:
- from_addr : The address sending this mail.
- to_addrs : A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
- msg : The message to send.
- mail_options : List of ESMTP options (such as ... | def sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]):
| self.ehlo_or_helo_if_needed()
esmtp_opts = []
if self.does_esmtp:
if self.has_extn('size'):
esmtp_opts.append(('size=%d' % len(msg)))
for option in mail_options:
esmtp_opts.append(option)
(code, resp) = self.mail(from_addr, esmtp_opts)
if (code != 250):
... |
'Close the connection to the SMTP server.'
| def close(self):
| try:
file = self.file
self.file = None
if file:
file.close()
finally:
sock = self.sock
self.sock = None
if sock:
sock.close()
|
'Terminate the SMTP session.'
| def quit(self):
| res = self.docmd('quit')
self.ehlo_resp = self.helo_resp = None
self.esmtp_features = {}
self.does_esmtp = False
self.close()
return res
|
'Initialize a new instance.'
| def __init__(self, host='', port=LMTP_PORT, local_hostname=None):
| SMTP.__init__(self, host, port, local_hostname)
|
'Connect to the LMTP daemon, on either a Unix or a TCP socket.'
| def connect(self, host='localhost', port=0):
| if (host[0] != '/'):
return SMTP.connect(self, host, port)
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(host)
except socket.error:
if (self.debuglevel > 0):
print >>stderr, 'connect fail:', host
if self.sock:
... |
'Initialize an instance. Arguments:
- host: hostname to connect to
- port: port to connect to (default the standard NNTP port)
- user: username to authenticate with
- password: password to use with username
- readermode: if true, send \'mode reader\' command after
connecting.
readermode is sometimes necessary if you a... | def __init__(self, host, port=NNTP_PORT, user=None, password=None, readermode=None, usenetrc=True):
| self.host = host
self.port = port
self.sock = socket.create_connection((host, port))
self.file = self.sock.makefile('rb')
self.debugging = 0
self.welcome = self.getresp()
readermode_afterauth = 0
if readermode:
try:
self.welcome = self.shortcmd('mode reader')
... |
'Get the welcome message from the server
(this is read and squirreled away by __init__()).
If the response code is 200, posting is allowed;
if it 201, posting is not allowed.'
| def getwelcome(self):
| if self.debugging:
print '*welcome*', repr(self.welcome)
return self.welcome
|
'Set the debugging level. Argument \'level\' means:
0: no debugging output (default)
1: print commands and responses but not body text etc.
2: also print raw lines read and sent before stripping CR/LF'
| def set_debuglevel(self, level):
| self.debugging = level
|
'Internal: send one line to the server, appending CRLF.'
| def putline(self, line):
| line = (line + CRLF)
if (self.debugging > 1):
print '*put*', repr(line)
self.sock.sendall(line)
|
'Internal: send one command to the server (through putline()).'
| def putcmd(self, line):
| if self.debugging:
print '*cmd*', repr(line)
self.putline(line)
|
'Internal: return one line from the server, stripping CRLF.
Raise EOFError if the connection is closed.'
| def getline(self):
| line = self.file.readline((_MAXLINE + 1))
if (len(line) > _MAXLINE):
raise NNTPDataError('line too long')
if (self.debugging > 1):
print '*get*', repr(line)
if (not line):
raise EOFError
if (line[(-2):] == CRLF):
line = line[:(-2)]
elif (line[(-1):] in CRLF)... |
'Internal: get a response from the server.
Raise various errors if the response indicates an error.'
| def getresp(self):
| resp = self.getline()
if self.debugging:
print '*resp*', repr(resp)
c = resp[:1]
if (c == '4'):
raise NNTPTemporaryError(resp)
if (c == '5'):
raise NNTPPermanentError(resp)
if (c not in '123'):
raise NNTPProtocolError(resp)
return resp
|
'Internal: get a response plus following text from the server.
Raise various errors if the response indicates an error.'
| def getlongresp(self, file=None):
| openedFile = None
try:
if isinstance(file, str):
openedFile = file = open(file, 'w')
resp = self.getresp()
if (resp[:3] not in LONGRESP):
raise NNTPReplyError(resp)
list = []
while 1:
line = self.getline()
if (line == '.'):
... |
'Internal: send a command and get the response.'
| def shortcmd(self, line):
| self.putcmd(line)
return self.getresp()
|
'Internal: send a command and get the response plus following text.'
| def longcmd(self, line, file=None):
| self.putcmd(line)
return self.getlongresp(file)
|
'Process a NEWGROUPS command. Arguments:
- date: string \'yymmdd\' indicating the date
- time: string \'hhmmss\' indicating the time
Return:
- resp: server response if successful
- list: list of newsgroup names'
| def newgroups(self, date, time, file=None):
| return self.longcmd(((('NEWGROUPS ' + date) + ' ') + time), file)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.