rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
n : int Sets the size of the arrays for which the returned indices will be valid. | arr : array_like The indices will be valid for square arrays whose dimensions are the same as arr. | def tril_indices_from(arr,k=0): """ Return the indices for the lower-triangle of an (n, n) array. See `tril_indices` for full details. Parameters ---------- n : int Sets the size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). See Also -------- ... |
if not arr.ndim==2 and arr.shape[0] == arr.shape[1]: | if not (arr.ndim == 2 and arr.shape[0] == arr.shape[1]): | def tril_indices_from(arr,k=0): """ Return the indices for the lower-triangle of an (n, n) array. See `tril_indices` for full details. Parameters ---------- n : int Sets the size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `tril` for details). See Also -------- ... |
Sets the size of the arrays for which the returned indices will be valid. | The size of the arrays for which the returned indices will be valid. | def triu_indices(n,k=0): """ Return the indices for the upper-triangle of an (n, n) array. Parameters ---------- n : int Sets the size of the arrays for which the returned indices will be valid. k : int, optional Diagonal offset (see `triu` for details). Returns ------- inds : tuple of arrays The indices for the tria... |
c = cov(x, y, bias=bias, ddof=ddof) | c = cov(x, y, rowvar, bias, ddof) | def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None): """ Return correlation coefficients. Please refer to the documentation for `cov` for more detail. The relationship between the correlation coefficient matrix, P, and the covariance matrix, C, is .. math:: P_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } } T... |
func(*args[:func.im_func.func_code.co_argcount]) | if sys.version_info[0] >= 3: func(*args[:func.__code__.co_argcount]) else: func(*args[:func.im_func.func_code.co_argcount]) | def link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, export_symbols = None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # Include the appropiate MSVC runtime library if Python was built # with MSVC >= 7.0 (MinGW standa... |
st = config.check_decl(fname2def("decl_%s" % f), | already_declared = config.check_decl(fname2def("decl_%s" % f), | def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) |
if not st: | if already_declared: pub.append('NPY_%s' % fname2def("decl_%s" % f)) else: | def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) |
else: _add_decl(f) | def _add_decl(f): priv.append(fname2def("decl_%s" % f)) pub.append('NPY_%s' % fname2def("decl_%s" % f)) | |
assert_all(isnan(array((1.,))/0.) == 0) seterr(**olderr) | try: assert_all(isnan(array((1.,))/0.) == 0) finally: seterr(**olderr) | def test_posinf(self): olderr = seterr(divide='ignore') assert_all(isnan(array((1.,))/0.) == 0) seterr(**olderr) |
assert_all(isnan(array((-1.,))/0.) == 0) seterr(**olderr) | try: assert_all(isnan(array((-1.,))/0.) == 0) finally: seterr(**olderr) | def test_neginf(self): olderr = seterr(divide='ignore') assert_all(isnan(array((-1.,))/0.) == 0) seterr(**olderr) |
assert_all(isnan(array((0.,))/0.) == 1) seterr(**olderr) | try: assert_all(isnan(array((0.,))/0.) == 1) finally: seterr(**olderr) | def test_ind(self): olderr = seterr(divide='ignore', invalid='ignore') assert_all(isnan(array((0.,))/0.) == 1) seterr(**olderr) |
assert_all(isnan(array(0+0j)/0.) == 1) seterr(**olderr) | try: assert_all(isnan(array(0+0j)/0.) == 1) finally: seterr(**olderr) | def test_complex1(self): olderr = seterr(divide='ignore', invalid='ignore') assert_all(isnan(array(0+0j)/0.) == 1) seterr(**olderr) |
assert_all(isfinite(array((1.,))/0.) == 0) seterr(**olderr) | try: assert_all(isfinite(array((1.,))/0.) == 0) finally: seterr(**olderr) | def test_posinf(self): olderr = seterr(divide='ignore') assert_all(isfinite(array((1.,))/0.) == 0) seterr(**olderr) |
assert_all(isfinite(array((-1.,))/0.) == 0) seterr(**olderr) | try: assert_all(isfinite(array((-1.,))/0.) == 0) finally: seterr(**olderr) | def test_neginf(self): olderr = seterr(divide='ignore') assert_all(isfinite(array((-1.,))/0.) == 0) seterr(**olderr) |
assert_all(isfinite(array((0.,))/0.) == 0) seterr(**olderr) | try: assert_all(isfinite(array((0.,))/0.) == 0) finally: seterr(**olderr) | def test_ind(self): olderr = seterr(divide='ignore', invalid='ignore') assert_all(isfinite(array((0.,))/0.) == 0) seterr(**olderr) |
assert_all(isfinite(array(1+1j)/0.) == 0) seterr(**olderr) | try: assert_all(isfinite(array(1+1j)/0.) == 0) finally: seterr(**olderr) | def test_complex1(self): olderr = seterr(divide='ignore', invalid='ignore') assert_all(isfinite(array(1+1j)/0.) == 0) seterr(**olderr) |
assert_all(isinf(array((1.,))/0.) == 1) seterr(**olderr) | try: assert_all(isinf(array((1.,))/0.) == 1) finally: seterr(**olderr) | def test_posinf(self): olderr = seterr(divide='ignore') assert_all(isinf(array((1.,))/0.) == 1) seterr(**olderr) |
assert_all(isinf(array(1.,)/0.) == 1) seterr(**olderr) | try: assert_all(isinf(array(1.,)/0.) == 1) finally: seterr(**olderr) | def test_posinf_scalar(self): olderr = seterr(divide='ignore') assert_all(isinf(array(1.,)/0.) == 1) seterr(**olderr) |
assert_all(isinf(array((-1.,))/0.) == 1) seterr(**olderr) | try: assert_all(isinf(array((-1.,))/0.) == 1) finally: seterr(**olderr) | def test_neginf(self): olderr = seterr(divide='ignore') assert_all(isinf(array((-1.,))/0.) == 1) seterr(**olderr) |
assert_all(isinf(array(-1.)/0.) == 1) seterr(**olderr) | try: assert_all(isinf(array(-1.)/0.) == 1) finally: seterr(**olderr) | def test_neginf_scalar(self): olderr = seterr(divide='ignore') assert_all(isinf(array(-1.)/0.) == 1) seterr(**olderr) |
assert_all(isinf(array((0.,))/0.) == 0) seterr(**olderr) | try: assert_all(isinf(array((0.,))/0.) == 0) finally: seterr(**olderr) | def test_ind(self): olderr = seterr(divide='ignore', invalid='ignore') assert_all(isinf(array((0.,))/0.) == 0) seterr(**olderr) |
vals = isposinf(array((-1.,0,1))/0.) seterr(**olderr) | try: vals = isposinf(array((-1.,0,1))/0.) finally: seterr(**olderr) | def test_generic(self): olderr = seterr(divide='ignore', invalid='ignore') vals = isposinf(array((-1.,0,1))/0.) seterr(**olderr) assert(vals[0] == 0) assert(vals[1] == 0) assert(vals[2] == 1) |
vals = isneginf(array((-1.,0,1))/0.) seterr(**olderr) | try: vals = isneginf(array((-1.,0,1))/0.) finally: seterr(**olderr) | def test_generic(self): olderr = seterr(divide='ignore', invalid='ignore') vals = isneginf(array((-1.,0,1))/0.) seterr(**olderr) assert(vals[0] == 1) assert(vals[1] == 0) assert(vals[2] == 0) |
vals = nan_to_num(array((-1.,0,1))/0.) seterr(**olderr) | try: vals = nan_to_num(array((-1.,0,1))/0.) finally: seterr(**olderr) | def test_generic(self): olderr = seterr(divide='ignore', invalid='ignore') vals = nan_to_num(array((-1.,0,1))/0.) seterr(**olderr) assert_all(vals[0] < -1e10) and assert_all(isfinite(vals[0])) assert(vals[1] == 0) assert_all(vals[2] > 1e10) and assert_all(isfinite(vals[2])) |
v += array(0+1.j)/0. seterr(**olderr) | try: v += array(0+1.j)/0. finally: seterr(**olderr) | def test_complex_bad(self): v = 1+1j olderr = seterr(divide='ignore', invalid='ignore') v += array(0+1.j)/0. seterr(**olderr) vals = nan_to_num(v) # !! This is actually (unexpectedly) zero assert_all(isfinite(vals)) |
v += array(-1+1.j)/0. seterr(**olderr) | try: v += array(-1+1.j)/0. finally: seterr(**olderr) | def test_complex_bad2(self): v = 1+1j olderr = seterr(divide='ignore', invalid='ignore') v += array(-1+1.j)/0. seterr(**olderr) vals = nan_to_num(v) assert_all(isfinite(vals)) #assert_all(vals.imag > 1e10) and assert_all(isfinite(vals)) # !! This is actually (unexpectedly) positive # !! inf. Comment out for now, and ... |
if typ!=typ2: | if typ2 is None: log.warn('source %r does not define swig target, assuming %s swig target' \ % (source, typ)) if is_cpp: target_ext = '.cpp' elif typ!=typ2: | def swig_sources(self, sources, extension): # Assuming SWIG 1.3.14 or later. See compatibility note in # http://www.swig.org/Doc1.3/Python.html#Python_nn6 |
result = 'c' | result = None | def get_swig_target(source): f = open(source,'r') result = 'c' line = f.readline() if _has_cpp_header(line): result = 'c++' if _has_c_header(line): result = 'c' f.close() return result |
f = open(file,'r') | f = open_latin1(file,'r') | def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 f = open(file,'r') line = f.readline() n = 10000 # the number of non-comment lines to scan for hints if _has_f_header(line): n = 0 elif ... |
f = open(src,'r') | f = open_latin1(src,'r') | def has_f90_header(src): f = open(src,'r') line = f.readline() f.close() return _has_f90_header(line) or _has_fix_header(line) |
f = open(src,'r') | f = open_latin1(src,'r') | def get_f77flags(src): """ Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}. """ flags = {} f = open(src,'r') i = 0 for line in f.readlines(): i += 1 if i>20: break m = _f77flags_re.match(line) if not m: continue f... |
for tup in iterizip(*iters): | for tup in itertools.izip(*iters): | def sentinel(counter = ([fill_value]*(len(seqarrays)-1)).pop): "Yields the fill_value or raises IndexError" yield counter() |
scale = 0.5*(np.abs(desired) + np.abs(actual)) scale = np.power(10,np.floor(np.log10(scale))) | err = np.seterr(invalid='ignore') try: scale = 0.5*(np.abs(desired) + np.abs(actual)) scale = np.power(10,np.floor(np.log10(scale))) finally: np.seterr(**err) | def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): """ Raise an assertion if two items are not equal up to significant digits. Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree. Parameters ---------- ac... |
r = np.array([['abc']], dtype=[('var1', '|S20')]) assert str(r['var1'][0][0]) == 'abc' | r = np.array([[asbytes('abc')]], dtype=[('var1', '|S20')]) assert asbytes(r['var1'][0][0]) == asbytes('abc') | def test_junk_in_string_fields_of_recarray(self, level=rlevel): """Ticket #483""" r = np.array([['abc']], dtype=[('var1', '|S20')]) assert str(r['var1'][0][0]) == 'abc' |
bad_version_magic = [ | bad_version_magic = asbytes_nested([ | def test_write_version_1_0(): f = StringIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), (2, 0), (2, 2), (255, 255), ] for version in bad_versions: try: format.write_array(f, arr, version... |
] malformed_magic = [ | ]) malformed_magic = asbytes_nested([ | def test_write_version_1_0(): f = StringIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), (2, 0), (2, 2), (255, 255), ] for version in bad_versions: try: format.write_array(f, arr, version... |
] | ]) | def test_write_version_1_0(): f = StringIO() arr = np.arange(1) # These should pass. format.write_array(f, arr, version=(1, 0)) format.write_array(f, arr) # These should all fail. bad_versions = [ (1, 1), (0, 0), (0, 1), (2, 0), (2, 2), (255, 255), ] for version in bad_versions: try: format.write_array(f, arr, version... |
s = StringIO('1') | s = StringIO(asbytes('1')) | def test_bad_header(): # header of length less than 2 should fail s = StringIO() assert_raises(ValueError, format.read_array_header_1_0, s) s = StringIO('1') assert_raises(ValueError, format.read_array_header_1_0, s) # header shorter than indicated size should fail s = StringIO('\x01\x00') assert_raises(ValueError, fo... |
s = StringIO('\x01\x00') | s = StringIO(asbytes('\x01\x00')) | def test_bad_header(): # header of length less than 2 should fail s = StringIO() assert_raises(ValueError, format.read_array_header_1_0, s) s = StringIO('1') assert_raises(ValueError, format.read_array_header_1_0, s) # header shorter than indicated size should fail s = StringIO('\x01\x00') assert_raises(ValueError, fo... |
x = np.array([1,2,3], dtype=np.int32) | x = np.array([1,2,3], dtype=np.dtype('<i4')) | def test_buffer_hashlib(self): try: from hashlib import md5 except ImportError: from md5 import new as md5 |
assert_equal(datetime_data(a.dtype), ('us', 1, 1, 1)) | assert_equal(datetime_data(a.dtype), (asbytes('us'), 1, 1, 1)) | def test_basic(self): a = array(['1980-03-23'], dtype=datetime64) assert_equal(datetime_data(a.dtype), ('us', 1, 1, 1)) |
sys.stderr.write("G3 f2py support is not implemented, yet.\n") | sys.stderr.write("G3 f2py support is not implemented, yet.\\n") | def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir,f2py_exe) if newer(__file__,target): log.info('Creatin... |
sys.stderr.write("Unknown mode: " + repr(mode) + "\n") | sys.stderr.write("Unknown mode: " + repr(mode) + "\\n") | def generate_f2py_py(build_dir): f2py_exe = 'f2py'+os.path.basename(sys.executable)[6:] if f2py_exe[-4:]=='.exe': f2py_exe = f2py_exe[:-4] + '.py' if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': f2py_exe = f2py_exe + '.py' target = os.path.join(build_dir,f2py_exe) if newer(__file__,target): log.info('Creatin... |
if sys.platform == 'win32' and not isinstance(target_file, StringIO): | if sys.platform == 'win32' and not isinstance(target_file, BytesIO): | def roundtrip(self, save_func, *args, **kwargs): """ save_func : callable Function used to save arrays to file. file_on_disk : bool If true, store the file on disk, instead of in a string buffer. save_kwds : dict Parameters passed to `save_func`. load_kwds : dict Parameters passed to `numpy.load`. args : tuple of array... |
for arch in ["ppc", "i686", "x86_64"]: | for arch in ["ppc", "i686", "x86_64", "ppc64"]: | def _universal_flags(self, cmd): """Return a list of -arch flags for every supported architecture.""" if not sys.platform == 'darwin': return [] arch_flags = [] for arch in ["ppc", "i686", "x86_64"]: if _can_target(cmd, arch): arch_flags.extend(["-arch", arch]) return arch_flags |
>>> from numpy import polynomial as P >>> c = P.Chebyshev(np.arange(4)) | >>> c = P.Legendre(range(4)) | def leg2poly(cs) : """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameter... |
Chebyshev([ 0., 1., 2., 3.], [-1., 1.]) >>> p = P.Polynomial(P.cheb2poly(c.coef)) | Legendre([ 0., 1., 2., 3.], [-1., 1.]) >>> p = c.convert(kind=P.Polynomial) | def leg2poly(cs) : """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameter... |
Polynomial([ -2., -8., 4., 12.], [-1., 1.]) | Polynomial([-1. , -3.5, 3. , 7.5], [-1., 1.]) >>> P.leg2poly(range(4)) array([-1. , -3.5, 3. , 7.5]) | def leg2poly(cs) : """ Convert a Legendre series to a polynomial. Convert an array representing the coefficients of a Legendre series, ordered from lowest degree to highest, to an array of the coefficients of the equivalent polynomial (relative to the "standard" basis) ordered from lowest to highest degree. Parameter... |
>>> L.legval(-3, L.chebline(3,2)) | >>> L.legval(-3, L.legline(3,2)) | def legline(off, scl) : """ Legendre series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Legendre series for ``off + scl*x``. See Also -------- polyline, chebline Examples --... |
def chebline(off, scl) : """ Chebyshev series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Chebyshev series for ``off + scl*x``. See Also -------- polyline Examples -------- ... | def chebline(off, scl) : """ Chebyshev series whose graph is a straight line. Parameters ---------- off, scl : scalars The specified line is given by ``off + scl*x``. Returns ------- y : ndarray This module's representation of the Chebyshev series for ``off + scl*x``. See Also -------- polyline Examples -------- ... | |
that are not in the Chebyshev polynomial basis set. Thus, to express the product as a C-series, it is typically necessary to "re-project" the product onto said basis set, which typically produces "un-intuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legen... | that are not in the Legendre polynomial basis set. Thus, to express the product as a Legendre series, it is necessary to "re-project" the product onto said basis set, which may produce "un-intuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L | def legmul(c1, c2): """ Multiply one Legendre series by another. Returns the product of two Legendre series `c1` * `c2`. The arguments are sequences of coefficients, from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-d arrays ... |
>>> from numpy.polynomial import legyshev as L | >>> from numpy.polynomial import legendre as L | def legint(cs, m=1, k=[], lbnd=0, scl=1): """ Integrate a Legendre series. Returns a Legendre series that is the Legendre series `cs`, integrated `m` times from `lbnd` to `x`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in... |
array([ 0.5, -0.5, 0.5, 0.5]) | array([ 0.33333333, 0.4 , 0.66666667, 0.6 ]) | def legint(cs, m=1, k=[], lbnd=0, scl=1): """ Integrate a Legendre series. Returns a Legendre series that is the Legendre series `cs`, integrated `m` times from `lbnd` to `x`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in... |
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667, 0.00625 ]) | array([ 1.66666667e-02, -1.78571429e-02, 4.76190476e-02, -1.73472348e-18, 1.90476190e-02, 9.52380952e-03]) | def legint(cs, m=1, k=[], lbnd=0, scl=1): """ Integrate a Legendre series. Returns a Legendre series that is the Legendre series `cs`, integrated `m` times from `lbnd` to `x`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in... |
array([ 3.5, -0.5, 0.5, 0.5]) >>> L.legint(cs,lbnd=-2) array([ 8.5, -0.5, 0.5, 0.5]) >>> L.legint(cs,scl=-2) array([-1., 1., -1., -1.]) | array([ 3.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(cs, lbnd=-2) array([ 7.33333333, 0.4 , 0.66666667, 0.6 ]) >>> L.legint(cs, scl=2) array([ 0.66666667, 0.8 , 1.33333333, 1.2 ]) | def legint(cs, m=1, k=[], lbnd=0, scl=1): """ Integrate a Legendre series. Returns a Legendre series that is the Legendre series `cs`, integrated `m` times from `lbnd` to `x`. At each iteration the resulting series is **multiplied** by `scl` and an integration constant, `k`, is added. The scaling factor is for use in... |
1-d array of Chebyshev coefficients ordered from low to high. | 1-d array of Legendre coefficients ordered from low to high. | def legval(x, cs): """Evaluate a Legendre series. If `cs` is of length `n`, this function returns : ``p(x) = cs[0]*P_0(x) + cs[1]*P_1(x) + ... + cs[n-1]*P_{n-1}(x)`` If x is a sequence or array then p(x) will have the same shape as x. If r is a ring_like object that supports multiplication and addition by the values... |
Compute the roots of a Chebyshev series. | Compute the roots of a Legendre series. | def legroots(cs): """ Compute the roots of a Chebyshev series. Return the roots (a.k.a "zeros") of the Legendre series represented by `cs`, which is the sequence of the C-series' coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the Legendre series ``P_0 + 2*P_1 + 3*P_2``. Parameters --------... |
`cs`, which is the sequence of the C-series' coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the Legendre series ``P_0 + 2*P_1 + 3*P_2``. | `cs`, which is the sequence of coefficients from lowest order "term" to highest, e.g., [1,2,3] is the series ``L_0 + 2*L_1 + 3*L_2``. | def legroots(cs): """ Compute the roots of a Chebyshev series. Return the roots (a.k.a "zeros") of the Legendre series represented by `cs`, which is the sequence of the C-series' coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the Legendre series ``P_0 + 2*P_1 + 3*P_2``. Parameters --------... |
>>> import numpy.polynomial.Legendre as L >>> P.polyroots((-1,1,-1,1)) array([ -4.99600361e-16-1.j, -4.99600361e-16+1.j, 1.00000e+00+0.j]) >>> L.legroots((-1,1,-1,1)) array([ -5.00000000e-01, 2.60860684e-17, 1.00000000e+00]) | >>> P.polyroots((1, 2, 3, 4)) array([-0.60582959+0.j , -0.07208521-0.63832674j, -0.07208521+0.63832674j]) >>> P.legroots((1, 2, 3, 4)) array([-0.85099543, -0.11407192, 0.51506735]) | def legroots(cs): """ Compute the roots of a Chebyshev series. Return the roots (a.k.a "zeros") of the Legendre series represented by `cs`, which is the sequence of the C-series' coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the Legendre series ``P_0 + 2*P_1 + 3*P_2``. Parameters --------... |
except: raise 'sign2map: expected complex number `(r,i)\' but got `%s\' as initial value of %s.'%(init,`a`) | except: raise ValueError('sign2map: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a)) | def getinit(a,var): if isstring(var): init,showinit='""',"''" else: init,showinit='','' if hasinitvalue(var): init=var['='] showinit=init if iscomplex(var) or iscomplexarray(var): ret={} try: v = var["="] if ',' in v: ret['init.r'],ret['init.i']=markoutercomma(v[1:-1]).split('@,@') else: v = eval(v,{},{}) ret['init.r'... |
self.failIf(len(deps) > 1, | self.assertFalse(len(deps) > 1, | def test_lapack(self): f = FindDependenciesLdd() deps = f.grep_dependencies(lapack_lite.__file__, asbytes_nested(['libg2c', 'libgfortran'])) self.failIf(len(deps) > 1, |
"Cannot compiler 'Python.h'. Perhaps you need to "\ | "Cannot compile 'Python.h'. Perhaps you need to "\ | def check_types(config_cmd, ext, build_dir): private_defines = [] public_defines = [] # Expected size (in number of bytes) for each type. This is an # optimization: those are only hints, and an exhaustive search for the size # is done if the hints are wrong. expected = {} expected['short'] = [2] expected['int'] = [4] ... |
return (a.size, [0, -1]) unmasked = np.flatnonzero(~m) if len(unmasked) == 0: return None | return slice(0, a.size, None) i = 0 | def flatnotmasked_contiguous(a): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of slices (start index, end index). See Also -------- flatnotmasked_edges, notmasked_contiguous, notmasked_e... |
for (k, group) in itertools.groupby(enumerate(unmasked), lambda (i, x):i - x): tmp = np.array([g[1] for g in group], int) result.append(slice(tmp[0], tmp[-1])) result.sort() | for (k, g) in itertools.groupby(m.ravel()): n = len(list(g)) if not k: result.append(slice(i, i + n)) i += n | def flatnotmasked_contiguous(a): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : narray The input array. Returns ------- slice_list : list A sorted sequence of slices (start index, end index). See Also -------- flatnotmasked_edges, notmasked_contiguous, notmasked_e... |
result.append(flatnotmasked_contiguous(a[idx])) | result.append(flatnotmasked_contiguous(a[idx]) or None) | def notmasked_contiguous(a, axis=None): """ Find contiguous unmasked data in a masked array along the given axis. Parameters ---------- a : array_like The input array. axis : int, optional Axis along which to perform the operation. If None (default), applies to a flattened version of the array. Returns ------- endpoi... |
def append_fields(base, names, data=None, dtypes=None, | def append_fields(base, names, data, dtypes=None, | 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` ... |
dtypes : sequence of datatypes | dtypes : sequence of datatypes, optional | 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` ... |
err_msg = "The number of arrays does not match the number of names" raise ValueError(err_msg) | msg = "The number of arrays does not match the number of names" raise ValueError(msg) | 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` ... |
if not hasattr(dtypes, '__iter__'): | if not isinstance(dtypes, (tuple, list)): | 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` ... |
msg = "The dtypes argument must be None, "\ "a single dtype or a list." | msg = "The dtypes argument must be None, a dtype, or a list." | 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` ... |
def prep_simple(simple_type, typestr): | def prep_simple(simple_type, dtype): | def prep_simple(simple_type, typestr): """Given a ctypes simple type, construct and attach an __array_interface__ property to it if it does not yet have one. """ try: simple_type.__array_interface__ except AttributeError: pass else: return |
typestr = _dtype(dtype).str | def prep_simple(simple_type, typestr): """Given a ctypes simple type, construct and attach an __array_interface__ property to it if it does not yet have one. """ try: simple_type.__array_interface__ except AttributeError: pass else: return | |
if sys.byteorder == "little": TYPESTR = "<%c%d" else: TYPESTR = ">%c%d" | def __array_interface__(self): return {'descr': [('', typestr)], '__ref': self, 'strides': None, 'shape': (), 'version': 3, 'typestr': typestr, 'data': (ct.addressof(self), False), } | |
prep_simple(tp, TYPESTR % (code, ct.sizeof(tp))) | prep_simple(tp, "%c%d" % (code, ct.sizeof(tp))) | def __array_interface__(self): return {'descr': [('', typestr)], '__ref': self, 'strides': None, 'shape': (), 'version': 3, 'typestr': typestr, 'data': (ct.addressof(self), False), } |
def relevance_sort(a, b): dr = relevance(b, *cache[b]) - relevance(a, *cache[a]) if dr != 0: return dr else: return cmp(a, b) found.sort(relevance_sort) | def relevance_value(a): return relevance(a, *cache[a]) found.sort(key=relevance_value) | def relevance_sort(a, b): dr = relevance(b, *cache[b]) - relevance(a, *cache[a]) if dr != 0: return dr else: return cmp(a, b) |
return open(f, mode=mode, encoding='iso-8859-1') | return open(filename, mode=mode, encoding='iso-8859-1') | def open_latin1(filename, mode='r'): return open(f, mode=mode, encoding='iso-8859-1') |
defdict['divide'] = defdict['true_divide'] | del defdict['divide'] | def english_upper(s): """ Apply English case rules to convert ASCII strings to all upper case. This is an internal utility function to replace calls to str.upper() such that we can avoid changing behavior with changing locales. In particular, Turkish has distinct dotted and dotless variants of the Latin letter "I" in ... |
g = GzipFile(fileobj=f.fileobj) g.name = f.name g.mode = f.mode f = g | try: name = f.name except AttributeError: name = f.filename mode = f.mode f = GzipFile(fileobj=f.fileobj, filename=name) f.mode = mode | def tell(self): return self.offset |
'initializes x; see ' in pydoc.getdoc(obj.__init__)): | (not hasattr(obj, '__init__') or 'initializes x; see ' in pydoc.getdoc(obj.__init__))): | def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and 'initializes x; see ' in pydoc.getdoc(obj.__init__)): return '', '' if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__... |
('numpy','site.cfg.example')) | ('numpy','site.cfg.example'), ('numpy/tools', 'tools/py3tool.py')) | def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('numpy'... |
nameargspattern=re.compile(r'\s*(?P<name>\b[\w$]+\b)\s*(@\(@\s*(?P<args>[\w\s,]*)\s*@\)@|)\s*(result(\s*@\(@\s*(?P<result>\b[\w$]+\b)\s*@\)@|))*\s*\Z',re.I) | nameargspattern=re.compile(r'\s*(?P<name>\b[\w$]+\b)\s*(@\(@\s*(?P<args>[\w\s,]*)\s*@\)@|)\s*((result(\s*@\(@\s*(?P<result>\b[\w$]+\b)\s*@\)@|))|(bind\s*@\(@\s*(?P<bind>.*)\s*@\)@))*\s*\Z',re.I) | def appenddecl(decl,decl2,force=1): if not decl: decl={} if not decl2: return decl if decl is decl2: return decl for k in decl2.keys(): if k=='typespec': if force or k not in decl: decl[k]=decl2[k] elif k=='attrspec': for l in decl2[k]: decl=setattrspec(decl,l,force) elif k=='kindselector': decl=setkindselector(decl,de... |
if m1: return m1.group('name'),m1.group('args'),m1.group('result') | if m1: return m1.group('name'),m1.group('args'),m1.group('result'), m1.group('bind') | def _resolvenameargspattern(line): line = markouterparen(line) m1=nameargspattern.match(line) if m1: return m1.group('name'),m1.group('args'),m1.group('result') m1=callnameargspattern.match(line) if m1: return m1.group('name'),m1.group('args'),None return None,[],None |
if m1: return m1.group('name'),m1.group('args'),None return None,[],None | if m1: return m1.group('name'),m1.group('args'),None, None return None,[],None, None | def _resolvenameargspattern(line): line = markouterparen(line) m1=nameargspattern.match(line) if m1: return m1.group('name'),m1.group('args'),m1.group('result') m1=callnameargspattern.match(line) if m1: return m1.group('name'),m1.group('args'),None return None,[],None |
name,args,result = _resolvenameargspattern(m.group('after')) | name,args,result,bind = _resolvenameargspattern(m.group('after')) | def analyzeline(m,case,line): global groupcounter,groupname,groupcache,grouplist,filepositiontext,\ currentfilename,f77modulename,neededinterface,neededmodule,expectbegin,\ gotnextfile,previous_context block=m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin','call','... |
needinterface=1 | if block != 'interface': needinterface=1 | def analyzeline(m,case,line): global groupcounter,groupname,groupcache,grouplist,filepositiontext,\ currentfilename,f77modulename,neededinterface,neededmodule,expectbegin,\ gotnextfile,previous_context block=m.group('this') if case != 'multiline': previous_context = None if expectbegin and case not in ['begin','call','... |
if errorStatus & numpy.FPE_INVALID: | if errorStatus & np.FPE_INVALID: | def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = np.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) if e... |
if errorStatus & numpy.FPE_DIVIDEBYZERO: | if errorStatus & np.FPE_DIVIDEBYZERO: | def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = np.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) if e... |
if errorStatus & numpy.FPE_OVERFLOW: | if errorStatus & np.FPE_OVERFLOW: | def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = np.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) if e... |
if errorStatus & numpy.FPE_UNDERFLOW: | if errorStatus & np.FPE_UNDERFLOW: | def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" modes = np.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) if e... |
if isinstance(obj, (str, _unicode)): | if isinstance(obj, (_bytes, _unicode)): | def array(obj, itemsize=None, copy=True, unicode=None, order=None): """ Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in :mod:`numpy.char <numpy.co... |
obj = str(obj) | obj = _bytes(obj) | def array(obj, itemsize=None, copy=True, unicode=None, order=None): """ Create a `chararray`. .. note:: This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in :mod:`numpy.char <numpy.co... |
try: import Numeric has_Numeric = 1 except ImportError: print 'Failed to import Numeric:',sys.exc_value has_Numeric = 0 try: import numarray has_numarray = 1 except ImportError: print 'Failed to import numarray:',sys.exc_value has_numarray = 0 | def run(): _path = os.getcwd() os.chdir(tempfile.gettempdir()) print '------' print 'os.name=%r' % (os.name) print '------' print 'sys.platform=%r' % (sys.platform) print '------' print 'sys.version:' print sys.version print '------' print 'sys.prefix:' print sys.prefix print '------' print 'sys.path=%r' % (':'.join(sy... | |
import f2py2e | from numpy.f2py import f2py2e | def run(): _path = os.getcwd() os.chdir(tempfile.gettempdir()) print '------' print 'os.name=%r' % (os.name) print '------' print 'sys.platform=%r' % (sys.platform) print '------' print 'sys.version:' print sys.version print '------' print 'sys.prefix:' print sys.prefix print '------' print 'sys.path=%r' % (':'.join(sy... |
if has_Numeric: try: print 'Found Numeric version %r in %s' % \ (Numeric.__version__,Numeric.__file__) except Exception,msg: print 'error:',msg print '------' if has_numarray: try: print 'Found numarray version %r in %s' % \ (numarray.__version__,numarray.__file__) except Exception,msg: print 'error:',msg print '------... | def run(): _path = os.getcwd() os.chdir(tempfile.gettempdir()) print '------' print 'os.name=%r' % (os.name) print '------' print 'sys.platform=%r' % (sys.platform) print '------' print 'sys.version:' print sys.version print '------' print 'sys.prefix:' print sys.prefix print '------' print 'sys.path=%r' % (':'.join(sy... | |
fh = file(fname, 'U') | fh = open(fname, 'U') | def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False): """ Load data from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : file or str File or filename to read. If the filename extension is ``.gz... |
except AttributeError: | except (TypeError, AttributeError): | def __array_finalize__(self, obj): """Finalizes the masked array. """ # Get main attributes ......... self._update_from(obj) if isinstance(obj, ndarray): odtype = obj.dtype if odtype.names: _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype)) else: _mask = getattr(obj, '_mask', nomask) else: _mask = nomask ... |
def savetxt(fname, X, fmt='%.18e', delimiter=' '): | def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n'): | def savetxt(fname, X, fmt='%.18e', delimiter=' '): """ Save an array to a text file. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a... |
fh = file(fname, 'w') | if sys.version_info[0] >= 3: fh = file(fname, 'wb') else: fh = file(fname, 'w') | def savetxt(fname, X, fmt='%.18e', delimiter=' '): """ Save an array to a text file. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a... |
format = delimiter.join(fmt) | format = asstr(delimiter).join(map(asstr, fmt)) | def savetxt(fname, X, fmt='%.18e', delimiter=' '): """ Save an array to a text file. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a... |
fh.write(format % tuple(row) + '\n') | fh.write(asbytes(format % tuple(row) + newline)) | def savetxt(fname, X, fmt='%.18e', delimiter=' '): """ Save an array to a text file. Parameters ---------- fname : filename or file handle If the filename ends in ``.gz``, the file is automatically saved in compressed gzip format. `loadtxt` understands gzipped files transparently. X : array_like Data to be saved to a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.