rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
self.stop = False while not self.stop: | self.stop_request = False self.stopped = False while not self.stop_request: | def serve_forever_stoppable(self): """Handle one request at a time until stop_serve_forever(). http://code.activestate.com/recipes/336012/ """ self.stop = False while not self.stop: self.handle_request() print "serve_forever_stoppable received stop request" |
print "serve_forever_stoppable received stop request" | self.stopped = True | def serve_forever_stoppable(self): """Handle one request at a time until stop_serve_forever(). http://code.activestate.com/recipes/336012/ """ self.stop = False while not self.stop: self.handle_request() print "serve_forever_stoppable received stop request" |
if contentlength < 0: | if ( (contentlength < 0) and (environ.get("HTTP_TRANSFER_ENCODING", "").lower() != "chunked") ): | def doPUT(self, environ, start_response): """ @see: http://www.webdav.org/specs/rfc4918.html#METHOD_PUT """ path = environ["PATH_INFO"] provider = self._davProvider res = provider.getResourceInst(path, environ) parentRes = provider.getResourceInst(util.getUriParent(path), environ) isnewfile = res is None |
l = int(environ["wsgi.input"].readline(), 16) | buf = environ["wsgi.input"].readline() if buf == '': l = 0 else: l = int(buf, 16) | def doPUT(self, environ, start_response): """ @see: http://www.webdav.org/specs/rfc4918.html#METHOD_PUT """ path = environ["PATH_INFO"] provider = self._davProvider res = provider.getResourceInst(path, environ) parentRes = provider.getResourceInst(util.getUriParent(path), environ) isnewfile = res is None |
res.endWrite(hasErrors=True) | res.endWrite(withErrors=True) | def doPUT(self, environ, start_response): """ @see: http://www.webdav.org/specs/rfc4918.html#METHOD_PUT """ path = environ["PATH_INFO"] provider = self._davProvider res = provider.getResourceInst(path, environ) parentRes = provider.getResourceInst(util.getUriParent(path), environ) isnewfile = res is None |
body = StringIO.StringIO() tree.write(body) body = body.getvalue() print body | def proppatch(self, path, set_props=None, remove_props=None, namespace='DAV:', headers=None): """Patch properties on a DAV resource. If namespace is not specified the DAV namespace is used for all properties""" root = ElementTree.Element('{DAV:}propertyupdate') if set_props is not None: prop_set = ElementTree.SubElement(root, '{DAV:}set') object_to_etree(prop_set, set_props, namespace=namespace) if remove_props is not None: prop_remove = ElementTree.SubElement(root, '{DAV:}remove') object_to_etree(prop_remove, remove_props, namespace=namespace) tree = ElementTree.ElementTree(root) # Add proper headers if headers is None: headers = {} headers['Content-Type'] = 'text/xml; charset="utf-8"' self._request('PROPPATCH', path, body=unicode('<?xml version="1.0" encoding="utf-8" ?>\n'+body, 'utf-8'), headers=headers) |
|
def set_lock(self, path, owner, locktype='exclusive', lockscope='write', depth=None, headers=None): | def set_lock(self, path, owner, locktype='write', lockscope='exclusive', depth=None, headers=None): | def set_lock(self, path, owner, locktype='exclusive', lockscope='write', depth=None, headers=None): """Set a lock on a dav resource""" root = ElementTree.Element('{DAV:}lockinfo') object_to_etree(root, {'locktype':locktype, 'lockscope':lockscope, 'owner':{'href':owner}}, namespace='DAV:') tree = ElementTree.ElementTree(root) # Add proper headers if headers is None: headers = {} if depth is not None: headers['Depth'] = depth headers['Content-Type'] = 'text/xml; charset="utf-8"' headers['Timeout'] = 'Infinite, Second-4100000000' self._request('LOCK', path, body=unicode('<?xml version="1.0" encoding="utf-8" ?>\n'+body, 'utf-8'), headers=headers) locks = self.response.etree.finall('.//{DAV:}locktoken') lock_list = [] for lock in locks: lock_list.append(lock.getchildren()[0].text.strip().strip('\n')) return lock_list |
locks = self.response.etree.finall('.//{DAV:}locktoken') | locks = self.response.tree.findall('.//{DAV:}locktoken') | def set_lock(self, path, owner, locktype='exclusive', lockscope='write', depth=None, headers=None): """Set a lock on a dav resource""" root = ElementTree.Element('{DAV:}lockinfo') object_to_etree(root, {'locktype':locktype, 'lockscope':lockscope, 'owner':{'href':owner}}, namespace='DAV:') tree = ElementTree.ElementTree(root) # Add proper headers if headers is None: headers = {} if depth is not None: headers['Depth'] = depth headers['Content-Type'] = 'text/xml; charset="utf-8"' headers['Timeout'] = 'Infinite, Second-4100000000' self._request('LOCK', path, body=unicode('<?xml version="1.0" encoding="utf-8" ?>\n'+body, 'utf-8'), headers=headers) locks = self.response.etree.finall('.//{DAV:}locktoken') lock_list = [] for lock in locks: lock_list.append(lock.getchildren()[0].text.strip().strip('\n')) return lock_list |
headers['Lock-Tocken'] = '<%s>' % token | headers['Lock-Token'] = '<%s>' % token | def unlock(self, path, token, headers=None): """Unlock DAV resource with token""" if headers is None: headers = {} headers['Lock-Tocken'] = '<%s>' % token self._request('UNLOCK', path, body=None, headers=headers) |
self._fail(HTTP_BAD_REQUEST, "PUT request with invalid Content-Length: (%s)" % environ.get("CONTENT_LENGTH")) | if "Microsoft-WebDAV-MiniRedir" in environ.get("HTTP_USER_AGENT", ""): _logger.warning("Setting misssing Content-Length to 0 for MS client") contentlength = 0 else: self._fail(HTTP_LENGTH_REQUIRED, "PUT request with invalid Content-Length: (%s)" % environ.get("CONTENT_LENGTH")) | def doPUT(self, environ, start_response): """ @see: http://www.webdav.org/specs/rfc4918.html#METHOD_PUT """ path = environ["PATH_INFO"] provider = self._davProvider res = provider.getResourceInst(path, environ) parentRes = provider.getResourceInst(util.getUriParent(path), environ) isnewfile = res is None |
self._checkWritePermission(res, environ["HTTP_DEPTH"], environ) | parentRes = provider.getResourceInst(util.getUriParent(path), environ) if parentRes: self._checkWritePermission(parentRes, environ["HTTP_DEPTH"], environ) else: self._checkWritePermission(res, environ["HTTP_DEPTH"], environ) | def doDELETE(self, environ, start_response): """ @see: http://www.webdav.org/specs/rfc4918.html#METHOD_DELETE """ path = environ["PATH_INFO"] provider = self._davProvider res = provider.getResourceInst(path, environ) |
"propsmanager": None, | "propsmanager": True, | def run(self): withAuthentication = True self.rootpath = os.path.join(gettempdir(), "wsgidav-test") if not os.path.exists(self.rootpath): os.mkdir(self.rootpath) provider = FilesystemProvider(self.rootpath) config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"/": provider}, "user_mapping": {}, "host": "localhost", "port": 8080, "enable_loggers": [], "propsmanager": None, # None: no property manager "locksmanager": True, # True: use lock_manager.LockManager "domaincontroller": None, # None: domain_controller.WsgiDAVDomainController(user_mapping) "verbose": 2, }) |
"verbose": 2, | "verbose": 3, | def run(self): withAuthentication = True self.rootpath = os.path.join(gettempdir(), "wsgidav-test") if not os.path.exists(self.rootpath): os.mkdir(self.rootpath) provider = FilesystemProvider(self.rootpath) config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"/": provider}, "user_mapping": {}, "host": "localhost", "port": 8080, "enable_loggers": [], "propsmanager": None, # None: no property manager "locksmanager": True, # True: use lock_manager.LockManager "domaincontroller": None, # None: domain_controller.WsgiDAVDomainController(user_mapping) "verbose": 2, }) |
self.ext_server.serve_forever() | self.ext_server.serve_forever_stoppable() | def run(self): withAuthentication = True self.rootpath = os.path.join(gettempdir(), "wsgidav-test") if not os.path.exists(self.rootpath): os.mkdir(self.rootpath) provider = FilesystemProvider(self.rootpath) config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"/": provider}, "user_mapping": {}, "host": "localhost", "port": 8080, "enable_loggers": [], "propsmanager": None, # None: no property manager "locksmanager": True, # True: use lock_manager.LockManager "domaincontroller": None, # None: domain_controller.WsgiDAVDomainController(user_mapping) "verbose": 2, }) |
self.ext_server.shutdown() | self.ext_server.stop_serve_forever() | def shutdown(self): if self.ext_server: print "shutting down" self.ext_server.shutdown() print "shut down" self.ext_server = None |
assert hasattr(lockManager, "checkWritePermission"), "Must be compatible with wsgidav.lock_manager.LockManager" | assert not lockManager or hasattr(lockManager, "checkWritePermission"), "Must be compatible with wsgidav.lock_manager.LockManager" | def setLockManager(self, lockManager): assert hasattr(lockManager, "checkWritePermission"), "Must be compatible with wsgidav.lock_manager.LockManager" |
assert hasattr(propManager, "copyProperties"), "Must be compatible with wsgidav.property_manager.PropertyManager" | assert not propManager or hasattr(propManager, "copyProperties"), "Must be compatible with wsgidav.property_manager.PropertyManager" | def setPropManager(self, propManager): assert hasattr(propManager, "copyProperties"), "Must be compatible with wsgidav.property_manager.PropertyManager" |
client.move("/test/put2.txt", "/test/put2_moved.txt", | client.move("/test/file2.txt", "/test/file2_moved.txt", | def testGetPut(self): """Read and write file contents.""" client = self.client |
my_events = PlayaEvent.objects.filter(year=year, creator=user)[0] my_events = True if my_events else False | my_events = PlayaEvent.objects.filter(year=year, creator=user) my_events = True if len(my_events)>0 else False | def playa_events_home(request, year_year, template='brc/playa_events_home.html', queryset=None |
my_events = True if len(my_events) else False | my_events = True if my_events else False | def playa_events_home(request, year_year, template='brc/playa_events_home.html', queryset=None |
extra_context = dict(next=next), | extra_context = dict(next=next, year=event.year), | def delete_event(request, year_year, playa_event_id, next=None, |
extra_context = dict(next=next, msg="This is the only occurrence of this event. By deleting it, you will delete the entire event. Are you sure you want to do this??"), | extra_context = dict(next=next, year=event.year, msg="This is the only occurrence of this event. By deleting it, you will delete the entire event. Are you sure you want to do this??"), | def delete_occurrence(request, year_year, occurrence_id, next=None, |
my_events = PlayaEvent.objects.filter(year=year, creator=user)[0] my_events = True if len(my_events) else False | if user: my_events = PlayaEvent.objects.filter(year=year, creator=user)[0] my_events = True if len(my_events) else False else: my_events = False | def playa_events_home(request, year_year, template='brc/playa_events_home.html', queryset=None |
if user: | if user and type(user) != AnonymousUser: | def playa_events_home(request, year_year, template='brc/playa_events_home.html', queryset=None |
data = {'year':year} | data = {'year':year, 'user':request.user} | def playa_events_home(request, year_year, template='brc/playa_events_home.html', queryset=None |
print "HERE", args, kwargs | def __init__(self, *args, **kwargs): print "HERE", args, kwargs super(PlayaEventForm, self).__init__(*args, **kwargs) |
|
self.profile_SaveButton.on_click += self.save_profile | self.profile_SaveButton.on_click += lambda _: self.save_profile() | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.profile_DeleteButton.on_click += self.delete_profile | self.profile_DeleteButton.on_click += lambda _: self.delete_profile() | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name1.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name1.on_click += lambda _: self.enable_keyboard(0) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name2.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name2.on_click += lambda _: self.enable_keyboard(1) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name3.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name3.on_click += lambda _: self.enable_keyboard(2) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name4.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name4.on_click += lambda _: self.enable_keyboard(3) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name5.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name5.on_click += lambda _: self.enable_keyboard(4) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
self.player_name6.on_click += lambda _: self.keyboard.set_visible(True) | self.player_name6.on_click += lambda _: self.enable_keyboard(5) | def __init__ (self, parent = None): ui.VBox.__init__(self, parent) |
def save_profile(self, random): if self.check_info(): | def save_profile(self, name = 'Prove'): if self.check_info() and name <> 'Default': | def load_profile(self, name): index = 0 |
GlobalConf ().path ('profiles').adopt (self._profile, 'Prove') self._listprof.append('Prove') | GlobalConf ().path ('profiles').adopt (self._profile, name) self._listprof.append(name) | def save_profile(self, random): #Need to be modified in order to accept the name of the profile, also check first if the profile already exists if self.check_info(): self.create_profile() GlobalConf ().path ('profiles').adopt (self._profile, 'Prove') self._listprof.append('Prove') self.profile_ComboBox.load(self._listprof) self.update_status("Profile saved") |
def delete_profile(self, random): GlobalConf ().path('profiles').remove('Prove') self._listprof.remove('Prove') self.profile_ComboBox.load(self._listprof) self.update_status("Profile deleted") | def delete_profile(self, name = 'Prove'): if name <> 'Default': GlobalConf ().path('profiles').remove(name) self._listprof.remove(name) self.profile_ComboBox.load(self._listprof) self.update_status("Profile deleted") | def delete_profile(self, random): #Need to be modified in order to accept the name of the profile, also check first if the profile already exists and what happened when there is no profiles or create a default one which cannot be deleted |
self.update_status("It should open a new window in order to load the game") | self.update_status("Not implemented yet") | def load_game(self, random): |
self.SetCenter (cx - (dx*c - dy*s)/sx, cy - (dx*s + dy*c)/sy) | self.set_center (cx - (dx*c - dy*s)/sx, cy - (dx*s + dy*c)/sy) | def do_pan (self, (nx, ny)): _log.debug ('Do panning: ' + str ((nx, ny))) |
self._region = model | self.model = model | def __init__ (self, parent = None, model = None, *a, **k): assert parent assert model super (RegionComponent, self).__init__ (parent = parent, radius = _REGION_RADIUS, *a, **k) |
else self._region.owner.color)) | else self.model.owner.color)) | def on_set_region_owner (self): self._fill_color = sf.Color (*( _REGION_FREE_COLOR if self._region.owner is None else self._region.owner.color)) |
self.load_profile('Default') | def __init__ (self, parent = None): ui.Image.__init__(self, parent, 'data/image/texture01.jpg') |
|
else: self.mapL.select(i.get_value()) | def load_profile(self, name): |
|
self._region.definition.name) | self.model.definition.name) | def __init__ (self, parent = None, model = None, *a, **k): assert parent assert model super (RegionComponent, self).__init__ (parent = parent, radius = _REGION_RADIUS, *a, **k) |
_REGION_FREE_COLOR if self._region.owner is None | _REGION_FREE_COLOR if self.model.owner is None | def on_set_region_owner (self): self._fill_color = sf.Color (*( _REGION_FREE_COLOR if self._region.owner is None else self.model.owner.color)) |
suite = unittest.TestLoader().loadTestsFromTestCase(TestObjectives) unittest.TextTestRunner(verbosity=2).run(suite) | def test_check_objective_player (self): print "\nTesting check mission player" world = self.world obj = self.obj pla_obj = filter (lambda o: o.type == 'player',obj) random.shuffle(pla_obj) |
|
time.gmtime ( | time.localtime ( | def __init__ (self, parent = None, save_folder = '', *a, **k): super (LoadGameDialog, self).__init__ (parent, *a, **k) |
c = sphere(radius=50, color=(1., 0.,0.), pos=(x-AREA_X/2,y-AREA_Y/2,50)) | if BALL_CYLINDER == 1: c = cylinder(axis=(0,0,1), radius=50, length=CORN_HEIGHT, color=(1., 0.,0.), pos=(x-AREA_X/2,y-AREA_Y/2,CORN_HEIGHT/2)) else: c = sphere(radius=50, color=(1., 0.,0.), pos=(x-AREA_X/2,y-AREA_Y/2,50)) | def toggle_obj_disp(): global area_objects """ if area_objects == []: c = sphere(radius=5, color=(0., 0.,1.), pos=(1238.-AREA_X/2, 1313.-AREA_Y/2, 5)) area_objects.append(c) c = sphere(radius=5, color=(0., 0.,1.), pos=(1364.-AREA_X/2, 1097.-AREA_Y/2, 5)) area_objects.append(c) c = sphere(radius=5, color=(0., 0.,1.), pos=(1453.-AREA_X/2, 1176.-AREA_Y/2, 5)) area_objects.append(c) c = sphere(radius=5, color=(0., 0.,1.), pos=(1109.-AREA_X/2, 1050.-AREA_Y/2, 5)) area_objects.append(c) |
print "cobboard: %x,%x"%(int(m.groups()[0]),int(m.groups()[1])) | def silent_mkfifo(f): try: os.mkfifo(f) except: pass |
|
widget=MasterSelectWidget( | widget=SelectionWidget( | def getVocabMun(self,province): municipality = EntiVocabulary.comuni4provincia(province) return DisplayList(monetVocabMap(municipality)) |
def quotient(self, sub, check=True): | def quotient(self, sub, check=True, positive_point=None, positive_dual_point=None): | def quotient(self, sub, check=True): """ Return the quotient of ``self`` by the given sublattice ``sub``. |
Torsion quotient of 3-d lattice N by Sublattice <N(1, 8, 0), N(0, 12, 0)> | Quotient with torsion of 3-d lattice N by Sublattice <N(1, 8, 0), N(0, 12, 0)> See :class:`ToricLattice_quotient` for more examples. | def quotient(self, sub, check=True): """ Return the quotient of ``self`` by the given sublattice ``sub``. |
return ToricLattice_quotient(self, sub, check=False) | return ToricLattice_quotient(self, sub, check=False, positive_point=positive_point, positive_dual_point=positive_dual_point) | def quotient(self, sub, check=True): """ Return the quotient of ``self`` by the given sublattice ``sub``. |
1-d lattice, quotient of 3-d lattice N by Sublattice <N(1, 0, 1), N(0, 1, -1)> | 1-d lattice, quotient of 3-d lattice N by Sublattice <N(1, 0, 1), N(0, 1, -1)> sage: Q.gens() (N[0, 0, 1],) Here, ``sublattice`` happens to be of codimension one in ``N``. If you want to prescribe the sign of the quotient generator, you can do either:: sage: Q = N.quotient(sublattice, positive_point=N(0,0,-1)); Q 1-d lattice, quotient of 3-d lattice N by Sublattice <N(1, 0, 1), N(0, 1, -1)> sage: Q.gens() (N[0, 0, -1],) or:: sage: M = N.dual() sage: Q = N.quotient(sublattice, positive_dual_point=M(0,0,-1)); Q 1-d lattice, quotient of 3-d lattice N by Sublattice <N(1, 0, 1), N(0, 1, -1)> sage: Q.gens() (N[0, 0, -1],) TESTS:: sage: loads(dumps(Q)) == Q True sage: loads(dumps(Q)).gens() == Q.gens() True | def _latex_(self): r""" Return a LaTeX representation of ``self``. |
- integer. | Integer. The dimension of the free part of the quotient. | def rank(self): r""" Return the rank of ``self``. |
m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.match(r'GNU Fortran.*?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): return ('g77', v) | ctype = self.compiler_type f90 = set_exe('compiler_f90') if not f90: f77 = set_exe('compiler_f77') if f77: log.warn('%s: no Fortran 90 compiler found' % ctype) | def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" m = re.match(r'GNU Fortran', version_string) if not m: return None m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.match(r'GNU Fortran.*?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) |
return ('gfortran', v) def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': | raise CompilerNotFound('%s: f90 nor f77' % ctype) else: f77 = set_exe('compiler_f77', f90=f90) if not f77: log.warn('%s: no Fortran 77 compiler found' % ctype) set_exe('compiler_fix', f90=f90) set_exe('linker_so', f77=f77, f90=f90) set_exe('linker_exe', f77=f77, f90=f90) set_exe('version_cmd', f77=f77, f90=f90) set_exe('archiver') set_exe('ranlib') def update_executables(elf): """Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as the command, which will be replaced by the found F77 or F90 compiler. """ pass def get_flags(self): """List of flags common to all compiler types.""" return [] + self.pic_flags def _get_command_flags(self, key): cmd = self.executables.get(key, None) if cmd is None: return [] return cmd[1:] def get_flags_f77(self): """List of Fortran 77 specific flags.""" return self._get_command_flags('compiler_f77') def get_flags_f90(self): """List of Fortran 90 specific flags.""" return self._get_command_flags('compiler_f90') def get_flags_free(self): """List of Fortran 90 free format specific flags.""" return [] def get_flags_fix(self): """List of Fortran 90 fixed format specific flags.""" return self._get_command_flags('compiler_fix') def get_flags_linker_so(self): """List of linker flags to build a shared library.""" return self._get_command_flags('linker_so') def get_flags_linker_exe(self): """List of linker flags to build an executable.""" return self._get_command_flags('linker_exe') def get_flags_ar(self): """List of archiver flags. """ return self._get_command_flags('archiver') def get_flags_opt(self): """List of architecture independent compiler flags.""" return [] def get_flags_arch(self): """List of architecture dependent compiler flags.""" return [] def get_flags_debug(self): """List of compiler flags to compile with debugging information.""" return [] get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug def get_libraries(self): """List of compiler libraries.""" return self.libraries[:] def get_library_dirs(self): """List of compiler library directories.""" return self.library_dirs[:] def get_version(self, force=False, ok_status=[0]): assert self._is_customised return CCompiler.get_version(self, force=force, ok_status=ok_status) def customize(self, dist = None): """Customize Fortran compiler. This method gets Fortran compiler specific information from (i) class definition, (ii) environment, (iii) distutils config files, and (iv) command line (later overrides earlier). This method should be always called after constructing a compiler instance. But not in __init__ because Distribution instance is needed for (iii) and (iv). """ log.info('customize %s' % (self.__class__.__name__)) self._is_customised = True self.distutils_vars.use_distribution(dist) self.command_vars.use_distribution(dist) self.flag_vars.use_distribution(dist) self.update_executables() self.find_executables() noopt = self.distutils_vars.get('noopt', False) noarch = self.distutils_vars.get('noarch', noopt) debug = self.distutils_vars.get('debug', False) f77 = self.command_vars.compiler_f77 f90 = self.command_vars.compiler_f90 f77flags = [] f90flags = [] freeflags = [] fixflags = [] if f77: f77flags = self.flag_vars.f77 if f90: f90flags = self.flag_vars.f90 freeflags = self.flag_vars.free fix = self.command_vars.compiler_fix if fix: fixflags = self.flag_vars.fix + f90flags oflags, aflags, dflags = [], [], [] def get_flags(tag, flags): flags.extend(getattr(self.flag_vars, tag)) this_get = getattr(self, 'get_flags_' + tag) for name, c, flagvar in [('f77', f77, f77flags), ('f90', f90, f90flags), ('f90', fix, fixflags)]: t = '%s_%s' % (tag, name) if c and this_get is not getattr(self, 'get_flags_' + t): flagvar.extend(getattr(self.flag_vars, t)) if not noopt: get_flags('opt', oflags) if not noarch: get_flags('arch', aflags) if debug: get_flags('debug', dflags) fflags = self.flag_vars.flags + dflags + oflags + aflags if f77: self.set_commands(compiler_f77=[f77]+f77flags+fflags) if f90: self.set_commands(compiler_f90=[f90]+freeflags+f90flags+fflags) if fix: self.set_commands(compiler_fix=[fix]+fixflags+fflags) linker_so = self.linker_so if linker_so: linker_so_flags = self.flag_vars.linker_so if sys.platform.startswith('aix'): python_lib = get_python_lib(standard_lib=1) ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix') python_exp = os.path.join(python_lib, 'config', 'python.exp') linker_so = [ld_so_aix] + linker_so + ['-bI:'+python_exp] self.set_commands(linker_so=linker_so+linker_so_flags) linker_exe = self.linker_exe if linker_exe: linker_exe_flags = self.flag_vars.linker_exe self.set_commands(linker_exe=linker_exe+linker_exe_flags) ar = self.command_vars.archiver if ar: arflags = self.flag_vars.ar self.set_commands(archiver=[ar]+arflags) self.set_library_dirs(self.get_library_dirs()) self.set_libraries(self.get_libraries()) def dump_properties(self): """Print out the attributes of a compiler instance.""" props = [] for key in self.executables.keys() + \ ['version','libraries','library_dirs', 'object_switch','compile_switch']: if hasattr(self,key): v = getattr(self,key) props.append((key, None, '= '+repr(v))) props.sort() pretty_printer = FancyGetopt(props) for l in pretty_printer.generate_help("%s instance properties:" \ % (self.__class__.__name__)): if l[:4]==' --': l = ' ' + l[4:] print l def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" src_flags = {} if is_f_file(src) and not has_f90_header(src): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) elif is_free_format(src): flavor = ':f90' compiler = self.compiler_f90 if compiler is None: raise DistutilsExecError, 'f90 not supported by %s needed for %s'\ % (self.__class__.__name__,src) else: flavor = ':fix' compiler = self.compiler_fix if compiler is None: raise DistutilsExecError, 'f90 (fixed) not supported by %s needed for %s'\ % (self.__class__.__name__,src) if self.object_switch[-1]==' ': o_args = [self.object_switch.strip(),obj] else: o_args = [self.object_switch.strip()+obj] assert self.compile_switch.strip() s_args = [self.compile_switch, src] extra_flags = src_flags.get(self.compiler_type,[]) if extra_flags: log.info('using compile options from source: %r' \ % ' '.join(extra_flags)) command = compiler + cc_args + extra_flags + s_args + o_args \ + extra_postargs display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src) try: self.spawn(command,display=display) except DistutilsExecError, msg: raise CompileError, msg def module_options(self, module_dirs, module_build_dir): options = [] if self.module_dir_switch is not None: if self.module_dir_switch[-1]==' ': options.extend([self.module_dir_switch.strip(),module_build_dir]) else: options.append(self.module_dir_switch.strip()+module_build_dir) else: print 'XXX: module_build_dir=%r option ignored' % (module_build_dir) print 'XXX: Fix module_dir_switch for ',self.__class__.__name__ if self.module_include_switch is not None: for d in [module_build_dir]+module_dirs: options.append('%s%s' % (self.module_include_switch, d)) else: print 'XXX: module_dirs=%r option ignored' % (module_dirs) print 'XXX: Fix module_include_switch for ',self.__class__.__name__ return options def library_option(self, lib): return "-l" + lib def library_dir_option(self, dir): return "-L" + dir def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): objects, output_dir = self._fix_object_args(objects, output_dir) libraries, library_dirs, runtime_library_dirs = \ self._fix_lib_args(libraries, library_dirs, runtime_library_dirs) lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries) if is_string(output_dir): output_filename = os.path.join(output_dir, output_filename) elif output_dir is not None: raise TypeError, "'output_dir' must be a string or None" if self._need_link(objects, output_filename): if self.library_switch[-1]==' ': o_args = [self.library_switch.strip(),output_filename] else: o_args = [self.library_switch.strip()+output_filename] if is_string(self.objects): ld_args = objects + [self.objects] else: ld_args = objects + self.objects ld_args = ld_args + lib_opts + o_args if debug: ld_args[:0] = ['-g'] if extra_preargs: ld_args[:0] = extra_preargs if extra_postargs: ld_args.extend(extra_postargs) self.mkpath(os.path.dirname(output_filename)) if target_desc == CCompiler.EXECUTABLE: linker = self.linker_exe[:] else: linker = self.linker_so[:] command = linker + ld_args try: self.spawn(command) except DistutilsExecError, msg: raise LinkError, msg else: log.debug("skipping %s (up-to-date)", output_filename) def _environment_hook(self, name, hook_name): if hook_name is None: | def gnu_version_match(self, version_string): """Handle the different versions of GNU fortran compilers""" m = re.match(r'GNU Fortran', version_string) if not m: return None m = re.match(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.match(r'GNU Fortran.*?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) |
return v[1] possible_executables = ['g77', 'f77'] executables = { 'version_cmd' : [None, "--version"], 'compiler_f77' : [None, "-g", "-Wall", "-fno-second-underscore"], 'compiler_f90' : None, 'compiler_fix' : None, 'linker_so' : [None, "-g", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-g", "-Wall"] } module_dir_switch = None module_include_switch = None if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') g2c = 'g2c' suggested_f90_compiler = 'gnu95' def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform=='darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) if not target: import distutils.sysconfig as sc g = {} filename = sc.get_makefile_filename() sc.parse_makefile(filename, g) target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = target if target == '10.3': s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3' warnings.warn(s) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) | if is_string(hook_name): if hook_name.startswith('self.'): hook_name = hook_name[5:] hook = getattr(self, hook_name) return hook() elif hook_name.startswith('exe.'): hook_name = hook_name[4:] var = self.executables[hook_name] if var: return var[0] else: return None elif hook_name.startswith('flags.'): hook_name = hook_name[6:] hook = getattr(self, 'get_flags_' + hook_name) return hook() | def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': return None return v[1] |
opt.append("-shared") if sys.platform.startswith('sunos'): opt.append('-mimpure-text') return opt def get_libgcc_dir(self): status, output = exec_command(self.compiler_f77 + ['-print-libgcc-file-name'], use_tee=0) if not status: return os.path.dirname(output) | return hook_name() _default_compilers = ( ('win32', ('gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), ('cygwin.*', ('sage_fortran', 'gnu','intelv','absoft','compaqv','intelev','gnu95','g95')), ('linux.*', ('sage_fortran','gnu','intel','lahey','pg','absoft','nag','vast','compaq', 'intele','intelem','gnu95','g95')), ('darwin.*', ('sage_fortran','nag', 'absoft', 'ibm', 'intel', 'gnu', 'gnu95', 'g95')), ('sunos.*', ('sage_fortran','sun','gnu','gnu95','g95')), ('irix.*', ('mips','gnu','gnu95',)), ('aix.*', ('ibm','gnu','gnu95',)), ('posix', ('gnu','gnu95',)), ('nt', ('gnu','gnu95',)), ('mac', ('gnu','gnu95',)), ) fcompiler_class = None fcompiler_aliases = None if os.popen("sage_fortran --version").read().startswith('GNU Fortran'): import gnu cls=gnu.Sage_FCompiler_1 else: import gnu cls=gnu.Sage_FCompiler def load_all_fcompiler_classes(): """Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package. """ from glob import glob global fcompiler_class, fcompiler_aliases,cls if fcompiler_class is not None: return pys = os.path.join(os.path.dirname(__file__), '*.py') fcompiler_class = {} fcompiler_aliases = {} for fname in glob(pys): module_name, ext = os.path.splitext(os.path.basename(fname)) module_name = 'numpy.distutils.fcompiler.' + module_name __import__ (module_name) module = sys.modules[module_name] if hasattr(module, 'compilers'): for cname in module.compilers: klass = getattr(module, cname) desc = (klass.compiler_type, klass, klass.description) fcompiler_class[klass.compiler_type] = desc for alias in klass.compiler_aliases: if alias in fcompiler_aliases: raise ValueError("alias %r defined for both %s and %s" % (alias, klass.__name__, fcompiler_aliases[alias][1].__name__)) fcompiler_aliases[alias] = desc fcompiler_class['sage_fortran']=('gnu',cls,"GNU Fortran (GCC)") def _find_existing_fcompiler(compiler_types, osname=None, platform=None, requiref90=False, c_compiler=None): from numpy.distutils.core import get_distribution dist = get_distribution(always=True) for compiler_type in compiler_types: v = None try: c = new_fcompiler(plat=platform, compiler=compiler_type, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if requiref90 and c.compiler_f90 is None: v = None new_compiler = c.suggested_f90_compiler if new_compiler: log.warn('Trying %r compiler as suggested by %r ' 'compiler for f90 support.' % (compiler_type, new_compiler)) c = new_fcompiler(plat=platform, compiler=new_compiler, c_compiler=c_compiler) c.customize(dist) v = c.get_version() if v is not None: compiler_type = new_compiler if requiref90 and c.compiler_f90 is None: raise ValueError('%s does not support compiling f90 codes, ' 'skipping.' % (c.__class__.__name__)) except DistutilsModuleError: log.debug("_find_existing_fcompiler: compiler_type='%s' raised DistutilsModuleError", compiler_type) except CompilerNotFound: log.debug("_find_existing_fcompiler: compiler_type='%s' not found", compiler_type) if v is not None: return compiler_type return None def available_fcompilers_for_platform(osname=None, platform=None): if osname is None: osname = os.name if platform is None: platform = sys.platform matching_compiler_types = [] for pattern, compiler_type in _default_compilers: if re.match(pattern, platform) or re.match(pattern, osname): for ct in compiler_type: if ct not in matching_compiler_types: matching_compiler_types.append(ct) if not matching_compiler_types: matching_compiler_types.append('gnu') return matching_compiler_types def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): """Determine the default Fortran compiler to use for the given platform.""" matching_compiler_types = available_fcompilers_for_platform(osname, platform) compiler_type = _find_existing_fcompiler(matching_compiler_types, osname=osname, platform=platform, requiref90=requiref90, c_compiler=c_compiler) return compiler_type def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler = None): """Generate an instance of some FCompiler subclass for the supplied platform/compiler combination. """ load_all_fcompiler_classes() if plat is None: plat = os.name if compiler is None: compiler = get_default_fcompiler(plat, requiref90=requiref90, c_compiler=c_compiler) if compiler in fcompiler_class: module_name, klass, long_description = fcompiler_class[compiler] elif compiler in fcompiler_aliases: module_name, klass, long_description = fcompiler_aliases[compiler] else: msg = "don't know how to compile Fortran code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler." % compiler msg = msg + " Supported compilers are: %s)" \ % (','.join(fcompiler_class.keys())) log.warn(msg) | def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform=='darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) # If MACOSX_DEPLOYMENT_TARGET is set, we simply trust the value # and leave it alone. But, distutils will complain if the # environment's value is different from the one in the Python # Makefile used to build Python. We let disutils handle this # error checking. if not target: # If MACOSX_DEPLOYMENT_TARGET is not set in the environment, # we try to get it first from the Python Makefile and then we # fall back to setting it to 10.3 to maximize the set of # versions we can work with. This is a reasonable default # even when using the official Python dist and those derived # from it. import distutils.sysconfig as sc g = {} filename = sc.get_makefile_filename() sc.parse_makefile(filename, g) target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = target if target == '10.3': s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3' warnings.warn(s) |
def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: if sys.platform == 'win32' and not d.startswith('/usr/lib'): d = os.path.normpath(d) if not os.path.exists(os.path.join(d, "lib%s.a" % self.g2c)): d2 = os.path.abspath(os.path.join(d, '../../../../lib')) if os.path.exists(os.path.join(d2, "lib%s.a" % self.g2c)): opt.append(d2) opt.append(d) return opt def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d,f)): g2c = self.g2c | compiler = klass(verbose=verbose, dry_run=dry_run, force=force) compiler.c_compiler = c_compiler return compiler def show_fcompilers(dist=None): """Print list of available compilers (used by the "--help-fcompiler" option to "config_fc"). """ if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() dist.script_name = os.path.basename(sys.argv[0]) dist.script_args = ['config_fc'] + sys.argv[1:] try: dist.script_args.remove('--help-fcompiler') except ValueError: pass dist.cmdclass['config_fc'] = config_fc dist.parse_config_files() dist.parse_command_line() compilers = [] compilers_na = [] compilers_ni = [] if not fcompiler_class: load_all_fcompiler_classes() platform_compilers = available_fcompilers_for_platform() for compiler in platform_compilers: v = None log.set_verbosity(-2) try: c = new_fcompiler(compiler=compiler, verbose=dist.verbose) c.customize(dist) v = c.get_version() except (DistutilsModuleError, CompilerNotFound), e: log.debug("show_fcompilers: %s not found" % (compiler,)) log.debug(repr(e)) if v is None: compilers_na.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2])) | def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: # if windows and not cygwin, libg2c lies in a different folder if sys.platform == 'win32' and not d.startswith('/usr/lib'): d = os.path.normpath(d) if not os.path.exists(os.path.join(d, "lib%s.a" % self.g2c)): d2 = os.path.abspath(os.path.join(d, '../../../../lib')) if os.path.exists(os.path.join(d2, "lib%s.a" % self.g2c)): opt.append(d2) opt.append(d) return opt |
g2c = self.g2c if g2c is not None: opt.append(g2c) c_compiler = self.c_compiler if sys.platform == 'win32' and c_compiler and \ c_compiler.compiler_type=='msvc': opt.append('gcc') runtime_lib = msvc_runtime_library() if runtime_lib: opt.append(runtime_lib) if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): if self.get_version()<='3.3.3': opt = ['-O2'] else: opt = ['-O3'] opt.append('-funroll-loops') return opt def get_flags_arch(self): return [] return opt class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' compiler_aliases = ('gfortran',) description = 'GNU Fortran 95 compiler' def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'gfortran': return None return v[1] possible_executables = ['gfortran', 'f95'] executables = { 'version_cmd' : ["<F90>", "--version"], 'compiler_f77' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"], 'compiler_f90' : [None, "-Wall", "-fno-second-underscore"], 'compiler_fix' : [None, "-Wall", "-ffixed-form", "-fno-second-underscore"], 'linker_so' : ["<F90>", "-Wall"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : [None, "-Wall"] } if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') module_dir_switch = '-J' module_include_switch = '-I' g2c = 'gfortran' def _can_target(self, cmd, arch): """Return true is the compiler support the -arch flag for the given architecture.""" newcmd = cmd[:] st, out = exec_command(" ".join(newcmd)) if st == 0: for line in out.splitlines(): m = re.search(_R_ARCHS[arch], line) if m: return True return False 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"]: if self._can_target(cmd, arch): arch_flags.extend(["-arch", arch]) return arch_flags def get_flags(self): flags = GnuFCompiler.get_flags(self) arch_flags = self._universal_flags(self.compiler_f90) if arch_flags: flags[:0] = arch_flags return flags def get_flags_linker_so(self): flags = GnuFCompiler.get_flags_linker_so(self) arch_flags = self._universal_flags(self.linker_so) if arch_flags: flags[:0] = arch_flags return flags def get_library_dirs(self): opt = GnuFCompiler.get_library_dirs(self) if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": target = self.get_target() if target: d = os.path.normpath(self.get_libgcc_dir()) root = os.path.join(d, os.pardir, os.pardir, os.pardir, os.pardir) mingwdir = os.path.normpath(os.path.join(root, target, "lib")) full = os.path.join(mingwdir, "libmingwex.a") if os.path.exists(full): opt.append(mingwdir) return opt def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == "msvc": if "gcc" in opt: i = opt.index("gcc") opt.insert(i+1, "mingwex") opt.insert(i+1, "mingw32") return opt def get_target(self): status, output = exec_command(self.compiler_f77 + ['-v'], use_tee=0) if not status: m = TARGET_R.search(output) if m: return m.group(1) return "" class Sage_FCompiler_1(Gnu95FCompiler): compiler_type = 'gnu95' version_match = simple_version_match(start='GNU Fortran') executables = { 'version_cmd' : ["sage_fortran","--version"], 'compiler_f77' : ["sage_fortran","-Wall","-ffixed-form","-fno-second-underscore"], 'compiler_f90' : ["sage_fortran","-Wall","-fno-second-underscore"], 'compiler_fix' : ["sage_fortran","-Wall","-ffixed-form","-fno-second-underscore"], 'linker_so' : ["sage_fortran","-Wall","-shared"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : ["sage_fortran","-Wall"] } if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') def find_executables(self): pass module_dir_switch = '-J' module_include_switch = '-I' g2c = 'gfortran' def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') return opt class Sage_FCompiler(FCompiler): compiler_type = 'g95' version_pattern = r'G95 \((GCC (?P<gccversion>[\d.]+)|.*?) \(g95 (?P<version>.*)!\) (?P<date>.*)\).*' suggested_f90_compiler = 'sage_fortran' if os.uname()[0]=="Darwin": link_command=["sage_fortran","-undefined", "dynamic_lookup", "-bundle"] else: link_command=["sage_fortran","-shared"] executables = { 'version_cmd' : ["sage_fortran", "--version"], 'compiler_f77' : ["sage_fortran", "-ffixed-form"], 'compiler_fix' : ["sage_fortran", "-ffixed-form"], 'compiler_f90' : ["sage_fortran"], 'linker_so' : link_command, 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"], 'linker_exe' : ["sage_fortran",""] } pic_flags = ['-fpic'] module_dir_switch = '-fmod=' module_include_switch = '-I' def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform=='darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) if target is None or target == '': target = '10.3' major, minor = target.split('.') if int(minor) < 3: minor = '3' warnings.warn('Environment variable ' 'MACOSX_DEPLOYMENT_TARGET reset to %s.%s' % (major, minor)) os.environ['MACOSX_DEPLOYMENT_TARGET'] = '%s.%s' % (major, minor) if sys.platform[:5]=='sunos': opt.append('-mimpure-text') return opt def get_library_dirs(self): SAGE_LOCAL=os.environ['SAGE_LOCAL'] GCC_LIB_DIR=SAGE_LOCAL+"/lib/" if os.path.exists(GCC_LIB_DIR + "gcc-lib"): GCC_LIB_DIR += "gcc-lib/" GCC_LIB_DIR += os.listdir(GCC_LIB_DIR)[0] + "/" GCC_LIB_DIR += os.listdir(GCC_LIB_DIR)[0] + "/" return [GCC_LIB_DIR] def get_libraries(self): l=[] if os.uname()[-1] == 'Power Macintosh': l.append('SystemStubs') else: if os.uname()[0].startswith('Linux'): l.append('f95') return l def get_flags(self): return ['-fno-second-underscore'] def get_flags_opt(self): return ['-O'] def get_flags_debug(self): return ['-g'] | c.dump_properties() compilers.append(("fcompiler="+compiler, None, fcompiler_class[compiler][2] + ' (%s)' % v)) compilers_ni = list(set(fcompiler_class.keys()) - set(platform_compilers)) compilers_ni = [("fcompiler="+fc, None, fcompiler_class[fc][2]) for fc in compilers_ni] compilers.sort() compilers_na.sort() compilers_ni.sort() pretty_printer = FancyGetopt(compilers) pretty_printer.print_help("Fortran compilers found:") pretty_printer = FancyGetopt(compilers_na) pretty_printer.print_help("Compilers available for this " "platform, but not found:") if compilers_ni: pretty_printer = FancyGetopt(compilers_ni) pretty_printer.print_help("Compilers not available on this platform:") print "For compiler details, run 'config_fc --verbose' setup command." def dummy_fortran_file(): fo, name = make_temp_file(suffix='.f') fo.write(" subroutine dummy()\n end\n") fo.close() return name[:-2] is_f_file = re.compile(r'.*[.](for|ftn|f77|f)\Z',re.I).match _has_f_header = re.compile(r'-[*]-\s*fortran\s*-[*]-',re.I).search _has_f90_header = re.compile(r'-[*]-\s*f90\s*-[*]-',re.I).search _has_fix_header = re.compile(r'-[*]-\s*fix\s*-[*]-',re.I).search _free_f90_start = re.compile(r'[^c*!]\s*[^\s\d\t]',re.I).match def is_free_format(file): """Check if file is in free format Fortran.""" result = 0 f = open(file,'r') line = f.readline() n = 10000 if _has_f_header(line): n = 0 elif _has_f90_header(line): n = 0 result = 1 while n>0 and line: line = line.rstrip() if line and line[0]!='!': n -= 1 if (line[0]!='\t' and _free_f90_start(line[:5])) or line[-1:]=='&': result = 1 break line = f.readline() f.close() return result def has_f90_header(src): f = open(src,'r') line = f.readline() f.close() return _has_f90_header(line) or _has_fix_header(line) _f77flags_re = re.compile(r'(c|)f77flags\s*\(\s*(?P<fcname>\w+)\s*\)\s*=\s*(?P<fflags>.*)',re.I) 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 fcname = m.group('fcname').strip() fflags = m.group('fflags').strip() flags[fcname] = split_quoted(fflags) f.close() return flags | def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d,f)): g2c = self.g2c else: g2c = self.g2c |
from distutils import log log.set_verbosity(2) compiler = GnuFCompiler() compiler.customize() print compiler.get_version() raw_input('Press ENTER to continue...') try: compiler = Gnu95FCompiler() compiler.customize() print compiler.get_version() except Exception, msg: print msg raw_input('Press ENTER to continue...') | show_fcompilers() | def get_flags_debug(self): return ['-g'] |
def pdflatex(self, t = None): """ | def pdflatex(self, t = None): """ This is deprecated. Use engine("pdflatex") instead. | def pdflatex(self, t = None): """ Controls whether Sage uses PDFLaTeX or LaTeX when typesetting with :func:`view`, in ``%latex`` cells, etc. |
return _Latex_prefs._option["pdflatex"] _Latex_prefs._option["pdflatex"] = bool(t) | from sage.misc.misc import deprecation deprecation('Use engine() instead.') return _Latex_prefs._option["engine"] == "pdflatex" elif t: from sage.misc.misc import deprecation deprecation('Use engine("pdflatex") instead.') self.engine("pdflatex") else: from sage.misc.misc import deprecation deprecation('Use engine("latex") instead.') self.engine("latex") def engine(self, e = None): r""" Set Sage to use ``e`` as latex engine when typesetting with :func:`view`, in ``%latex`` cells, etc. INPUT: - ``e`` -- 'latex', 'pdflatex', 'xelatex' or None If ``e`` is None, return the current engine. If using the XeLaTeX engine, it will almost always be necessary to set the proper preamble with :func:`extra_preamble` or :func:`add_to_preamble`. For example:: latex.extra_preamble(r'''\usepackage{fontspec,xunicode,xltxtra} \setmainfont[Mapping=tex-text]{some font here} \setmonofont[Mapping=tex-text]{another font here}''') EXAMPLES:: sage: latex.engine() 'latex' sage: latex.engine("pdflatex") sage: latex.engine() 'pdflatex' sage: latex.engine("xelatex") sage: latex.engine() 'xelatex' """ if e is None: return _Latex_prefs._option["engine"] if e == "latex": _Latex_prefs._option["engine"] = "latex" _Latex_prefs._option["engine_name"] = "LaTeX" elif e == "pdflatex": _Latex_prefs._option["engine"] = "pdflatex" _Latex_prefs._option["engine_name"] = "PDFLaTeX" elif e == "xelatex": _Latex_prefs._option["engine"] = e _Latex_prefs._option["engine_name"] = "XeLaTeX" else: raise ValueError, "%s is not a supported LaTeX engine. Use latex, pdflatex, or xelatex" % e | def pdflatex(self, t = None): """ Controls whether Sage uses PDFLaTeX or LaTeX when typesetting with :func:`view`, in ``%latex`` cells, etc. |
the computation again but turn off the second descent:: | the computation again but turn off ``second_descent``:: | def selmer_rank(self): r""" Returns the rank of the 2-Selmer group of the curve. |
but with no 2-torsion, the selmer rank is strictly greater | but with no 2-torsion, the Selmer rank is strictly greater | def selmer_rank(self): r""" Returns the rank of the 2-Selmer group of the curve. |
all primes up to `max_prime`. If `-1` (default) then an | all primes up to ``max_prime``. If `-1` (the default), an | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
computed bound is greater than a value set by the eclib | computed bound is greater than a value set by the ``eclib`` | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
- ``odd_primes_only`` (bool, default False) -- only do | - ``odd_primes_only`` (bool, default ``False``) -- only do | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
via 2-descent they should alreday be 2-saturated.) | via :meth:``two_descent()`` they should already be 2-saturated.) | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
- ``ok`` (bool) is True if and only if the saturation was | - ``ok`` (bool) -- ``True`` if and only if the saturation was | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
the computed saturation bound being too high, then True indicates that the subgroup is saturated at `\emph{all}` | the computed saturation bound being too high, then ``True`` indicates that the subgroup is saturated at *all* | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
- ``index`` (int) is the index of the group generated by the | - ``index`` (int) -- the index of the group generated by the | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
uses floating points methods based on elliptic logarithms to | uses floating point methods based on elliptic logarithms to | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
We emphasize that if this function returns True as the first return argument, and if the default was used for the parameter ``sat_bnd``, then the points in the basis after calling this function are saturated at `\emph{all}` primes, | We emphasize that if this function returns ``True`` as the first return argument (``ok``), and if the default was used for the parameter ``max_prime``, then the points in the basis after calling this function are saturated at *all* primes, | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
saturate up to, and that prime is `\leq` ``max_prime``. | saturate up to, and that prime might be smaller than ``max_prime``. | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
calling search. So calling search up to height 20 then calling saturate results in another search up to height 18. | calling :meth:`search()`. So calling :meth:`search()` up to height 20 then calling :meth:`saturate()` results in another search up to height 18. | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
Subgroup of Mordell Weil group: [[1547:-2967:343], [2707496766203306:864581029138191:2969715140223272], [-13422227300:-49322830557:12167000000]] | Subgroup of Mordell-Weil group: [[1547:-2967:343], [2707496766203306:864581029138191:2969715140223272], [-13422227300:-49322830557:12167000000]] | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
Subgroup of Mordell Weil group: [[-2:3:1], [2707496766203306:864581029138191:2969715140223272], [-13422227300:-49322830557:12167000000]] | Subgroup of Mordell-Weil group: [[-2:3:1], [2707496766203306:864581029138191:2969715140223272], [-13422227300:-49322830557:12167000000]] | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
Subgroup of Mordell Weil group: [[-2:3:1], [-14:25:8], [-13422227300:-49322830557:12167000000]] | Subgroup of Mordell-Weil group: [[-2:3:1], [-14:25:8], [-13422227300:-49322830557:12167000000]] | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
Subgroup of Mordell Weil group: [[-2:3:1], [-14:25:8], [1:-1:1]] | Subgroup of Mordell-Weil group: [[-2:3:1], [-14:25:8], [1:-1:1]] | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
Of course, the ``process`` function would have done all this | Of course, the :meth:`process()` function would have done all this | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
But we would still need to use the ``saturate`` function to | But we would still need to use the :meth:`saturate()` function to | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
side-effect. It proves that the inde of the points in their | side-effect. It proves that the index of the points in their | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
by reducing the poits modulo all primes of good reduction up | by reducing the points modulo all primes of good reduction up | def saturate(self, max_prime=-1, odd_primes_only=False): r""" Saturate this subgroup of the Mordell-Weil group. |
sage: latex(maxima(derivative(ceil(x*y*d), d,x,x,y))) d^3\,\left({{{\it \partial}^4}\over{{\it \partial}\,d^4}}\, {\it ceil}\left(d , x , y\right)\right)\,x^2\,y^3+5\,d^2\,\left({{ {\it \partial}^3}\over{{\it \partial}\,d^3}}\,{\it ceil}\left(d , x , y\right)\right)\,x\,y^2+4\,d\,\left({{{\it \partial}^2}\over{ {\it \partial}\,d^2}}\,{\it ceil}\left(d , x , y\right)\right)\,y | sage: f = function('f') sage: latex(maxima(derivative(f(x*y*d), d,x,x,y))) Traceback (most recent call last): ... NotImplementedError: arguments must be distinct variables sage: latex(maxima(derivative(f(x,y,d), d,x,x,y))) {{{\it \partial}^4}\over{{\it \partial}\,d\,{\it \partial}\,x^2\, {\it \partial}\,y}}\,f\left(x , y , d\right) | def _latex_(self): """ Return Latex representation of this Maxima object. |
Return the rational points on this curve computed via enumeration. | Return a generator object for the rational points on this curve. | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
- ``algorithm`` (string, default: 'enum') -- the algorithm to use. Currently this is ignored. - ``sort`` (boolean, default ``True``) -- whether the output points should be sorted. If False, the order of the output is non-deterministic. | - ``self`` -- a projective curve | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
A list of all the rational points on the curve defined over its base field, possibly sorted. .. note:: This is a slow Python-level implementation. EXAMPLES:: sage: F = GF(5) | A generator of all the rational points on the curve defined over its base field. EXAMPLE:: sage: F = GF(37) | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
sage: C = Curve(X^3+Y^3-Z^3) sage: C.rational_points() [(0 : 1 : 1), (1 : 0 : 1), (2 : 2 : 1), (3 : 4 : 1), (4 : 1 : 0), (4 : 3 : 1)] sage: C.rational_points(sort=False) [(4 : 1 : 0), (1 : 0 : 1), (0 : 1 : 1), (2 : 2 : 1), (4 : 3 : 1), (3 : 4 : 1)] | sage: C = Curve(X^7+Y*X*Z^5*55+Y^7*12) sage: len(list(C.rational_points_iterator())) 37 | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
sage: F = GF(1009) | sage: F = GF(2) | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
sage: C = Curve(X^5+12*X*Y*Z^3 + X^2*Y^3 - 13*Y^2*Z^3) sage: len(C.rational_points()) 1043 | sage: C = Curve(X*Y*Z) sage: a = C.rational_points_iterator() sage: a.next() (1 : 0 : 0) sage: a.next() (0 : 1 : 0) sage: a.next() (1 : 1 : 0) sage: a.next() (0 : 0 : 1) sage: a.next() (1 : 0 : 1) sage: a.next() (0 : 1 : 1) sage: a.next() Traceback (most recent call last): ... StopIteration | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
sage: F = GF(2^6,'a') | sage: F = GF(3^2,'a') | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
sage: C = Curve(X^5+11*X*Y*Z^3 + X^2*Y^3 - 13*Y^2*Z^3) sage: len(C.rational_points()) 104 :: sage: R.<x,y,z> = GF(2)[] sage: f = x^3*y + y^3*z + x*z^3 sage: C = Curve(f); pts = C.rational_points() sage: pts [(0 : 0 : 1), (0 : 1 : 0), (1 : 0 : 0)] | sage: C = Curve(X^3+5*Y^2*Z-33*X*Y*X) sage: b = C.rational_points_iterator() sage: b.next() (0 : 1 : 0) sage: b.next() (0 : 0 : 1) sage: b.next() (2*a + 2 : 2*a : 1) sage: b.next() (2 : a + 1 : 1) sage: b.next() (a + 1 : a + 2 : 1) sage: b.next() (1 : 2 : 1) sage: b.next() (2*a + 2 : a : 1) sage: b.next() (2 : 2*a + 2 : 1) sage: b.next() (a + 1 : 2*a + 1 : 1) sage: b.next() (1 : 1 : 1) sage: b.next() Traceback (most recent call last): ... StopIteration | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
points.append(self.point([one,zero,zero])) | t = self.point([one,zero,zero]) yield(t) | def rational_points(self, algorithm="enum", sort=True): r""" Return the rational points on this curve computed via enumeration. |
Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. | Return a list of the associated primes of primary ideals of which the intersection is `I` = ``self``. | def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. |
- ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...] | - ``list`` - a list of associated primes | def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. |
sage: W = Words('123') sage: W('1212').is_square() True sage: W('1213').is_square() False sage: W('12123').is_square() False sage: W().is_square() | sage: Word('1212').is_square() True sage: Word('1213').is_square() False sage: Word('12123').is_square() False sage: Word().is_square() | def is_square(self): r""" Returns True if self is a square, and False otherwise. |
sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True TESTS:: sage: W = Words('123') sage: W('11').is_square_free() False sage: W('211').is_square_free() False sage: W('3211').is_square_free() False """ l = self.length() if l < 2: | sage: Word('12312').is_square_free() True sage: Word('31212').is_square_free() False sage: Word().is_square_free() True TESTS: We make sure that sage: Word('11').is_square_free() False sage: Word('211').is_square_free() False sage: Word('3211').is_square_free() False """ L = self.length() if L < 2: | def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. |
suff = self for i in xrange(0, l-1): for ll in xrange(2, l-i+1, 2): if suff[:ll].is_square(): | for start in xrange(0, L-1): for end in xrange(start+2, L+1, 2): if self[start:end].is_square(): | def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.