rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
Py_DECREF(numpy);
#ifdef NPY_ENABLE_SEPARATE_COMPILATION
return tuple(x/dim_prod % dims)
return tuple(x//dim_prod % dims)
def unravel_index(x,dims): """ Convert a flat index to an index tuple for an array of given shape. Parameters ---------- x : int Flattened index. dims : tuple of ints Input shape, the shape of an array into which indexing is required. Returns ------- idx : tuple of ints Tuple of the same shape as `dims`, containing t...
dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64),
dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'),
def test_roundtrip(self): x = np.array([1,2,3,4,5], dtype='i4') self._check_roundtrip(x)
x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
def test_roundtrip(self): x = np.array([1,2,3,4,5], dtype='i4') self._check_roundtrip(x)
x = np.array([1,2,3,4,5], dtype='i4')
x = np.array([1,2,3,4,5], dtype='i')
def test_export_simple_1d(self): x = np.array([1,2,3,4,5], dtype='i4') y = memoryview(x) assert_equal(y.format, '=l') assert_equal(y.shape, (5,)) assert_equal(y.ndim, 1) assert_equal(y.strides, (4,)) assert_equal(y.suboffsets, None) assert_equal(y.itemsize, 4)
assert_equal(y.format, '=l')
assert_equal(y.format, '=i')
def test_export_simple_1d(self): x = np.array([1,2,3,4,5], dtype='i4') y = memoryview(x) assert_equal(y.format, '=l') assert_equal(y.shape, (5,)) assert_equal(y.ndim, 1) assert_equal(y.strides, (4,)) assert_equal(y.suboffsets, None) assert_equal(y.itemsize, 4)
dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64),
dt = [('a', 'b'), ('b', 'h'), ('c', 'i'), ('d', 'l'), ('dx', 'q'), ('e', 'B'), ('f', 'H'), ('g', 'I'), ('h', 'L'), ('hx', 'Q'),
def test_export_record(self): dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64), ('i', np.float), ('j', np.double), ('k', np.longdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?')] x = np.array([(1, 1, 1, 1, 1, 1, 1, 1,...
x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
x = np.array([(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
def test_export_record(self): dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64), ('i', np.float), ('j', np.double), ('k', np.longdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?')] x = np.array([(1, 1, 1, 1, 1, 1, 1, 1,...
assert_equal(y.format, 'T{b:a:=h:b:=l:c:=q:d:B:e:=H:f:=L:g:=Q:h:=d:i:=d:j:=g:k:4s:l:=4w:m:3x:n:?:o:}')
assert_equal(y.format, 'T{b:a:=h:b:=i:c:=l:d:=q:dx:B:e:=H:f:=I:g:=L:h:=Q:hx:=d:i:=d:j:=g:k:4s:l:=4w:m:3x:n:?:o:}')
def test_export_record(self): dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64), ('i', np.float), ('j', np.double), ('k', np.longdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?')] x = np.array([(1, 1, 1, 1, 1, 1, 1, 1,...
assert_equal(y.strides, (82,))
def test_export_record(self): dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64), ('i', np.float), ('j', np.double), ('k', np.longdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?')] x = np.array([(1, 1, 1, 1, 1, 1, 1, 1,...
assert_equal(y.itemsize, 82)
if dtype('l').itemsize == 4: assert_equal(y.strides, (90,)) assert_equal(y.itemsize, 90) else: assert_equal(y.strides, (102,)) assert_equal(y.itemsize, 102)
def test_export_record(self): dt = [('a', np.int8), ('b', np.int16), ('c', np.int32), ('d', np.int64), ('e', np.uint8), ('f', np.uint16), ('g', np.uint32), ('h', np.uint64), ('i', np.float), ('j', np.double), ('k', np.longdouble), ('l', 'S4'), ('m', 'U4'), ('n', 'V3'), ('o', '?')] x = np.array([(1, 1, 1, 1, 1, 1, 1, 1,...
x = np.array(([[1,2],[3,4]],), dtype=[('a', (int, (2,2)))])
x = np.array(([[1,2],[3,4]],), dtype=[('a', ('i', (2,2)))])
def test_export_subarray(self): x = np.array(([[1,2],[3,4]],), dtype=[('a', (int, (2,2)))]) y = memoryview(x) assert_equal(y.format, 'T{(2,2)=l:a:}') assert_equal(y.shape, None) assert_equal(y.ndim, 0) assert_equal(y.strides, None) assert_equal(y.suboffsets, None) assert_equal(y.itemsize, 16)
assert_equal(y.format, 'T{(2,2)=l:a:}')
assert_equal(y.format, 'T{(2,2)=i:a:}')
def test_export_subarray(self): x = np.array(([[1,2],[3,4]],), dtype=[('a', (int, (2,2)))]) y = memoryview(x) assert_equal(y.format, 'T{(2,2)=l:a:}') assert_equal(y.shape, None) assert_equal(y.ndim, 0) assert_equal(y.strides, None) assert_equal(y.suboffsets, None) assert_equal(y.itemsize, 16)
x = np.array([1,2,3], dtype='>i4')
x = np.array([1,2,3], dtype='>l')
def test_export_endian(self): x = np.array([1,2,3], dtype='>i4') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, '>l') else: assert_equal(y.format, '=l')
x = np.array([1,2,3], dtype='<i4')
x = np.array([1,2,3], dtype='<l')
def test_export_endian(self): x = np.array([1,2,3], dtype='>i4') y = memoryview(x) if sys.byteorder == 'little': assert_equal(y.format, '>l') else: assert_equal(y.format, '=l')
if not np.issubdtype(y.dtype, np.integer): np.putmask(y, mask, fill)
np.putmask(y, mask, fill)
def _nanop(op, fill, a, axis=None): """ General operation on arrays with not-a-number values. Parameters ---------- op : callable Operation to perform. fill : float NaN values are set to fill before doing the operation. a : array-like Input array. axis : {int, None}, optional Axis along which the operation is computed...
def test_tril_indices():
def test_tril_indices(self):
def test_tril_indices(): # indices without and with offset il1 = tril_indices(4) il2 = tril_indices(4, 2)
def test_triu_indices():
def test_triu_indices(self):
def test_triu_indices(): iu1 = triu_indices(4) iu2 = triu_indices(4, 2)
if m < 0: raise ValueError, "Order of derivative must be positive (see polyint)"
def polyder(p, m=1): """ Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ------- der : poly1d A ne...
return p
val = p
def polyder(p, m=1): """ Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ------- der : poly1d A ne...
'mtrand', '_dotblas']:
'mtrand', '_dotblas', 'version']:
def custom_mangling(filename): import_mangling = [ os.path.join('core', '__init__.py'), os.path.join('core', 'numeric.py'), os.path.join('core', '_internal.py'), os.path.join('core', 'arrayprint.py'), os.path.join('core', 'fromnumeric.py'), os.path.join('numpy', '__init__.py'), os.path.join('lib', 'npyio.py'), os.path....
sections[rname][oname] += ' %s' % ovalue
if ovalue: sections[rname][oname] += ' %s' % ovalue
def _read_config(f): meta, vars, sections, reqs = parse_config(f, dirs) # recursively add sections and variables of required libraries for rname, rvalue in reqs.items(): nmeta, nvars, nsections, nreqs = _read_config(pkg_to_filename(rvalue))
>>> bagobj = np.lib.io.BagObj(demo_obj)
>>> bagobj = np.lib.npyio.BagObj(demo_obj)
... def __getitem__(self, key):
>>> isinstance(npz, np.lib.io.NpzFile)
>>> isinstance(npz, np.lib.npyio.NpzFile)
def __getattribute__(self, key): try: return object.__getattribute__(self, '_obj')[key] except KeyError: raise AttributeError, key
self.filename = filename.name
self.filename = os.path.abspath(filename.name)
def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0, shape=None, order='C'): # Import here to minimize 'import numpy' overhead import mmap import os.path try: mode = mode_equivalents[mode] except KeyError: if mode not in valid_filemodes: raise ValueError("mode must be one of %s" % \ (valid_filemodes + mode_...
elif not hasattr(dtypes, '__iter__'): dtypes = [dtypes, ]
else : if not hasattr(dtypes, '__iter__'): dtypes = [dtypes, ]
def append_fields(base, names, data=None, dtypes=None, fill_value= -1, usemask=True, asrecarray=False): """ Add new fields to an existing array. The names of the fields are given with the `names` arguments, the corresponding values with the `data` arguments. If a single field is appended, `names`, `data` and `dtypes` ...
GIT_REVISION = out.strip()
GIT_REVISION = out.strip().decode('ascii')
def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0] ...
line = line.split(comments)[0].strip()
line = asbytes(line).split(comments)[0].strip()
def split_line(line): """Chop off comments, strip, and split at delimiter.""" line = line.split(comments)[0].strip() if line: return line.split(delimiter) else: return []
UPPER_TABLE = string.maketrans(bytes(string.ascii_lowercase, "ascii"),
UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"),
def __init__(self, nin, nout, identity, docstring, *type_descriptions): self.nin = nin self.nout = nout if identity is None: identity = None_ self.identity = identity self.docstring = docstring self.type_descriptions = [] for td in type_descriptions: self.type_descriptions.extend(td) for td in self.type_descriptions: t...
elif callable(item):
elif hasattr(item, "__call__"):
def _lookfor_generate_cache(module, import_modules, regenerate): """ Generate docstring cache for given module. Parameters ---------- module : str, None, module Module for which to generate docstring cache import_modules : bool Whether to import sub-modules in packages. regenerate: bool Re-generate the docstring cache...
if filename.endswith(os.path.join('lib', 'npyio.py')): f = open(filename, 'r') text = f.read() f.close() text = text.replace('from . import io', 'import io') f = open(filename, 'w') f.write(text) f.close()
def custom_mangling(filename): import_mangling = [ os.path.join('core', '__init__.py'), os.path.join('core', 'numeric.py'), os.path.join('core', '_internal.py'), os.path.join('core', 'arrayprint.py'), os.path.join('core', 'fromnumeric.py'), os.path.join('numpy', '__init__.py'), os.path.join('lib', 'npyio.py'), os.path....
argv += ['--exclude','array_from_pyobj']
def prepare_test_args(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False): """ Run tests for module using nose.
modes = numpy.geterr()
modes = np.geterr()
def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = numpy.geterr() if errorStatus & numpy.FPE_INVALID: if modes['invalid'] == "warn": print "Warning: Encountered invalid numeric result(s)", sourcemsg if modes['invalid'] == "raise": raise MathDomainError(sourcemsg) i...
long('0x' + 'f'*i_width,16) assert_equal(255,np.long('0xFF',16)) assert_equal(1024,np.long(1024))
np.intp('0x' + 'f'*i_width,16) self.failUnlessRaises(OverflowError,np.intp,'0x' + 'f'*(i_width+1),16) self.failUnlessRaises(ValueError,np.intp,'0x1',32) assert_equal(255,np.intp('0xFF',16)) assert_equal(1024,np.intp(1024))
def test_intp(self,level=rlevel): """Ticket #99""" i_width = np.int_(0).nbytes*2 - 1 long('0x' + 'f'*i_width,16) #self.failUnlessRaises(OverflowError,np.intp,'0x' + 'f'*(i_width+1),16) #self.failUnlessRaises(ValueError,np.intp,'0x1',32) assert_equal(255,np.long('0xFF',16)) assert_equal(1024,np.long(1024))
z = f(np.array(np.complex(-np.inf, np.inf))) if z.real != 0 or z.imag != 0: raise AssertionError( "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)" \ % (z.real, z.imag))
msgform = "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)" err = np.seterr(invalid='ignore') try: z = f(np.array(np.complex(-np.inf, np.inf))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform %(z.real, z.imag)) finally: np.seterr(**err)
def _check_ninf_inf(dummy): z = f(np.array(np.complex(-np.inf, np.inf))) if z.real != 0 or z.imag != 0: raise AssertionError( "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)" \ % (z.real, z.imag))
z = f(np.array(np.complex(np.inf, np.inf))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError( "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)" \ % (z.real, z.imag))
msgform = "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)" err = np.seterr(invalid='ignore') try: z = f(np.array(np.complex(np.inf, np.inf))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) finally: np.seterr(**err)
def _check_inf_inf(dummy): z = f(np.array(np.complex(np.inf, np.inf))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError( "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)" \ % (z.real, z.imag))
z = f(np.array(np.complex(-np.inf, np.nan))) if z.real != 0 or z.imag != 0: raise AssertionError( "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)" \ % (z.real, z.imag))
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)" err = np.seterr(invalid='ignore') try: z = f(np.array(np.complex(-np.inf, np.nan))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform % (z.real, z.imag)) finally: np.seterr(**err)
def _check_ninf_nan(dummy): z = f(np.array(np.complex(-np.inf, np.nan))) if z.real != 0 or z.imag != 0: raise AssertionError( "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)" \ % (z.real, z.imag))
z = f(np.array(np.complex(np.inf, np.nan))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError( "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)" \ % (z.real, z.imag))
msgform = "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)" err = np.seterr(invalid='ignore') try: z = f(np.array(np.complex(np.inf, np.nan))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) finally: np.seterr(**err)
def _check_inf_nan(dummy): z = f(np.array(np.complex(np.inf, np.nan))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError( "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)" \ % (z.real, z.imag))
x = np.array([np.NZERO], dtype=np.complex) y = np.complex(-np.inf, np.pi) assert_almost_equal(np.log(x), y)
err = np.seterr(divide='raise') try: x = np.array([np.NZERO], dtype=np.complex) y = np.complex(-np.inf, np.pi) self.assertRaises(FloatingPointError, np.log, x) np.seterr(divide='ignore') assert_almost_equal(np.log(x), y) finally: np.seterr(**err)
def test_special_values(self): xl = [] yl = []
x = np.array([0], dtype=np.complex) y = np.complex(-np.inf, 0) assert_almost_equal(np.log(x), y)
err = np.seterr(divide='raise') try: x = np.array([0], dtype=np.complex) y = np.complex(-np.inf, 0) self.assertRaises(FloatingPointError, np.log, x) np.seterr(divide='ignore') assert_almost_equal(np.log(x), y) finally: np.seterr(**err)
def test_special_values(self): xl = [] yl = []
x = np.array([complex(1., np.nan)], dtype=np.complex) y = np.complex(np.nan, np.nan) assert_almost_equal(np.log(x), y) xl.append(x) yl.append(y) x = np.array([np.inf + np.nan * 1j], dtype=np.complex) assert_almost_equal(np.log(x), y)
err = np.seterr(invalid='raise') try: x = np.array([complex(1., np.nan)], dtype=np.complex) y = np.complex(np.nan, np.nan) np.seterr(invalid='ignore') assert_almost_equal(np.log(x), y) finally: np.seterr(**err) xl.append(x) yl.append(y) err = np.seterr(invalid='raise') try: x = np.array([np.inf + 1j * np.nan], dtype...
def test_special_values(self): xl = [] yl = []
for i in range(len(xa)): assert_almost_equal(np.log(np.conj(xa[i])), np.conj(np.log(xa[i])))
err = np.seterr(divide='ignore') try: for i in range(len(xa)): assert_almost_equal(np.log(np.conj(xa[i])), np.conj(np.log(xa[i]))) finally: np.seterr(**err)
def test_special_values(self): xl = [] yl = []
if not np.isnan(z.real) or not np.isinf(z.imag): raise AssertionError( "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" \ % (z.real, z.imag))
err = np.seterr(invalid='ignore') try: if not (np.isnan(z.real) and np.isinf(z.imag)): raise AssertionError(msgform % (z.real, z.imag)) finally: np.seterr(**err)
def _check_ninf_nan(dummy): z = np.sqrt(np.array(np.complex(-np.inf, np.nan))) if not np.isnan(z.real) or not np.isinf(z.imag): raise AssertionError( "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" \ % (z.real, z.imag))
y_r = x ** 2 y = np.power(x, 2) for i in range(len(x)): assert_almost_equal(y[i], y_r[i])
err = np.seterr(invalid='ignore') try: y_r = x ** 2 y = np.power(x, 2) for i in range(len(x)): assert_almost_equal(y[i], y_r[i]) finally: np.seterr(**err)
def test_simple(self): x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) y_r = x ** 2 y = np.power(x, 2) for i in range(len(x)): assert_almost_equal(y[i], y_r[i])
n_r = [x[i] ** y[i] for i in lx] for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)
err = np.seterr(invalid='ignore') try: n_r = [x[i] ** y[i] for i in lx] for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) finally: np.seterr(**err)
def test_scalar(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) lx = range(len(x)) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard p_r[4] = comp...
n_r = x ** y for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i)
err = np.seterr(invalid='ignore') try: n_r = x ** y for i in lx: assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) finally: np.seterr(**err)
def test_array(self): x = np.array([1, 1j, 2, 2.5+.37j, np.inf, np.nan]) y = np.array([1, 1j, -0.5+1.5j, -0.5+1.5j, 2, 3]) lx = range(len(x)) # Compute the values for complex type in python p_r = [complex(x[i]) ** complex(y[i]) for i in lx] # Substitute a result allowed by C99 standard p_r[4] = compl...
if not np.issubdtype(y.dtype, int):
if not np.issubdtype(y.dtype, np.integer):
def _nanop(op, fill, a, axis=None): """ General operation on arrays with not-a-number values. Parameters ---------- op : callable Operation to perform. fill : float NaN values are set to fill before doing the operation. a : array-like Input array. axis : {int, None}, optional Axis along which the operation is computed...
f = tempfile.TemporaryFile()
f0 = tempfile.NamedTemporaryFile() f = f0.file
def test_fromfile_tofile_seeks(self): # On Python 3, tofile/fromfile used to get (#1610) the Python # file handle out of sync f = tempfile.TemporaryFile() f.write(np.arange(255, dtype='u1').tostring())
mid = (high - low) / 2 + low
mid = (high - low) // 2 + low
typedef %(type)s npy_check_sizeof_type;
loggername="%s.%s"%(BASENAME,myclass)
loggername="fuglu.%s"%(myclass,)
def _logger(self): myclass=self.__class__.__name__ loggername="%s.%s"%(BASENAME,myclass) return logging.getLogger(loggername)
class SMTPServer: def __init__(self, controller,port=10025,address="127.0.0.1"): self.logger=logging.getLogger("%s.smtp.incoming.%s"%(BASENAME,port)) self.logger.debug('Starting incoming SMTP Server on Port %s'%port) self.port=port self.controller=controller self.stayalive=1 try: self._socket = socket.socket(socket.AF...
def _load_component(self,structured_name,configsection=None): #from: http://mail.python.org/pipermail/python-list/2003-May/204392.html component_names = structured_name.split('.') mod = __import__('.'.join(component_names[:-1])) for component_name in component_names[1:]: mod = getattr(mod, component_name) if configsec...
self.logger=logging.getLogger("%s.controlsessoin"%(BASENAME,))
self.logger=logging.getLogger('fuglu.controlsession')
def __init__(self,socket,controller): self.controller=controller self.socket=socket self.commands={ 'workerlist':self.workerlist, 'threadlist':self.threadlist, 'uptime':self.uptime, 'stats':self.stats } self.logger=logging.getLogger("%s.controlsessoin"%(BASENAME,))
self.logger=logging.getLogger("%s.control.%s"%(BASENAME,port))
self.logger=logging.getLogger("fuglu.control.%s"%port)
def __init__(self, controller,port=10010,address="127.0.0.1"): self.logger=logging.getLogger("%s.control.%s"%(BASENAME,port)) self.logger.debug('Starting Control/Info server on port %s'%port) self.port=port self.controller=controller self.stayalive=1 try: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM...
class DummySMTPServer(object): """one-time smtp server to test re-injects""" def __init__(self, config,port=11026,address="127.0.0.1"): self.logger=logging.getLogger("dummy.smtpserver") self.logger.debug('Starting dummy SMTP Server on Port %s'%port) self.port=port self.config=config self._socket = socket.socket(socket...
def serve(self): threading.currentThread().name='ControlServer Thread' controller=self.controller self.logger.info('Control/Info Server running on port %s'%self.port) while self.stayalive: try: self.logger.debug('Waiting for connection...') nsd = self._socket.accept() if not self.stayalive: break engine = ControlSessi...
sesshandler=SessionHandler(None,self.mc.config,self.mc.prependers,self.mc.plugins,self.mc.appenders)
def test_writeheaders(self): import random sesshandler=SessionHandler(None,self.mc.config,self.mc.prependers,self.mc.plugins,self.mc.appenders) suspect=Suspect("oli@unittests.fuglu.org", "recipient@unittests.fuglu.org", "testdata/helloworld.eml") rnd=random.randint(1000,1000000) suspect.addheader('randomstuff',str(rnd...
msgsource=sesshandler._buildmsgsource(suspect)
from fuglu.smtpconnector import buildmsgsource msgsource=buildmsgsource(suspect)
def test_writeheaders(self): import random sesshandler=SessionHandler(None,self.mc.config,self.mc.prependers,self.mc.plugins,self.mc.appenders) suspect=Suspect("oli@unittests.fuglu.org", "recipient@unittests.fuglu.org", "testdata/helloworld.eml") rnd=random.randint(1000,1000000) suspect.addheader('randomstuff',str(rnd...
class OtherTests(unittest.TestCase): """Other testcases""" def setUp(self): config=ConfigParser.RawConfigParser() config.add_section('main') config.set('main', 'disablebounces', '1') config.set('main', 'tempdir', '/tmp') self.config=config def testSMTPClient(self): """Test Overridden smtpclient""" self.smtp=DummySMT...
def testE2E(self): """test if a standard message runs through""" from email.mime.text import MIMEText
self.protohandlerdefer(retmesg)
self.protohandler.defer(retmesg)
def handlesession(self,workerthread=None): self.workerthread=workerthread starttime=time.time() sess=None prependheader=self.config.get('main','prependaddedheaders') try: self.set_threadinfo('receiving message')
port = struct.unpack('!H', data[1:3])[0] address = data[3:]
if family==4 or family==6: port = struct.unpack('!H', data[1:3])[0] address = data[3:] else: port =0 address = 'unknown'
def _ParseConnect(self, cmd, data): """Parse the 'Connect' milter data into arguments for the milter handler.
if result.find('GTUBE ')>-1:
gtubere=re.compile('GTUBE[^-]') if gtubere.search(result)!=None:
def lint_spam(self): stream="""Date: Mon, 08 Sep 2008 17:33:54 +0200
self.__milter_dispatcher = PpyMilterDispatcher(object) self.__milter_dispatcher.__milter=self
self.__milter_dispatcher = PpyMilterDispatcher(self)
def __init__(self,socket,config): PpyMilter.__init__(self) self.socket=socket self.config=config self.CanAddHeaders() self.CanChangeBody() self.CanChangeHeaders()
def OnMailFrom(self,cmd,mail_from):
def OnMailFrom(self,cmd,mail_from,args):
def OnMailFrom(self,cmd,mail_from): self.from_address=mail_from return self.Continue()
dat=self.socket.recv(MILTER_LEN_BYTES)
lenbuf=[] lenread=0 while lenread < MILTER_LEN_BYTES: pdat=self.socket.recv(MILTER_LEN_BYTES-lenread) lenbuf.append(pdat) lenread+=len(pdat) dat="".join(lenbuf)
def getincomingmail(self): try: while True: dat=self.socket.recv(MILTER_LEN_BYTES) self.logger.info(dat) self.logger.info(len(dat)) packetlen = int(struct.unpack('!I',dat)[0]) inbuf = [] read = 0 while read < packetlen: partial_data = self.socket.recv(packetlen - read) inbuf.append(partial_data) read += len(partial_dat...
def unquoteData(self,data): """two leading dots at the beginning of a line must be unquoted to a single dot""" return re.sub(r'(?m)^\.\.', '.',data)
def doData(self, data): #store the last few bytes in memory to keep track when the msg is finished self.dataAccum = self.dataAccum + data if len(self.dataAccum)>4: self.dataAccum=self.dataAccum[-5:] if len(self.dataAccum) > 4 and self.dataAccum[-5:] == '\r\n.\r\n': #check if there is more data to write tot he file if...
if 'section' in inspect.getargspec(mod.__init__).args:
if 'section' in inspect.getargspec(mod.__init__)[0]:
def _load_component(self,structured_name,configsection=None): #from: http://mail.python.org/pipermail/python-list/2003-May/204392.html component_names = structured_name.split('.') mod = __import__('.'.join(component_names[:-1])) for component_name in component_names[1:]: mod = getattr(mod, component_name) if configsec...
return string_to_actioncode(self.config.get(self.section,'virusaction'))
virusaction=self.config.get(self.section,'virusaction') actioncode=string_to_actioncode(virusaction,self.config) return actioncode
def examine(self,suspect): starttime=time.time() if suspect.size>self.maxsize: self._logger().info('Not scanning - message too big') return content=suspect.getMessageRep().as_string()
return True
return True class ClamavPluginTestCase(unittest.TestCase): """Testcases for the Stub Plugin""" def setUp(self): from ConfigParser import RawConfigParser import os config=RawConfigParser() config.add_section('main') config.add_section('virus') config.set('main','prependaddedheaders','X-Fuglu-') config.set('virus','def...
def lint_eicar(self): stream="""Date: Mon, 08 Sep 2008 17:33:54 +0200
return "Vacation(%s) start=%s end=%s ignore=%s subject=%s"%(self.awayuser,self.start,self.end,self.ignoresender,self.subject)
return "Vacation(%s) start=%s end=%s ignore=%s"%(self.awayuser,self.start,self.end,self.ignoresender)
def __str__(self): return "Vacation(%s) start=%s end=%s ignore=%s subject=%s"%(self.awayuser,self.start,self.end,self.ignoresender,self.subject)
self.logger=logging.getLogger('fuglu.plugins.vacation.Cache')
self.logger=logging.getLogger('fuglu.plugin.vacation.Cache')
def __init__(self,config): self.__dict__ = self.__shared_state if not hasattr(self, 'vacations'): self.vacations={} if not hasattr(self,'regexcache'): self.regexcache={}
log=dbsession.query(VacationReply).filter_by(vacation=vacation).filter(VacationReply.sent>datetime.now()-timedelta(days=1)).first()
log=dbsession.query(VacationReply).filter_by(vacation=vacation).filter(VacationReply.sent>datetime.now()-timedelta(days=1)).filter_by(recipient=recipient).first()
def already_notified(self,vacation,recipient): """return true if this user has been notfied in the last 24 hours""" dbsession=fuglu.extensions.sql.get_session(self.config.get(self.section,'dbconnectstring')) log=dbsession.query(VacationReply).filter_by(vacation=vacation).filter(VacationReply.sent>datetime.now()-timedel...
print "Could not connect to database: %s"%e
print "Database error: %s"%e
def lint_sql(self): if not fuglu.extensions.sql.ENABLED: print "Vacation requires the fuglu sql extension to be enabled" return False try: dbsession=fuglu.extensions.sql.get_session(self.config.get(self.section,'dbconnectstring')) bind=dbsession.get_bind(Vacation) bind.connect() except Exception,e: print "Could not co...
self.failUnless(score>1000, "GTUBE mails should score > 1000")
self.failUnless(score>999, "GTUBE mails should score ~1000 , we got %s"%score)
def test_score(self): suspect=Suspect('sender@unittests.fuglu.org','recipient@unittests.fuglu.org','/dev/null') stream="""Date: Mon, 08 Sep 2008 17:33:54 +0200
(spamword,spamstatus,colon, score,slash,required)=line2_spaminfo.split()
self.logger.debug('Spamd said: %s'%line2_spaminfo) (spamword,spamstatusword,colon, score,slash,required)=line2_spaminfo.split()
def safilter_symbols(self,messagecontent,user): """Pass content to sa, return spamflag, score, rules""" serverHost = self.config.get(self.section,'host') serverPort = self.config.getint(self.section,'port') timeout=self.config.getint(self.section,'timeout') retries = self.config.getint(self.section,'retries') peruserco...
if spamstatus=='True': spamstatus=True return (spamstatus,float(score),rules)
if spamstatusword=='True': spstatus=True return (spstatus,float(score),rules)
def safilter_symbols(self,messagecontent,user): """Pass content to sa, return spamflag, score, rules""" serverHost = self.config.get(self.section,'host') serverPort = self.config.getint(self.section,'port') timeout=self.config.getint(self.section,'timeout') retries = self.config.getint(self.section,'retries') peruserco...
suspect=Suspect('sender@unittests.fuglu.org','recipient@unittests.fuglu.org','/dev/null')
def test_symbols(self): suspect=Suspect('sender@unittests.fuglu.org','recipient@unittests.fuglu.org','/dev/null') stream="""Date: Mon, 08 Sep 2008 17:33:54 +0200
spamstatus,spamscore,rules=self.candidate.safilter_symbols(stream,'oli@wgwh.ch')
spamstatus,spamscore,rules=self.candidate.safilter_symbols(stream,'oli@unittests.fuglu.org')
def test_symbols(self): suspect=Suspect('sender@unittests.fuglu.org','recipient@unittests.fuglu.org','/dev/null') stream="""Date: Mon, 08 Sep 2008 17:33:54 +0200
c.todense().I * np.arange(4)[:, np.newaxis])
(c.todense().I * np.arange(4)[:, np.newaxis]).ravel())
def test_complex(): c = complex_matrix() fc = cholesky(c) r = real_matrix() fr = cholesky(r) assert factor_of(fc, c) assert np.allclose(fc(np.arange(4)), c.todense().I * np.arange(4)[:, np.newaxis]) assert np.allclose(fc(np.arange(4) * 1j), c.todense().I * (np.arange(4) * 1j)[:, np.newaxis]) assert np.allclose(fr(np....
c.todense().I * (np.arange(4) * 1j)[:, np.newaxis])
(c.todense().I * (np.arange(4) * 1j)[:, np.newaxis]).ravel())
def test_complex(): c = complex_matrix() fc = cholesky(c) r = real_matrix() fr = cholesky(r) assert factor_of(fc, c) assert np.allclose(fc(np.arange(4)), c.todense().I * np.arange(4)[:, np.newaxis]) assert np.allclose(fc(np.arange(4) * 1j), c.todense().I * (np.arange(4) * 1j)[:, np.newaxis]) assert np.allclose(fr(np....
r.todense().I * np.arange(4)[:, np.newaxis])
(r.todense().I * np.arange(4)[:, np.newaxis]).ravel())
def test_complex(): c = complex_matrix() fc = cholesky(c) r = real_matrix() fr = cholesky(r) assert factor_of(fc, c) assert np.allclose(fc(np.arange(4)), c.todense().I * np.arange(4)[:, np.newaxis]) assert np.allclose(fc(np.arange(4) * 1j), c.todense().I * (np.arange(4) * 1j)[:, np.newaxis]) assert np.allclose(fr(np....
readset = select([self.sock], [], [], timeout)
readset = select([self.sock], [], [], 1)
def wait_msg_from(self, timeout): endtime = time.time() + timeout msg = "" src_addr = None while time.time() < endtime: readset = select([self.sock], [], [], timeout) if len(readset[0]) < 1 or not self.sock in readset[0]: if len(readset[0]) < 1: print "select() timeout" elif not self.sock in readset[0]: print "select()...
print "select() timeout"
print "select() timeout (will wait for " + str(int(endtime - time.time())) + "more secs)"
def wait_msg_from(self, timeout): endtime = time.time() + timeout msg = "" src_addr = None while time.time() < endtime: readset = select([self.sock], [], [], timeout) if len(readset[0]) < 1 or not self.sock in readset[0]: if len(readset[0]) < 1: print "select() timeout" elif not self.sock in readset[0]: print "select()...
if len(readset) < 1 or not self.sock in readset[0]: if len(readset) < 1: print "select() returns " + str(len(readset))
if len(readset[0]) < 1 or not self.sock in readset[0]: if len(readset[0]) < 1: print "select() timeout"
def wait_msg_from(self, timeout): endtime = time.time() + timeout msg = "" src_addr = None while time.time() < endtime: readset = select([self.sock], [], [], timeout) if len(readset) < 1 or not self.sock in readset[0]: if len(readset) < 1: print "select() returns " + str(len(readset)) elif not self.sock in readset[0]: ...
scenario.append(scenario)
scenarios.append(scenario)
def usage(): print """Periodically monitor working directory for Continuous and Nightly builds
self.resp_body = resp_body
self.body = resp_body
def __init__(self, title, resp_code, check_cseq=True, include=[], exclude=[], cmds=[], resp_hdr=[], resp_body=None, expect=""): self.title = title self.cmds = cmds self.include = include self.exclude = exclude self.resp_code = resp_code self.resp_hdr = resp_hdr self.resp_body = resp_body self.expect = expect
while cseq <= last_cseq and method == last_method: request, src_addr = dlg.wait_msg_from(10)
call_id = last_call_id while cseq <= last_cseq and method == last_method and call_id == last_call_id: request, src_addr = dlg.wait_msg_from(30)
def test_func(test): pjsua = test.process[0] dlg = sip.Dialog("127.0.0.1", pjsua.inst_param.sip_port, local_port=srv_port, tcp=cfg_file.recvfrom_cfg.tcp) last_cseq = 0 last_method = "" for t in cfg_file.recvfrom_cfg.transaction: # Print transaction title if t.title != "": dlg.trace(t.title) # Run command and expect pa...
request, src_addr = dlg.wait_msg_from(10)
request, src_addr = dlg.wait_msg_from(30)
def test_func(test): pjsua = test.process[0] dlg = sip.Dialog("127.0.0.1", pjsua.inst_param.sip_port, local_port=srv_port, tcp=cfg_file.recvfrom_cfg.tcp) last_cseq = 0 last_method = "" for t in cfg_file.recvfrom_cfg.transaction: # Print transaction title if t.title != "": dlg.trace(t.title) # Run command and expect pa...
self.pdf.set_x(x)
self.pdf.set_x(self.table_offset)
def output_table_header(self): if self.theader: b = self.b x = self.pdf.x self.set_style('B',True) for cell, bgcolor in self.theader: self.box_shadow(cell[0], cell[1], bgcolor) self.pdf.cell(*cell) self.set_style('B',b) self.pdf.ln(self.theader[0][0][1]) self.pdf.set_x(x) self.theader_out = True
if int(self.table.get('border', 0)): self.output_table_sep()
def output_table_footer(self): if self.tfooter: x = self.pdf.x #TODO: self.output_table_sep() for cell, bgcolor in self.tfooter: self.box_shadow(cell[0], cell[1], bgcolor) self.pdf.cell(*cell) self.pdf.ln(self.tfooter[0][0][1]) self.pdf.set_x(x) #TODO: self.output_table_sep() self.tfooter_out = True
print "h", h
def handle_data(self, txt): if self.td is not None: # drawing a table? if 'width' not in self.td and 'colspan' not in self.td: l = [self.table_col_width[self.table_col_index]] elif 'colspan' in self.td: i = self.table_col_index colspan = int(self.td['colspan']) l = self.table_col_width[i:i+colspan] else: l = [self.td.g...
print "td cell", self.pdf.x, w, txt, "*"
if DEBUG: print "td cell", self.pdf.x, w, txt, "*"
def handle_data(self, txt): if self.td is not None: # drawing a table? if 'width' not in self.td and 'colspan' not in self.td: l = [self.table_col_width[self.table_col_index]] elif 'colspan' in self.td: i = self.table_col_index colspan = int(self.td['colspan']) l = self.table_col_width[i:i+colspan] else: l = [self.td.g...
print "cell", txt, "*"
if DEBUG: print "cell", txt, "*"
def handle_data(self, txt): if self.td is not None: # drawing a table? if 'width' not in self.td and 'colspan' not in self.td: l = [self.table_col_width[self.table_col_index]] elif 'colspan' in self.td: i = self.table_col_index colspan = int(self.td['colspan']) l = self.table_col_width[i:i+colspan] else: l = [self.td.g...
print "write", txt, "*"
if DEBUG: print "write", txt, "*"
def handle_data(self, txt): if self.td is not None: # drawing a table? if 'width' not in self.td and 'colspan' not in self.td: l = [self.table_col_width[self.table_col_index]] elif 'colspan' in self.td: i = self.table_col_index colspan = int(self.td['colspan']) l = self.table_col_width[i:i+colspan] else: l = [self.td.g...
print "box_shadow", w, h, bgcolor
if DEBUG: print "box_shadow", w, h, bgcolor
def box_shadow(self, w, h, bgcolor): print "box_shadow", w, h, bgcolor if bgcolor: fill_color = self.pdf.fill_color self.pdf.set_fill_color(*bgcolor) self.pdf.rect(self.pdf.x, self.pdf.y, w, h, 'F') self.pdf.fill_color = fill_color
print "STARTTAG", tag, attrs
if DEBUG: print "STARTTAG", tag, attrs
def handle_starttag(self, tag, attrs): attrs = dict(attrs) print "STARTTAG", tag, attrs if tag=='b' or tag=='i' or tag=='u': self.set_style(tag,1) if tag=='a': self.href=attrs['href'] if tag=='br': self.pdf.ln(5) if tag=='p': self.pdf.ln(5) if attrs: self.align=attrs['align'].lower() if tag in ('h1', 'h2', 'h3', 'h4', ...
print "ENDTAG", tag
if DEBUG: print "ENDTAG", tag
def handle_endtag(self, tag): #Closing tag print "ENDTAG", tag if tag=='h1' or tag=='h2' or tag=='h3' or tag=='h4': self.pdf.ln(6) self.set_font() self.set_style() self.align = None if tag=='pre': self.pdf.set_font(self.font or 'Times','',12) self.pdf.set_font_size(12) self.pre=False if tag=='blockquote': self.set_text...
print "revert style"
if DEBUG: print "revert style"
def handle_endtag(self, tag): #Closing tag print "ENDTAG", tag if tag=='h1' or tag=='h2' or tag=='h3' or tag=='h4': self.pdf.ln(6) self.set_font() self.set_style() self.align = None if tag=='pre': self.pdf.set_font(self.font or 'Times','',12) self.pdf.set_font_size(12) self.pre=False if tag=='blockquote': self.set_text...
print "H", self.h
if DEBUG: print "H", self.h
def set_font(self, face=None, size=None): if face: self.font_face = face if size: self.font_size = size self.h = size / 72.0*25.4 print "H", self.h self.pdf.set_font(self.font_face or 'times','',12) self.pdf.set_font_size(self.font_size or 12) self.set_style('u', False) self.set_style('b', False) self.set_style('i', Fa...
print "SET_FONT_STYLE", style
if DEBUG: print "SET_FONT_STYLE", style
def set_style(self, tag=None, enable=None): #Modify style and select corresponding font if tag: t = self.style.get(tag.lower()) self.style[tag.lower()] = enable style='' for s in ('b','i','u'): if self.style.get(s): style+=s print "SET_FONT_STYLE", style self.pdf.set_font('',style)
self.diffs=[]
self.diffs={}
def __init__(self, orientation='P',unit='mm',format='A4'): #Some checks self._dochecks() #Initialization of properties self.offsets={} self.page=0 self.n=2 self.buffer='' self.pages={} self.orientation_changes={} self.state=0 self.fonts={} self.font_files={} self.diffs=[] self.images={} self.page_links={} self.links={}...
if(type(dest)==type(bool())): if dest: dest='D' else: dest='F'
def output(self, name='',dest=''): "Output PDF to some destination" #Finish document if necessary if(self.state<3): self.close() #Normalize parameters if(type(dest)==type(bool())): if dest: dest='D' else: dest='F' dest=dest.upper() if(dest==''): if(name==''): name='doc.pdf' dest='I' else: dest='F' if dest=='I': print s...