rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
raise RuntimeError | raise RuntimeError, msg % (_, one.dtype) | def __init__(self, float_conv=float,int_conv=int, float_to_float=float, float_to_str = lambda v:'%24.16e' % v, title = 'Python floating point number'): """ float_conv - convert integer to float (array) int_conv - convert float (array) to integer float_to_float - convert float array to float float_to_str - convert arr... |
except ValueError: | except (AttributeError, ValueError): | def CCompiler_customize(self, dist, need_cxx=0): # See FCompiler.customize for suggested usage. log.info('customize %s' % (self.__class__.__name__)) customize_compiler(self) if need_cxx: # In general, distutils uses -Wstrict-prototypes, but this option is # not valid for C++ code, only for C. Remove it if it's there t... |
self.parent_path = eval('__path__',frame.f_globals,frame.f_locals) | parent_path = eval('__path__',frame.f_globals,frame.f_locals) if isinstance(parent_path, str): parent_path = [parent_path] self.parent_path = parent_path | def __init__(self, verbose=False): """ Manages loading packages. """ |
lengths = [len(name)-name.find('.')-1 for (name,title) in titles] | lengths = [len(name)-name.find('.')-1 for (name,title) in titles]+[0] | def _format_titles(self,titles,colsep='---'): display_window_width = 70 # How to determine the correct value in runtime?? lengths = [len(name)-name.find('.')-1 for (name,title) in titles] max_length = max(lengths) lines = [] for (name,title) in titles: name = name[name.find('.')+1:] w = max_length - len(name) words = t... |
objects or numpy arrays as inputs and returns a | of objects or numpy arrays as inputs and returns a | def _get_nargs(obj): if not callable(obj): raise TypeError, "Object is not callable." if hasattr(obj,'func_code'): fcode = obj.func_code nargs = fcode.co_argcount if obj.func_defaults is not None: ndefaults = len(obj.func_defaults) else: ndefaults = 0 if isinstance(obj, types.MethodType): nargs -= 1 return nargs, ndefa... |
raise ValueError, "output types must be a string" for char in self.otypes: if char not in typecodes['All']: raise ValueError, "invalid typecode specified" | raise ValueError, "output types must be a string of typecode characters or a list of data-types" | def __init__(self, pyfunc, otypes='', doc=None): self.thefunc = pyfunc self.ufunc = None nin, ndefault = _get_nargs(pyfunc) if nin == 0 and ndefault == 0: self.nin = None self.nin_wo_defaults = None else: self.nin = nin self.nin_wo_defaults = nin - ndefault self.nout = None if doc is None: self.__doc__ = pyfunc.__doc__... |
otypes = [] for k in range(self.nout): otypes.append(asarray(theout[k]).dtype.char) self.otypes = ''.join(otypes) | if self.otypes == '': otypes = [] for k in range(self.nout): otypes.append(asarray(theout[k]).dtype.char) self.otypes = ''.join(otypes) | def __call__(self, *args): # get number of outputs and output types by calling # the function on the first entries of args nargs = len(args) if self.nin: if (nargs > self.nin) or (nargs < self.nin_wo_defaults): raise ValueError, "mismatch between python function inputs"\ " and received arguments" |
v = array(vr,Complex) | v = array(vr, w.dtype) | def eig(a): """eig(a) returns u,v where u is the eigenvalues and |
args.extend(['-faltivec','-framework','Accelerate']) | args.extend(['-faltivec']) | def calc_info(self): |
args.extend(['-faltivec','-framework','vecLib']) | args.extend(['-faltivec']) | def calc_info(self): |
args.extend(['-faltivec','-framework','Accelerate']) | args.extend(['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers', ]) | def calc_info(self): |
args.extend(['-faltivec','-framework','vecLib']) | args.extend(['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers', ]) | def calc_info(self): |
return masked_array(self._data.real, mask=self._mask.ravel(), | return masked_array(self._data.real, mask=self._mask, | def _get_real(self): "Get the real part of a complex array." if self._mask is nomask: return masked_array(self._data.real, mask=nomask, fill_value = self.fill_value()) else: return masked_array(self._data.real, mask=self._mask.ravel(), fill_value = self.fill_value()) |
return masked_array(self._data.imag, mask=self._mask.ravel(), | return masked_array(self._data.imag, mask=self._mask, | def _get_imaginary(self): "Get the imaginary part of a complex array." if self._mask is nomask: return masked_array(self._data.imag, mask=nomask, fill_value = self.fill_value()) else: return masked_array(self._data.imag, mask=self._mask.ravel(), fill_value = self.fill_value()) |
s = f(os.path.join(self.build_src,d)) | s = f(build_dir) | def build_data_files_sources(self): if not self.data_files: return log.info('building data_files sources') from numpy.distutils.misc_util import get_data_files new_data_files = [] for data in self.data_files: if isinstance(data,str): new_data_files.append(data) elif isinstance(data,tuple): d,files = data funcs = filter... |
target = os.path.join(*([self.build_src]+\ package.split('.')+\ [module_base + '.py'])) | target = os.path.join(build_dir, module_base + '.py') | def build_py_modules_sources(self): if not self.py_modules: return log.info('building py_modules sources') new_py_modules = [] for source in self.py_modules: if type(source) is type(()) and len(source)==3: package, module_base, source = source if callable(source): target = os.path.join(*([self.build_src]+\ package.spli... |
return array2string(a, max_line_width, precision, suppress_small, ' ', "") | return array2string(a, max_line_width, precision, suppress_small, ' ', "", str) | def array_str(a, max_line_width=None, precision=None, suppress_small=None): return array2string(a, max_line_width, precision, suppress_small, ' ', "") |
opt = FCompiler.get_library_dirs(self) | opt = FCompiler.get_libraries(self) | def get_libraries(self): opt = FCompiler.get_library_dirs(self) d = self.get_libgcc_dir() if d is not None: for g2c in ['g2c-pic','g2c']: f = self.static_lib_format % (g2c, self.static_lib_extension) if os.path.isfile(os.path.join(d,f)): break else: g2c = 'g2c' if sys.platform=='win32': opt.extend(['gcc',g2c]) else: op... |
return "A record with fields: %s" % (','.join(self.fields.keys()),) | return self.__str__() | def __repr__(self): return "A record with fields: %s" % (','.join(self.fields.keys()),) |
return self.data[:] | fdict = self.fields names = fdict.keys() all = [] for name in names: item = fdict[name] if (len(item) > 3) and item[2] == name: continue all.append(item) all.sort(lambda x,y: cmp(x[1],y[1])) outlist = [self.getfield(item[0], item[1]) for item in all] return str(outlist) | def __str__(self): return self.data[:] |
self.libraries = ['fio', 'fmath', 'f90math', 'COMDLG32'] | self.libraries = ['fio', 'f90math', 'fmath', 'COMDLG32'] | def __init__(self, fc=None, f90c=None, verbose=0): fortran_compiler_base.__init__(self, verbose=verbose) |
y = _nx.arange(0, num) * step + start if endpoint: y[-1] = stop | y = _nx.arange(0, num) * step + start | def linspace(start, stop, num=50, endpoint=True, retstep=False): """Return evenly spaced numbers. Return num evenly spaced samples from start to stop. If endpoint is True, the last sample is stop. If retstep is True then return the step value used. """ num = int(num) if num <= 0: return array([], float) if endpoint: ... |
def _format_titles(self,titles): | def _format_titles(self,titles,colsep='---'): display_window_width = 70 | def _format_titles(self,titles): lengths = [len(name)-name.find('.')-1 for (name,title) in titles] max_length = max(lengths) lines = [] for (name,title) in titles: name = name[name.find('.')+1:] w = max_length - len(name) lines.append('%s%s --- %s' % (name, w*' ', title)) return '\n'.join(lines) |
lines.append('%s%s --- %s' % (name, w*' ', title)) | words = title.split() line = '%s%s %s' % (name,w*' ',colsep) tab = len(line) * ' ' while words: word = words.pop(0) if len(line)+len(word)>display_window_width: lines.append(line) line = tab line += ' ' + word else: lines.append(line) | def _format_titles(self,titles): lengths = [len(name)-name.find('.')-1 for (name,title) in titles] max_length = max(lengths) lines = [] for (name,title) in titles: name = name[name.find('.')+1:] w = max_length - len(name) lines.append('%s%s --- %s' % (name, w*' ', title)) return '\n'.join(lines) |
return self._format_titles(titles) +\ '\n [*] - using a package requires explicit import' | if global_symbols: symbols.append((package_name,', '.join(global_symbols))) retstr = self._format_titles(titles) +\ '\n [*] - using a package requires explicit import (see pkgload)' if symbols: retstr += """\n\nGlobal symbols from subpackages"""\ """\n-------------------------------\n""" +\ self._format_titles(symb... | def get_pkgdocs(self): """ Return documentation summary of subpackages. """ import sys self.info_modules = {} self._init_info_modules(None) |
revdict = {} | def bitname(obj): """Return a bit-width name for a given type object""" name = obj.__name__[:-6] base = '' char = '' try: info = typeinfo[name.upper()] assert(info[-1] == obj) # sanity check bits = info[2] except KeyError: # bit-width name base, bits = _evalname(name) char = base[0] if name == 'bool': char = 'b'... | |
if isinstance(typeinfo[a], type(())): | if isinstance(typeinfo[a], tuple): | def _add_types(): for a in typeinfo.keys(): name = a.lower() if isinstance(typeinfo[a], type(())): typeobj = typeinfo[a][-1] # define C-name and insert typenum and typechar references also allTypes[name] = typeobj typeDict[name] = typeobj typeDict[typeinfo[a][0]] = typeobj typeDict[typeinfo[a][1]] = typeobj # insert ... |
base, bit, char = bitname(typeobj) revdict[typeobj] = (typeinfo[a][:-1], (base, bit, char), a) if base != '': myname = "%s%d" % (base, bit) if (name != 'longdouble' and name != 'clongdouble') or \ myname not in allTypes.keys(): allTypes[myname] = typeobj typeDict[myname] = typeobj if base == 'uint': tmpstr = 'UInt%d' %... | def _add_types(): for a in typeinfo.keys(): name = a.lower() if isinstance(typeinfo[a], type(())): typeobj = typeinfo[a][-1] # define C-name and insert typenum and typechar references also allTypes[name] = typeobj typeDict[name] = typeobj typeDict[typeinfo[a][0]] = typeobj typeDict[typeinfo[a][1]] = typeobj # insert ... | |
dir_env_var = 'DJBFFTW' | dir_env_var = 'DJBFFT' | def calc_info(self): lib_dirs = self.get_lib_dirs() incl_dirs = self.get_include_dirs() incl_dir = None libs = self.get_libs(self.section+'_libs', self.libs) info = None for d in lib_dirs: r = self.check_libs(d,libs) if r is not None: info = r break if info is not None: flag = 0 for d in incl_dirs: if len(combine_paths... |
return res | return copy.deepcopy(res) | def get_info(self,notfound_action=0): """ Return a dictonary with items that are compatible with numpy.distutils.setup keyword arguments. """ flag = 0 if not self.has_info(): flag = 1 if self.verbosity>0: print self.__class__.__name__ + ':' if hasattr(self, 'calc_info'): self.calc_info() if notfound_action: if not self... |
def __init__(self, filename, flag='c'): import dumbdbm_patched Shelf.__init__(self, dumbdbm_patched.open(filename, flag)) | def _update(self): import string self._index = {} try: f = _open(self._dirfile) except IOError: pass else: while 1: line = string.rstrip(f.readline()) if not line: break key, (pos, siz) = eval(line) self._index[key] = (pos, siz) f.close() | def __init__(self, filename, flag='c'): import dumbdbm_patched Shelf.__init__(self, dumbdbm_patched.open(filename, flag)) |
compressed = self.dict[key] try: r = zlib.decompress(compressed) except zlib.error: r = compressed return cPickle.loads(r) | pos, siz = self._index[key] f = _open(self._datfile, 'rb') f.seek(pos) dat = f.read(siz) f.close() return dat def _addval(self, val): f = _open(self._datfile, 'rb+') f.seek(0, 2) pos = f.tell() npos = ((pos + _BLOCKSIZE - 1) / _BLOCKSIZE) * _BLOCKSIZE f.write('\0'*(npos-pos)) pos = npos | def __getitem__(self, key): compressed = self.dict[key] try: r = zlib.decompress(compressed) except zlib.error: r = compressed return cPickle.loads(r) |
def __setitem__(self, key, value): s = cPickle.dumps(value,1) self.dict[key] = zlib.compress(s) | f.write(val) f.close() return (pos, len(val)) def _setval(self, pos, val): f = _open(self._datfile, 'rb+') f.seek(pos) f.write(val) f.close() return (pos, len(val)) def _addkey(self, key, (pos, siz)): self._index[key] = (pos, siz) f = _open(self._dirfile, 'a') f.write("%s, (%s, %s)\n" % (`key`, `pos`, `siz`)) f.close... | def __setitem__(self, key, value): s = cPickle.dumps(value,1) self.dict[key] = zlib.compress(s) |
throw throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); | throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); | def check_exceptions(self): a = 3 code = """ if (a < 2) throw throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = Py::new_reference_to(Py::Int(a+1)); """ result = inline_tools.inline(code,['a']) assert(result == 4) try: a = 1 result = inline_tools.inline(code,['a']) assert(1)... |
% (source, process_str(''.join(lines)))) | % (sourcefile, process_str(''.join(lines)))) | def process_file(source): lines = resolve_includes(source) return ('#line 1 "%s"\n%s' % (source, process_str(''.join(lines)))) |
print ' !! FAILURE building tests for ', mstr(module) | print ' !! FAILURE building tests for ', mstr(test_module) | def _get_suite_list(self, test_module, level, module_name='__main__'): mstr = self._module_str if hasattr(test_module,'test_suite'): # Using old styled test suite try: total_suite = test_module.test_suite(level) return total_suite._tests except: print ' !! FAILURE building tests for ', mstr(module) print ' ', outpu... |
return 1 | return True | def _is_64bit(self): if self.is_Alpha(): return 1 if self.info[0].get('clflush size','')=='64': return 1 if self.info[0]['uname_m']=='x86_64': return 1 if self.info[0].get('arch','')=='IA-64': return 1 return 0 |
return 1 if self.info[0]['uname_m']=='x86_64': return 1 | return True if self.info[0].get('uname_m','')=='x86_64': return True | def _is_64bit(self): if self.is_Alpha(): return 1 if self.info[0].get('clflush size','')=='64': return 1 if self.info[0]['uname_m']=='x86_64': return 1 if self.info[0].get('arch','')=='IA-64': return 1 return 0 |
return 1 return 0 | return True return False | def _is_64bit(self): if self.is_Alpha(): return 1 if self.info[0].get('clflush size','')=='64': return 1 if self.info[0]['uname_m']=='x86_64': return 1 if self.info[0].get('arch','')=='IA-64': return 1 return 0 |
scale = pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual))))) | scale = float(pow(10,math.floor(math.log10(0.5*(abs(desired)+abs(actual)))))) | def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1): """ Raise an assertion if two items are not equal. I think this should be part of unittest.py Approximately equal is defined as the number of significant digits correct """ msg = '\nItems are not equal to %d significant digits:\n' % significan... |
for obj, (src, ext) in build.items(): self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) | if isinstance(self, FCompiler): from distutils.sysconfig import python_build objects = self.object_filenames(sources, strip_dir=python_build, output_dir=output_dir) objects_to_build = build.keys() for obj in objects: if obj in objects_to_build: src, ext = build[obj] self._compile(obj, src, ext, cc_args, extra_postargs,... | def CCompiler_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): if not sources: return [] from fcompiler import FCompiler if isinstance(self, FCompiler): display = [] for fc in ['f77','f90','fix']: fcomp = getattr(self,'compiler_'+fc... |
return sqrt(x) | return _nx.sqrt(x) | def sqrt(x): x = _fix_real_lt_zero(x) return sqrt(x) |
return log(x) | return _nx.log(x) | def log(x): x = _fix_real_lt_zero(x) return log(x) |
return log10(x) | return _nx.log10(x) | def log10(x): x = _fix_real_lt_zero(x) return log10(x) |
return power(x, p) | return _nx.power(x, p) | def power(x, p): x = _fix_real_lt_zero(x) return power(x, p) |
% (source,`base`,`ext.name`))) | % (source,`base`,`ext_name`))) | def f2py_sources (self, sources, ext): |
flib = {'sources':[], 'define_macros':[], 'undef_macros':[], 'include_dirs':[], } | flib = {} | def fortran_sources_to_flib(self, ext): """ Extract fortran files from ext.sources and append them to fortran_libraries item having the same name as ext. """ sources = [] f_files = [] |
flib['sources'].extend(f_files) flib['define_macros'].extend(ext.define_macros) flib['undef_macros'].extend(ext.undef_macros) flib['include_dirs'].extend(ext.include_dirs) | flib.setdefault('sources',[]).extend(f_files) flib.setdefault('define_macros',[]).extend(ext.define_macros) flib.setdefault('undef_macros',[]).extend(ext.undef_macros) flib.setdefault('include_dirs',[]).extend(ext.include_dirs) | def fortran_sources_to_flib(self, ext): """ Extract fortran files from ext.sources and append them to fortran_libraries item having the same name as ext. """ sources = [] f_files = [] |
ret = self.ufunc(*args) c = self.otypes[0] try: return ret.astype(c) except AttributeError: return array(ret).astype(c) | return asarray(self.ufunc(*args)).astype(self.otypes[0]) | def __call__(self, *args): # get number of outputs and output types by calling # the function on the first entries of args nargs = len(args) if (nargs > self.nin) or (nargs < self.nin_wo_defaults): raise ValueError, "mismatch between python function inputs"\ " and received arguments" if self.nout is None or self.otype... |
ret = [] for x, c in zip(self.ufunc(*args), self.otypes): try: ret.append(x.astype(c)) except AttributeError: ret.append(array(x).astype(c)) return tuple(ret) | return tuple([asarray(x).astype(c) \ for x, c in zip(self.ufunc(*args), self.otypes)]) | def __call__(self, *args): # get number of outputs and output types by calling # the function on the first entries of args nargs = len(args) if (nargs > self.nin) or (nargs < self.nin_wo_defaults): raise ValueError, "mismatch between python function inputs"\ " and received arguments" if self.nout is None or self.otype... |
def __float__(self): return float(self.array) | def __array__(self,t=None): if t: return self.array.astype(t) return self.array | |
def _scalarfunc(a, func): if len(a.shape) == 0: return func(a[0]) | def _scalarfunc(self, func): if len(self.shape) == 0: return func(self[0]) | def _scalarfunc(a, func): if len(a.shape) == 0: return func(a[0]) else: raise TypeError, "only rank-0 arrays can be converted to Python scalars." |
import numpy | def __getattr__(self,attr): return self.array.__getattribute__(attr) | |
newdata = re.sub("\n", "\r\n", data) | newdata = re.sub("\r\n", "\n", data) newdata = re.sub("\n", "\r\n", newdata) | def unix2dos(file): "Replace LF with CRLF in argument files. Print names of changed files." if os.path.isdir(file): print file, "Directory!" return data = open(file, "rb").read() if '\0' in data: print file, "Binary!" return newdata = re.sub("\n", "\r\n", data) if newdata != data: print 'unix2dos:', file f = open(fi... |
if base[-3:] == 'int': continue | if base[-3:] == 'int' or char[0] in 'ui': continue | def _add_aliases(): for a in typeinfo.keys(): name = a.lower() if not isinstance(typeinfo[a], tuple): continue typeobj = typeinfo[a][-1] # insert bit-width version for this class (if relevant) base, bit, char = bitname(typeobj) if base[-3:] == 'int': continue if base != '': myname = "%s%d" % (base, bit) if (name != 'lo... |
if not all(isfinite(x)): | if not all(_nx.isfinite(x)): | def asarray_chkfinite(x): """Like asarray except it checks to be sure no NaNs or Infs are present. """ x = asarray(x) if not all(isfinite(x)): raise ValueError, "Array must not contain infs or nans." return x |
blitz_tools.blitz(expr,arg_dict,{},verbose) | blitz_tools.blitz(expr,arg_dict,{},verbose=0) | def generic_test(self,expr,arg_dict,type,size,mod_location): clean_result = array(arg_dict['result'],copy=1) t1 = time.time() exec expr in globals(),arg_dict t2 = time.time() standard = t2 - t1 desired = arg_dict['result'] arg_dict['result'] = clean_result t1 = time.time() old_env = os.environ.get('PYTHONCOMPILED','') ... |
num_to_c_types[type(1)] = 'int' | num_to_c_types[type(1)] = 'long' | def c_to_py_code(self): # !! Need to dedent returned code. code = """ PyObject* file_to_py(FILE* file, char* name, char* mode) { PyObject* py_obj = NULL; //extern int fclose(FILE *); return (PyObject*) PyFile_FromFile(file, name, mode, fclose); } """ return code |
num_to_c_types[type(1L)] = 'int' | num_to_c_types[type(1L)] = 'longlong' | def c_to_py_code(self): # !! Need to dedent returned code. code = """ PyObject* file_to_py(FILE* file, char* name, char* mode) { PyObject* py_obj = NULL; //extern int fclose(FILE *); return (PyObject*) PyFile_FromFile(file, name, mode, fclose); } """ return code |
self.c_type = 'int' self.return_type = 'int' self.to_c_return = "(int) PyInt_AsLong(py_obj)" | self.c_type = 'long' self.return_type = 'long' self.to_c_return = "PyInt_AsLong(py_obj)" | def init_info(self): scalar_converter.init_info(self) self.type_name = 'int' self.check_func = 'PyInt_Check' self.c_type = 'int' self.return_type = 'int' self.to_c_return = "(int) PyInt_AsLong(py_obj)" self.matching_types = [IntType] |
self.c_type = 'int' self.return_type = 'int' self.to_c_return = "(int) PyLong_AsLong(py_obj)" | self.c_type = 'longlong' self.return_type = 'longlong' self.to_c_return = "(longlong) PyLong_AsLongLong(py_obj)" | def init_info(self): scalar_converter.init_info(self) # !! long to int conversion isn't safe! self.type_name = 'long' self.check_func = 'PyLong_Check' self.c_type = 'int' self.return_type = 'int' self.to_c_return = "(int) PyLong_AsLong(py_obj)" self.matching_types = [LongType] |
print 'c speed:', c | print 'CXX speed:', c | def time_it(m,n): import time seq = ['aadasdf'] * n t1 = time.time() for i in range(m): result = map(len,seq) t2 = time.time() py = t2 - t1 print 'python speed:', py #load cache result = c_list_map(len,seq) t1 = time.time() for i in range(m): result = c_list_map(len,seq) t2 = time.time() c = t2-t1 print 'c speed:', c ... |
format_function = lambda x, f = format: format % x | format_function = lambda x: format % x | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
format_function = lambda x, f = format: _formatInteger(x, f) | format_function = lambda x: _formatInteger(x, format) | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
format = _floatFormat(data, precision, suppress_small) format_function = lambda x, f = format: _formatFloat(x, f) | if issubclass(dtype, _nt.longfloat): format_function = str else: format = _floatFormat(data, precision, suppress_small) format_function = lambda x: _formatFloat(x, format) | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
real_format = _floatFormat( data.real, precision, suppress_small, sign=0) imag_format = _floatFormat( data.imag, precision, suppress_small, sign=1) format_function = lambda x, f1 = real_format, f2 = imag_format: \ _formatComplex(x, f1, f2) | if issubclass(dtype, _nt.clongfloat): real_format = imag_format = '%s' else: real_format = _floatFormat( data.real, precision, suppress_small, sign=0) imag_format = _floatFormat( data.imag, precision, suppress_small, sign=1) format_function = lambda x: \ _formatComplex(x, real_format, imag_format) | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
format_function = lambda x, f = format: repr(x) | format_function = lambda x: repr(x) | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
format_function = lambda x, f = format: format % str(x) | format_function = lambda x: format % str(x) | def _array2string(a, max_line_width, precision, suppress_small, separator=' ', prefix=""): if max_line_width is None: max_line_width = _line_width if precision is None: precision = _float_output_precision if suppress_small is None: suppress_small = _float_output_suppress_small if a.size > _summaryThreshhold: summar... |
if mod_name == '__builtin__': | if mod_name == '__main__' and not hasattr('__main__', '__file__'): d = os.path.abspath('.') elif mod_name == '__builtin__': | def get_path(mod_name, parent_path=None): """ Return path of the module. Returned path is relative to parent_path when given, otherwise it is absolute path. """ if mod_name == '__builtin__': #builtin if/then added by Pearu for use in core.run_setup. d = os.path.dirname(os.path.abspath(sys.argv[0])) else: __import__(mo... |
self.failUnlessRaises(OverflowError,N.intp,'0xb72a7008',16) | i_width = N.int_(0).nbytes*2 - 1 N.intp('0x' + 'f'*i_width,16) self.failUnlessRaises(OverflowError,N.intp,'0x' + 'f'*(i_width+1),16) | def check_intp(self,level=rlevel): """Ticket #99""" self.failUnlessRaises(OverflowError,N.intp,'0xb72a7008',16) self.failUnlessRaises(ValueError,N.intp,'0x1',32) assert_equal(255,N.intp('0xFF',16)) assert_equal(1024,N.intp(1024)) |
argv0 = argv[0] if ' ' in argv[0]: argv[0] = '"%s"' % (argv[0]) | argv0 = quote_arg(argv[0]) | def _exec_command( command, use_shell=None, **env ): log.debug('_exec_command(...)') if use_shell is None: use_shell = os.name=='posix' using_command = 0 if use_shell: # We use shell (unless use_shell==0) so that wildcards can be # used. sh = os.environ.get('SHELL','/bin/sh') if type(command) is type([]): argv = [sh,... |
args = (parent_name,) | pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) | def _get_configuration_from_setup_py(self, setup_py, subpackage_name, subpackage_path, parent_name, caller_level = 1): # In case setup_py imports local modules: sys.path.insert(0,os.path.dirname(setup_py)) try: fo_setup_py = open(setup_py, 'U') setup_name = os.path.splitext(os.path.basename(setup_py))[0] n = dot_join(s... |
assert '*' not in subpackage_name,`subpackage_name, subpackage_path,parent_name` | def get_subpackage(self,subpackage_name, subpackage_path=None, parent_name=None, caller_level = 1): """ Return list of subpackage configurations. | |
if not sys.stdout.isatty(): return 0 | if not hasattr(sys.stdout,'isatty') or not sys.stdout.isatty(): return 0 | def terminal_has_colors(): if not sys.stdout.isatty(): return 0 try: import curses curses.setupterm() return (curses.tigetnum("colors") >= 0 and curses.tigetnum("pairs") >= 0 and ((curses.tigetstr("setf") is not None and curses.tigetstr("setb") is not None) or (curses.tigetstr("setaf") is not None and curses.tigetstr("... |
def test_nt(): | def test_nt(**kws): | def test_nt(): pythonexe = get_pythonexe() if 1: ## not (sys.platform=='win32' and os.environ.get('OSTYPE','')=='cygwin'): s,o=exec_command('echo Hello') assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo a%AAA%') assert s==0 and o=='a',(s,o) s,o=exec_command('echo a%AAA%',AAA='Tere') assert s==0 and o=='aTere... |
if not lib.startswtih('msvcr'): | if not lib.startswith('msvcr'): | def _libs_with_msvc_and_fortran(self, c_libraries, c_library_dirs): # Always use system linker when using MSVC compiler. f_lib_dirs = [] for dir in self.fcompiler.library_dirs: # correct path when compiling in Cygwin but with normal Win # Python if dir.startswith('/usr/lib'): s,o = exec_command(['cygpath', '-w', dir], ... |
def assert_array_compare(comparision, x, y, err_msg='', verbose=True, | def assert_array_compare(comparison, x, y, err_msg='', verbose=True, | def assert_array_compare(comparision, x, y, err_msg='', verbose=True, header=''): from numpy.core import asarray x = asarray(x) y = asarray(y) try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), verbose=verb... |
reduced = comparision(x, y).ravel() cond = reduced.all() | val = comparison(x,y) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() | def assert_array_compare(comparision, x, y, err_msg='', verbose=True, header=''): from numpy.core import asarray x = asarray(x) y = asarray(y) try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), verbose=verb... |
match = 100-100.0*reduced.tolist().count(1)/len(reduced) | match = 100-100.0*reduced.count(1)/len(reduced) | def assert_array_compare(comparision, x, y, err_msg='', verbose=True, header=''): from numpy.core import asarray x = asarray(x) y = asarray(y) try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), verbose=verb... |
return NX.array([]) | roots = NX.array([]) | def roots(p): """ Return the roots of the polynomial coefficients in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] """ # If input is scalar, this makes it an array p = atleast_1d(p) if len(p.s... |
attr = getattr(self.__dict__['_ppimport_attr_module'], | module = self.__dict__['_ppimport_attr_module'] if isinstance(module, _ModuleLoader): module = sys.modules[module.__name__] attr = getattr(module, | def _ppimport_attr_getter(self): attr = getattr(self.__dict__['_ppimport_attr_module'], self.__dict__['_ppimport_attr_name']) try: d = attr.__dict__ if d is not None: self.__dict__ = d except AttributeError: pass self.__dict__['_ppimport_attr'] = attr return attr |
return matrix(out) | return asmatrix(out) | def __getitem__(self, index): out = self.arr.__getitem__(index) # Need to swap if slice is on first index retscal = False try: n = len(index) if (n==2): if isinstance(index[0], types.SliceType): if (isscalar(index[1])): sh = out.shape out.shape = (sh[1], sh[0]) else: if (isscalar(index[0])) and (isscalar(index[1])): re... |
return matrix(self.arr.copy()) | return asmatrix(self.arr.copy()) | def copy(self): return matrix(self.arr.copy()) |
return matrix(self.arr.copy()) | return asmatrix(self.arr.copy()) | def __copy__(self): return matrix(self.arr.copy()) |
return matrix(self.arr + other) | return asmatrix(self.arr + other) | def __add__(self, other): return matrix(self.arr + other) |
return matrix(other + self.arr) | return asmatrix(other + self.arr) | def __radd__(self, other): return matrix(other + self.arr) |
return matrix(self.arr - other) | return asmatrix(self.arr - other) | def __sub__(self, other): return matrix(self.arr - other) |
return matrix(other - self.arr) | return asmatrix(other - self.arr) | def __rsub__(self, other): return matrix(other - self.arr) |
return matrix(N.multiply(self.arr, other)) else: return matrix(N.dot(self.arr, other)) | return asmatrix(N.multiply(self.arr, other)) else: return asmatrix(N.dot(self.arr, other)) | def __mul__(self, other): if (isinstance(other, N.ndarray) or isinstance(other, matrix)) \ and other.ndim == 0: return matrix(N.multiply(self.arr, other)) else: return matrix(N.dot(self.arr, other)) |
return matrix(N.multiply(other, self.arr)) else: return matrix(N.dot(other, self.arr)) | return asmatrix(N.multiply(other, self.arr)) else: return asmatrix(N.dot(other, self.arr)) | def __rmul__(self, other): if (isinstance(other, N.ndarray) or isinstance(other, matrix)) \ and other.ndim == 0: return matrix(N.multiply(other, self.arr)) else: return matrix(N.dot(other, self.arr)) |
return matrix(N.divide(self.arr, other)) | return asmatrix(N.divide(self.arr, other)) | def __div__(self, other): try: if other.ndim == 0: return matrix(N.divide(self.arr, other)) else: raise NotImplementedError, "matrix division not yet implemented" except AttributeError: return matrix(N.divide(self.arr, other)) |
return matrix(N.divide(other, self.arr)) | return asmatrix(N.divide(other, self.arr)) | def __rdiv__(self, other): try: if other.ndim == 0: return matrix(N.divide(other, self.arr)) else: raise NotImplementedError, "matrix division not yet implemented" except AttributeError: return matrix(N.divide(other, self.arr)) |
def __getattr__(self, obj): return self.arr.__getattribute__(obj) | def __getattr__(self, obj): return self.arr.__getattribute__(obj) | |
if obj in ('shape', 'arr'): | if obj in ('arr',): | def __setattr__(self, obj, value): if obj in ('shape', 'arr'): object.__setattr__(self, obj, value) else: self.arr.__setattr__(obj, value) |
return matrix(N.identity(shape[0])) | return asmatrix(N.identity(shape[0])) | def __pow__(self, other): shape = self.arr.shape if len(shape) != 2 or shape[0] != shape[1]: raise TypeError, "matrix is not square" if type(other) in (type(1), type(1L)): if other==0: return matrix(N.identity(shape[0])) if other<0: x = self.I other=-other else: x=self if other <= 3: result = x.copy() while(other>1): r... |
return matrix(self.arr.transpose()) | return asmatrix(self.arr.transpose()) | def getT(self): return matrix(self.arr.transpose()) |
return matrix(self.arr.transpose().conjugate()) else: return matrix(self.arr.transpose()) | return asmatrix(self.arr.transpose().conjugate()) else: return asmatrix(self.arr.transpose()) | def getH(self): if issubclass(self.arr.dtype, N.complexfloating): return matrix(self.arr.transpose().conjugate()) else: return matrix(self.arr.transpose()) |
return matrix(linalg.inv(self)) | return asmatrix(linalg.inv(self)) def getshape(self): return self.arr.shape def getdtype(self): return self.arr.dtype def getdtypechar(self): return self.arr.dtypechar def getsize(self): return self.arr.size def getflags(self): return self.arr.flags def getndim(self): return self.arr.ndim def getreal(self): retu... | def getI(self): from scipy import linalg return matrix(linalg.inv(self)) |
build_dir = d | build_dir = self.get_package_dir('.'.join(d.split(os.sep))) | def build_data_files_sources(self): if not self.data_files: return log.info('building data_files sources') from numpy.distutils.misc_util import get_data_files new_data_files = [] for data in self.data_files: if isinstance(data,str): new_data_files.append(data) elif isinstance(data,tuple): d,files = data if self.inplac... |
if self.inplace: get_package_dir = self.get_finalized_command('build_py').get_package_dir | def build_py_modules_sources(self): if not self.py_modules: return log.info('building py_modules sources') new_py_modules = [] if self.inplace: get_package_dir = self.get_finalized_command('build_py').get_package_dir for source in self.py_modules: if is_sequence(source) and len(source)==3: package, module_base, source ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.