rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
be persistent or pickable.
be persistent or picklable.
def __setitem__(self, browser_id, session_data): """Store an ISessionData"""
page.source = (u'<div ' u'tal:define="session request/session:products.foo"/>')
page.source = u'<div>Foo</div>'
def setUp(self): super(VirtualHostSessionTest, self).setUp() page = ZPTPage() page.source = (u'<div ' u'tal:define="session request/session:products.foo"/>') page.evaluateInlineCode = True root = self.getRootFolder() root['folder'] = Folder() root['folder']['page'] = page self.commit() provideHandler(self.accessSessio...
provideHandler(self.accessSessionOnTraverse, (IBeforeTraverseEvent,))
provideHandler(self.accessSessionOnRootTraverse, (IBeforeTraverseEvent,))
def setUp(self): super(VirtualHostSessionTest, self).setUp() page = ZPTPage() page.source = (u'<div ' u'tal:define="session request/session:products.foo"/>') page.evaluateInlineCode = True root = self.getRootFolder() root['folder'] = Folder() root['folder']['page'] = page self.commit() provideHandler(self.accessSessio...
getGlobalSiteManager().unregisterHandler(self.accessSessionOnTraverse, (IBeforeTraverseEvent,))
getGlobalSiteManager().unregisterHandler( self.accessSessionOnRootTraverse, (IBeforeTraverseEvent,))
def tearDown(self): getGlobalSiteManager().unregisterHandler(self.accessSessionOnTraverse, (IBeforeTraverseEvent,))
def accessSessionOnTraverse(self, event): session = ISession(event.request)
def accessSessionOnRootTraverse(self, event): if IRootFolder.providedBy(event.object): session = ISession(event.request)
def accessSessionOnTraverse(self, event): session = ISession(event.request)
log.info('getChild %s, %s' % name, request)
log.info('getChild %s, %s' % (name, request))
def getChild(self, name, request): log.info('getChild %s, %s' % name, request) ch = self.store.get_by_id(name) if ch != None: p = ch.get_path() if os.path.exists(p): new_id = self.server.connection_manager_server.add_connection() log.msg("startup, add %d to connection table" % new_id) d = request.notifyFinish() d.addCa...
new_id = self.server.connection_manager_server.add_connection()
new_id = self.server.connection_manager_server.add_connection('', 'Output', -1, '')
def getChild(self, name, request): log.info('getChild %s, %s' % name, request) ch = self.store.get_by_id(name) if ch != None: p = ch.get_path() if os.path.exists(p): new_id = self.server.connection_manager_server.add_connection() log.msg("startup, add %d to connection table" % new_id) d = request.notifyFinish() d.addCa...
class INotify(FileDescriptor):
class INotify(FileDescriptor, object):
def notify(self, filename, events): for callback in self.callbacks: if callback != None: callback[0](self, filename, events, callback[1])
def __new__(cls): if not INotify.__instance: INotify.__instance = object.__new__(cls) return INotify.__instance def __init__(self): if ctypes == None: raise SystemError, "ctypes not detected on this system, INotify support disabled" try: self.libc = ctypes.CDLL("libc.so.6") except: raise SystemError, "libc not found,...
def __new__(cls, *args, **kwargs): obj = getattr(cls,'_instance_',None) if obj is not None: return obj else: obj = super(INotify, cls).__new__(cls, *args, **kwargs) cls._instance_ = obj if ctypes == None: raise SystemError, "ctypes not detected on this system, INotify support disabled" try: obj.libc = ctypes.CDLL("libc...
def notify(self, filename, events): for callback in self.callbacks: if callback != None: callback[0](self, filename, events, callback[1])
print "Event %s on %s %s" % ( ', '.join(self._flag_to_human(mask)), iwp.path, filename)
print "event %s on %s %s" % ( ', '.join(self.flag_to_human(mask)), iwp.path, filename)
def notify(self, iwp, filename, mask, parameter=None): print "Event %s on %s %s" % ( ', '.join(self._flag_to_human(mask)), iwp.path, filename)
if ObjectID == 0:
root_id = ObjectID if root_id == 0:
def upnp_Browse(self, *args, **kwargs): ObjectID = int(kwargs['ObjectID']) BrowseFlag = kwargs['BrowseFlag'] Filter = kwargs['Filter'] StartingIndex = int(kwargs['StartingIndex']) RequestedCount = int(kwargs['RequestedCount']) SortCriteria = kwargs['SortCriteria']
print "propagate_notification", notify
def propagate_notification(self, notify): print "propagate_notification", notify if len(self._subscribers) <= 0: return if len(notify) <= 0: return root = Element('propertyset') root.attrib['xmlns']='urn:schemas-upnp-org:event-1-0'
print "propagate_notification", xml
def propagate_notification(self, notify): print "propagate_notification", notify if len(self._subscribers) <= 0: return if len(notify) <= 0: return root = Element('propertyset') root.attrib['xmlns']='urn:schemas-upnp-org:event-1-0'
print s
def check_subscribers(self): for s in self._subscribers.values(): timeout = 86400 print s if s['timeout'].startswith('Second-'): timeout = int(s['timeout'][len('Second-'):]) if time.time() > s['created'] + timeout: del s
print "check_moderated for %s" % self.id print self._subscribers
def check_moderated_variables(self): print "check_moderated for %s" % self.id print self._subscribers if len(self._subscribers) <= 0: return print "check_moderated for %s" % self.id variables = moderated_variables[self.get_type()] notify = [] for v in variables: if self._variables[0][v].updated == True: self._variables...
print "check_moderated for %s" % self.id
def check_moderated_variables(self): print "check_moderated for %s" % self.id print self._subscribers if len(self._subscribers) <= 0: return print "check_moderated for %s" % self.id variables = moderated_variables[self.get_type()] notify = [] for v in variables: if self._variables[0][v].updated == True: self._variables...
self.service.set_variable( 0, argument.get_state_variable(), r[argument.name])
def get_action_results(self, result, action): """ check for out arguments if yes: check if there are related ones to StateVariables with non A_ARG_TYPE_ prefix if yes: check if there is a call plugin method for this action if yes: update StateVariable values with call result if no: get StateVariable values and add the...
return { '%sResponse'%action.name: r}
r= { '%sResponse'%action.name: r} return r
def get_action_results(self, result, action): """ check for out arguments if yes: check if there are related ones to StateVariables with non A_ARG_TYPE_ prefix if yes: check if there is a call plugin method for this action if yes: update StateVariable values with call result if no: get StateVariable values and add the...
print "soap__generic", action, __name__, kwargs
def soap__generic(self, *args, **kwargs): """ generic UPnP service control method, which will be used if no soap_ACTIONNAME method in the server service control class can be found """ try: action = self.actions[kwargs['soap_methodName']] except: return failure.Failure(errorCode(401)) #print "soap__generic", action, __...
log.msg('Unknown SSDP command %s %s' % cmd)
log.msg('Unknown SSDP command %s %s' % (cmd[0], cmd[1])
def datagramReceived(self, data, (host, port)): """Handle a received multicast datagram.""" try: header, payload = data.split('\r\n\r\n') except ValueError, err: print err print 'Arggg,', data import pdb; pdb.set_trace() lines = header.split('\r\n') cmd = string.split(lines[0], ' ') lines = map(lambda x: x.replace(': ...
device = self.coherence.get_device_with_usn(c)
device = self.coherence.get_device_with_id(c)
def render_listchilds(self, ctx, data): cl = [] #print 'children:', self.coherence.children for c in self.coherence.children: if c[:5] == 'uuid:': device = self.coherence.get_device_with_usn(c) if device != None: cl.append( tags.li[tags.a(href='/'+c)[device.get_device_type(), device.get_friendly_name()]]) else: cl.appe...
cl.append( tags.li[tags.a(href='/'+c)[device.get_device_type(), device.get_friendly_name()]])
_,_,_,device_type,version = device.get_device_type().split(':') cl.append( tags.li[tags.a(href='/'+c)[device_type, ':', version, ' ', device.get_friendly_name()]])
def render_listchilds(self, ctx, data): cl = [] #print 'children:', self.coherence.children for c in self.coherence.children: if c[:5] == 'uuid:': device = self.coherence.get_device_with_usn(c) if device != None: cl.append( tags.li[tags.a(href='/'+c)[device.get_device_type(), device.get_friendly_name()]]) else: cl.appe...
keywords = {'soap_methodName':methodName} for k, v in kwargs.items(): keywords[str(k)] = v
def render(self, request): """Handle a SOAP command.""" data = request.content.read() headers = request.getAllHeaders()
keywords = {'soap_methodName':methodName}
def render(self, request): """Handle a SOAP command.""" data = request.content.read() headers = request.getAllHeaders()
port = reactor.listenUDP(5654, self)
port = reactor.listenUDP(0, self)
def __init__(self, ssdp_server): self.ssdp_server = ssdp_server port = reactor.listenUDP(5654, self)
result.update( callback( **kwargs))
return callback( **kwargs)
def callit( *args, **kwargs): #print 'callit args', args #print 'callit kwargs', kwargs result = {} #print 'callit before callback', result callback = action.get_callback() if callback != None: result.update( callback( **kwargs)) #print 'callit after callback', result return result
print _global_color_map[level](msg % _fix_args(args))
if args: print _global_color_map[level](msg % _fix_args(args)) else: print _global_color_map[level](msg)
def _log(self, level, msg, args): if level >= self.threshold: print _global_color_map[level](msg % _fix_args(args)) sys.stdout.flush()
return res
return res[0]
def nonzero(a): """nonzero(a) returns the indices of the elements of a which are not zero, a must be 1d """ try: nonzero = a.nonzero except AttributeError: res = _wrapit(a, 'nonzero') else: res = nonzero() return res
import tempfile d = tempfile.gettempdir() dummy_name = os.path.join(d,'__dummy.f') dummy = open(dummy_name,'w')
import tempfile dummy_name = tempfile.mktemp()+'__dummy' dummy = open(dummy_name+'.f','w')
def dummy_fortran_files(self): import tempfile d = tempfile.gettempdir() dummy_name = os.path.join(d,'__dummy.f') dummy = open(dummy_name,'w') dummy.write(" subroutine dummy()\n end\n") dummy.close() return (os.path.join(d,'__dummy.f'),os.path.join(d,'__dummy.o'))
return (os.path.join(d,'__dummy.f'),os.path.join(d,'__dummy.o'))
return (dummy_name+'.f',dummy_name+'.o')
def dummy_fortran_files(self): import tempfile d = tempfile.gettempdir() dummy_name = os.path.join(d,'__dummy.f') dummy = open(dummy_name,'w') dummy.write(" subroutine dummy()\n end\n") dummy.close() return (os.path.join(d,'__dummy.f'),os.path.join(d,'__dummy.o'))
cmd = self.f90_compiler + ' -dryrun dummy.f'
cmd = self.f90_compiler + ' -dryrun __dummy.f'
def find_lib_dir(self): library_dirs = ["/opt/SUNWspro/prod/lib"] lib_match = r'### f90: Note: LD_RUN_PATH\s*= '\ '(?P<lib_paths>[^\s.]*).*' cmd = self.f90_compiler + ' -dryrun dummy.f' self.announce(yellow_text(cmd)) exit_status, output = run_command(cmd) if not exit_status: libs = re.findall(lib_match,output) if libs...
return a1 + a2
val = a1 + a2
def polyadd(a1, a2): """Adds two polynomials represented as sequences """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: return a1 + a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) + a2 else: zr ...
return self.__getattribute__(attr) else: return self.__setattr__(attr,val)
obj = self.getfield(*res) if obj.dtype.fields: return obj if obj.dtype.char in 'SU': return obj.view(chararray) return obj.view(sb.ndarray) else: return self.setfield(val, *res)
def field(self,attr, val=None): fielddict = sb.ndarray.__getattribute__(self,'dtype').fields
d = diag(c)
try: d = diag(c) except ValueError: return 1
def corrcoef(x, y=None): """The correlation coefficients """ c = cov(x, y) d = diag(c) return c/sqrt(multiply.outer(d,d))
self.parent_path = eval('__path__[0]',frame.f_globals,frame.f_locals)
self.parent_path = eval('__path__',frame.f_globals,frame.f_locals)
def __init__(self): """ Manages loading SciPy packages. """
def _get_info_files(self, parent_path=None): """ Return info.py files from parent_path subdirectories.
def _get_info_files(self, package_dir, parent_path, parent_package=None): """ Return list of (package name,info.py file) from parent_path subdirectories.
def _get_info_files(self, parent_path=None): """ Return info.py files from parent_path subdirectories. """ from glob import glob if parent_path is None: parent_path = self.parent_path info_files = glob(os.path.join(parent_path,'*','info.py')) for info_file in glob(os.path.join(parent_path,'*','info.pyc')): if info_file...
if parent_path is None: parent_path = self.parent_path info_files = glob(os.path.join(parent_path,'*','info.py')) for info_file in glob(os.path.join(parent_path,'*','info.pyc')): if info_file[:-1] not in info_files: info_files.append(info_file) for info_file in info_files[:]: info_files.extend(self._get_info_files(os.p...
files = glob(os.path.join(parent_path,package_dir,'info.py')) for info_file in glob(os.path.join(parent_path,package_dir,'info.pyc')): if info_file[:-1] not in files: files.append(info_file) info_files = [] for info_file in files: package_name = os.path.dirname(info_file[len(parent_path)+1:])\ .replace(os.sep,'.') if p...
def _get_info_files(self, parent_path=None): """ Return info.py files from parent_path subdirectories. """ from glob import glob if parent_path is None: parent_path = self.parent_path info_files = glob(os.path.join(parent_path,'*','info.py')) for info_file in glob(os.path.join(parent_path,'*','info.pyc')): if info_file...
info_files = self._get_info_files()
for path in self.parent_path: info_files.extend(self._get_info_files('*',path))
def _init_info_modules(self, packages=None): """Initialize info_modules = {<package_name>: <package info.py module>}. """ import imp if packages is None: info_files = self._get_info_files() else: info_files = [] for package in packages: package = os.path.join(*package.split('.')) info_file = os.path.join(self.parent_pa...
info_files = [] for package in packages: package = os.path.join(*package.split('.')) info_file = os.path.join(self.parent_path,package,'info.py') if not os.path.isfile(info_file): info_file += 'c' if os.path.isfile(info_file): info_files.append(info_file)
for package_name in packages: package_dir = os.path.join(*package_name.split('.')) for path in self.parent_path: names_files = self._get_info_files(package_dir, path) if names_files: info_files.extend(names_files) break
def _init_info_modules(self, packages=None): """Initialize info_modules = {<package_name>: <package info.py module>}. """ import imp if packages is None: info_files = self._get_info_files() else: info_files = [] for package in packages: package = os.path.join(*package.split('.')) info_file = os.path.join(self.parent_pa...
% package)
% package_name)
def _init_info_modules(self, packages=None): """Initialize info_modules = {<package_name>: <package info.py module>}. """ import imp if packages is None: info_files = self._get_info_files() else: info_files = [] for package in packages: package = os.path.join(*package.split('.')) info_file = os.path.join(self.parent_pa...
for info_file in info_files: package_name = os.path.dirname(info_file[len(self.parent_path)+1:])\ .replace(os.sep,'.')
for package_name,info_file in info_files:
def _init_info_modules(self, packages=None): """Initialize info_modules = {<package_name>: <package info.py module>}. """ import imp if packages is None: info_files = self._get_info_files() else: info_files = [] for package in packages: package = os.path.join(*package.split('.')) info_file = os.path.join(self.parent_pa...
mathlibs.extend(line[len(s):].strip().split(','))
value = line[len(s):].strip() if value: mathlibs.extend(value.split(','))
def generate_config_h(ext, build_dir): target = join(build_dir,'config.h') if newer(__file__,target): config_cmd = config.get_config_cmd() print 'Generating',target # tc = generate_testcode(target) from distutils import sysconfig python_include = sysconfig.get_python_inc() result = config_cmd.try_run(tc,include_dirs=[p...
if issubclass(a.dtype, NX.complexfloating):
if issubclass(a.dtype.type, NX.complexfloating):
def poly(seq_of_zeros): """ Return a sequence representing a polynomial given a sequence of roots. If the input is a matrix, return the characteristic polynomial. Example: >>> b = roots([1,3,1,5,6]) >>> poly(b) array([1., 3., 1., 5., 6.]) """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh)...
if not issubclass(p.dtype, (NX.floating, NX.complexfloating)):
if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
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...
typeobj = val[-1] utypeobj = uval[-1]
def _add_integer_aliases(): _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE'] for ctype in _ctypes: val = typeinfo[ctype] bits = val[2] intname = 'int%d' % bits UIntname = 'UInt%d' % bits Intname = 'Int%d' % bits uval = typeinfo['U'+ctype] if intname not in allTypes.keys(): uintname = 'uint%d' % bits typeobj = val...
typeNA[typeobj] = Intname typeNA[utypeobj] = UIntname typeNA[val[0]] = Intname typeNA[uval[0]] = UIntname else: typeNA[typeobj] = Intname typeNA[utypeobj] = UIntname typeNA[val[0]] = Intname typeNA[uval[0]] = UIntname
typeNA[typeobj] = Intname typeNA[utypeobj] = UIntname typeNA[val[0]] = Intname typeNA[uval[0]] = UIntname
def _add_integer_aliases(): _ctypes = ['LONG', 'LONGLONG', 'INT', 'SHORT', 'BYTE'] for ctype in _ctypes: val = typeinfo[ctype] bits = val[2] intname = 'int%d' % bits UIntname = 'UInt%d' % bits Intname = 'Int%d' % bits uval = typeinfo['U'+ctype] if intname not in allTypes.keys(): uintname = 'uint%d' % bits typeobj = val...
self.__queue.put((None,None))
self.__queue.put((None,None,None))
def shutdown(self): """ Shutdown parallel thread.""" self.__queue.put((None,None))
def func(extension, src_dir):
def func(extension, src_dir, name=name, fullname=fullname, backends=backends):
def func(extension, src_dir): source = os.path.join(os.path.dirname(src_dir),name+'.py') if newer(__file__, source): f = open(source,'w') f.write(_split_ext_template \ % {'name':name,'fullname':fullname, 'backends':backends}) f.close() return [ source ]
if _free_f90_start(line[:5]) or line[-2:-1]=='&':
if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-2:-1]=='&':
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 = 15 # the number of non-comment lines to scan for hints if _has_f_header(line): n = 0 elif _ha...
return matrix_base.bmat(key,frame.f_globals,frame.f_locals)
return array(matrix_base.bmat(key,frame.f_globals,frame.f_locals))
def __getitem__(self,key): if isinstance(key,types.StringType): frame = sys._getframe().f_back return matrix_base.bmat(key,frame.f_globals,frame.f_locals) if type(key) is not types.TupleType: key = (key,) objs = [] for k in range(len(key)): if type(key[k]) is types.SliceType: typecode = Numeric.Int step = key[k].step s...
fprintf(fp," }\n");
fprintf(fp," }\\n");
typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar **vars; int nvars; int maxvars;
fprintf(stderr,"SWIG : Fatal error in initializing Python module.\n");
fprintf(stderr,"SWIG : Fatal error in initializing Python module.\\n");
typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar **vars; int nvars; int maxvars;
//printf("str: %s\n", str);
//printf("str: %s\\n", str);
typedef struct { int stat; /* Status (valid) bit */ SwigPtrType *tp; /* Pointer to type structure */ char name[256]; /* Given datatype name */ char mapped[256]; /* Equivalent name ...
def svd(a, full_matrices = 1): _assertRank2(a) n = a.shape[1] m = a.shape[0]
def svd(a, full_matrices=1): _assertRank2(a) m, n = a.shape
def svd(a, full_matrices = 1): _assertRank2(a) n = a.shape[1] m = a.shape[0] t =_commonType(a) real_t = _array_type[0][_array_precision[t]] a = _fastCopyAndTranspose(t, a) wrap = a.__array_wrap__ if full_matrices: nu = m nvt = n option = 'A' else: nu = min(n,m) nvt = min(n,m) option = 'S' s = zeros((min(n,m),), real_t)...
return svd(A, 0)
return svd(A, full_matrices)
def singular_value_decomposition(A, full_matrices=0): return svd(A, 0)
command_posix = '%s > %s 2>&1' % (command_str,tmpfile)
stsfile = tempfile.mktemp() command_posix = '( %s ; echo $? > %s ) > %s 2>&1'\ % (command_str,stsfile,tmpfile)
def _exec_command_posix( command, use_shell = None, use_tee = None, **env ): log.debug('_exec_command_posix(...)') if type(command) is type([]): command_str = ' '.join(command) else: command_str = command tmpfile = tempfile.mktemp() if use_tee: stsfile = tempfile.mktemp() filter = '' if use_tee == 2: filter = r'| tr ...
def test_posix(): s,o=exec_command("echo Hello")
def test_posix(**kws): s,o=exec_command("echo Hello",**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo $AAA')
s,o=exec_command('echo $AAA',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo "$AAA"',AAA='Tere')
s,o=exec_command('echo "$AAA"',AAA='Tere',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo "$AAA"')
s,o=exec_command('echo "$AAA"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo "$BBB"')
s,o=exec_command('echo "$BBB"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo "$BBB"',BBB='Hey')
s,o=exec_command('echo "$BBB"',BBB='Hey',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('this_is_not_a_command')
s,o=exec_command('this_is_not_a_command',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('echo path=$PATH')
s,o=exec_command('echo path=$PATH',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"')
s,o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('python -c "raise \'Ignore me.\'"')
s,o=exec_command('python -c "raise \'Ignore me.\'"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"')
s,o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('python -c "import sys;sys.exit(15)"')
s,o=exec_command('python -c "import sys;sys.exit(15)"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
s,o=exec_command('python -c "print \'Heipa\'"')
s,o=exec_command('python -c "print \'Heipa\'"',**kws)
def test_posix(): s,o=exec_command("echo Hello") assert s==0 and o=='Hello',(s,o) s,o=exec_command('echo $AAA') assert s==0 and o=='',(s,o) s,o=exec_command('echo "$AAA"',AAA='Tere') assert s==0 and o=='Tere',(s,o) s,o=exec_command('echo "$AAA"') assert s==0 and o=='',(s,o) os.environ['BBB'] = 'Hi' s,o=exec_comman...
def test_execute_in():
def test_execute_in(**kws):
def test_execute_in(): pythonexe = get_pythonexe() tmpfile = tempfile.mktemp() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile,'w') f.write('Hello') f.close() s,o = exec_command('%s -c "print \'Ignore following IOError:\',open(%r,\'r\')"' \ % (pythonexe,fn)) assert s and o!='',(s,o) s...
% (pythonexe,fn))
% (pythonexe,fn),**kws)
def test_execute_in(): pythonexe = get_pythonexe() tmpfile = tempfile.mktemp() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile,'w') f.write('Hello') f.close() s,o = exec_command('%s -c "print \'Ignore following IOError:\',open(%r,\'r\')"' \ % (pythonexe,fn)) assert s and o!='',(s,o) s...
execute_in = tmpdir)
execute_in = tmpdir,**kws)
def test_execute_in(): pythonexe = get_pythonexe() tmpfile = tempfile.mktemp() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile,'w') f.write('Hello') f.close() s,o = exec_command('%s -c "print \'Ignore following IOError:\',open(%r,\'r\')"' \ % (pythonexe,fn)) assert s and o!='',(s,o) s...
test() test_execute_in()
test(use_tee=0) test(use_tee=1) test_execute_in(use_tee=0) test_execute_in(use_tee=1)
def test_execute_in(): pythonexe = get_pythonexe() tmpfile = tempfile.mktemp() fn = os.path.basename(tmpfile) tmpdir = os.path.dirname(tmpfile) f = open(tmpfile,'w') f.write('Hello') f.close() s,o = exec_command('%s -c "print \'Ignore following IOError:\',open(%r,\'r\')"' \ % (pythonexe,fn)) assert s and o!='',(s,o) s...
return elapsed
return 0.01*elapsed
def measure(self,code_str,times=1): """ Return elapsed time for executing code_str in the namespace of the caller for given times. """ frame = sys._getframe(1) locs,globs = frame.f_locals,frame.f_globals code = compile(code_str, 'ScipyTestCase runner for '+self.__class__.__name__, 'exec') i = 0 elapsed = jiffies() whil...
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False):
def array(obj, itemsize=None, copy=True, unicode=False, fortran=False):
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
if copy or (itemlen != obj.itemlen) \
if itemsize is None: itemsize = obj.itemsize if copy or (itemsize != obj.itemsize) \
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
return obj.astype("%s%d" % (obj.dtypechar, itemlen))
return obj.astype("%s%d" % (obj.dtypechar, itemsize))
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
dtype = 'U%d' % obj.itemlen
dtype = 'U%d' % obj.itemsize
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
dtype = 'S%d' % obj.itemlen
dtype = 'S%d' % obj.itemsize
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
return ndarray.__new__(chararray, obj.shape, (dtype, itemlen),
return ndarray.__new__(chararray, obj.shape, dtype,
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
if unicode: dtype = "U%d" % itemlen else: dtype = "S%d" % itemlen
if unicode: dtype = "U" else: dtype = "S" if itemsize is not None: dtype += str(itemsize)
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
return chararray(val.shape, itemlen, unicode, buffer=val,
return chararray(val.shape, itemsize, unicode, buffer=val,
def array(obj, itemlen=7, copy=True, unicode=False, fortran=False): if isinstance(obj, chararray): if copy or (itemlen != obj.itemlen) \ or (not unicode and obj.dtype == unicode_) \ or (unicode and obj.dtype == string): return obj.astype("%s%d" % (obj.dtypechar, itemlen)) else: return obj if isinstance(obj, ndarray) ...
return self._ctypes.c_void_p(self._data)
return self._data
def get_data(self): return self._ctypes.c_void_p(self._data)
return self._data
return self._ctypes.c_void_p(self._data)
def get_as_parameter(self): return self._data
'unicode', 'object']
'unicode', 'object', ('a', allTypes['string_'])]
def sctype2char(sctype): sctype = obj2sctype(sctype) if sctype is None: raise ValueError, "unrecognized type" return _sctype2char_dict[sctype]
'square-root elementwise.',
'square-root elementwise. For real x, the domain is restricted to x>=0.',
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...
if sys.executable.startswith('/usr/bin'):
if os.path.realpath(sys.executable).startswith('/System'):
def get_flags_linker_so(self): opt = [] if sys.platform=='darwin': if sys.executable.startswith('/usr/bin'): # This is when Python is from Apple framework opt.extend(["-Wl,-framework","-Wl,Python"]) #else we are running in Fink python. opt.extend(["-lcc_dynamic","-bundle"]) else: opt.append("-shared") if sys.platform[:...
assert_all(vals.imag > 1e10) and assert_all(isfinite(vals))
assert_all(isfinite(vals))
def check_complex_bad(self): v = 1+1j v += array(0+1.j)/0. vals = nan_to_num(v) # !! This is actually (unexpectedly) zero assert_all(vals.imag > 1e10) and assert_all(isfinite(vals))
from types import *
def test(): from types import * obj = mt.get_state() mt.set_state(obj) obj2 = mt.get_state() if (obj2[1] - obj[1]).any(): raise SystemExit, "Failed seed test." print "First random number is", random() print "Average of 10000 random numbers is", Numeric.sum(random(10000))/10000. x = random([10,1000]) if len(x.shape) != ...
if isdtype(M): dtype = M M = N
def eye(N, M=None, k=0, dtype=float): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ if M is None: M = N if isdtype(M): dtype = M M = N m = equal(subtract.outer(arange(N), arange(M)),-k) if dtype is None: return m+0 else: return m.astype(dtype)
if k > 0: v = concatenate((zeros(k, v.dtype),v)) elif k < 0: v = concatenate((v,zeros(-k, v.dtype))) return eye(n, k=k)*v
res = zeros((n,n), v.dtype) i = arange(0,n-k) if (k>=0): fi = i+k+i*n else: fi = i+(i-k)*n res.flat[fi] = v return res
def diag(v, k=0): """ returns the k-th diagonal if v is a array or returns a array with v as the k-th diagonal if v is a vector. """ v = asarray(v) s = v.shape if len(s)==1: n = s[0]+abs(k) if k > 0: v = concatenate((zeros(k, v.dtype),v)) elif k < 0: v = concatenate((v,zeros(-k, v.dtype))) return eye(n, k=k)*v elif len...
v = add.reduce(eye(s[0], s[1], k=k)*v) if k > 0: return v[k:] elif k < 0: return v[:k] else: return v
N1,N2 = s if k >= 0: M = min(N1,N2-k) i = arange(0,M) fi = i+k+i*N2 else: M = min(N1+k,N2) i = arange(0,M) fi = i + (i-k)*N2 return v.flat[fi]
def diag(v, k=0): """ returns the k-th diagonal if v is a array or returns a array with v as the k-th diagonal if v is a vector. """ v = asarray(v) s = v.shape if len(s)==1: n = s[0]+abs(k) if k > 0: v = concatenate((zeros(k, v.dtype),v)) elif k < 0: v = concatenate((v,zeros(-k, v.dtype))) return eye(n, k=k)*v elif len...
i.set_compiler(self.compiler
i.set_compiler(self.compiler)
def build_information(self): info = self._build_information + [self.customize] + \ self.arg_specs().build_information() for func in self.functions: info.append(func.customize) #redundant, but easiest place to make sure compiler is set for i in info: i.set_compiler(self.compiler return info
if _with_python and sys.__stdout__.fileno()==-1: st = _exec_command_python(command, **env)
if _with_python and (0 or sys.__stdout__.fileno()==-1): st = _exec_command_python(command, exec_command_dir = exec_dir, **env)
def exec_command( command, execute_in='', use_shell=None, use_tee = None, _with_python = 1, **env ): """ Return (status,output) of executed command. command is a concatenated string of executable and arguments. The output contains both stdout and stderr messages. The following special keyword arguments can be used: us...
def _exec_command_python(command, **env):
def _exec_command_python(command, exec_command_dir='', **env):
def _exec_command_python(command, **env): log.debug('_exec_command_python(...)') python_exe = get_pythonexe() cmdfile = tempfile.mktemp() stsfile = tempfile.mktemp() outfile = tempfile.mktemp() if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command...
if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command.py'): exec_dir = os.path.abspath('.') else: exec_dir = os.path.abspath(sys.argv[0]) if os.path.isfile(exec_dir): exec_dir = os.path.dirname(exec_dir)
def _exec_command_python(command, **env): log.debug('_exec_command_python(...)') python_exe = get_pythonexe() cmdfile = tempfile.mktemp() stsfile = tempfile.mktemp() outfile = tempfile.mktemp() if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command...
f.write('sys.path.insert(0,%r)\n' % (exec_dir))
f.write('sys.path.insert(0,%r)\n' % (exec_command_dir))
def _exec_command_python(command, **env): log.debug('_exec_command_python(...)') python_exe = get_pythonexe() cmdfile = tempfile.mktemp() stsfile = tempfile.mktemp() outfile = tempfile.mktemp() if __name__[-12:] == 'exec_command': exec_dir = os.path.dirname(os.path.abspath(__file__)) elif os.path.isfile('exec_command...
_old_pydoc_locate = _pydoc.locate def _scipy_pydoc_locate(thing, forceload=0): _old_pydoc_locate.__doc__ return _old_pydoc_locate(_ppresolve_ignore_failure(thing), forceload=forceload) _pydoc.locate = _scipy_pydoc_locate
def _scipy_pydoc_describe(object): _old_pydoc_describe.__doc__ return _old_pydoc_describe(_ppresolve_ignore_failure(object))
x = ones((1,1))
x = ones((1,1,1))
def check_tuple(self): x = ones((1,1)) x[:,(0,)] = 2.0 assert_array_equal(x, array([[2.0]])) x = ones((1,1)) x[:,:,(0,)] = 2.0 assert_array_equal(x, array([[[2.0]]]))
ar = numpy.array( ar1 ).ravel()
def unique1d( ar1, retindx = False ): """Unique elements of 1D array. When ret_indx is True, return also the indices indx such that ar1.flat[indx] is the resulting array of unique elements.""" ar = numpy.array( ar1 ).ravel() if retindx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) !=...