def index(self): c.items=[] c.flash="" maxver = meta.Session.query(CustomSet.setname.label('setname'), sa.func.max(CustomSet.version).label('maxver')).group_by(CustomSet.setname).subquery() c.newset=datetime.strftime(datetime.utcnow(),"%Y-%m-%d %H:%M") for res in meta.Session.query(CustomSets,maxver).filter( sa.and_( CustomSets.user==session['user'], CustomSets.setname==maxver.c.setname)).all(): print repr(res) custom,setname,maxver=res assert setname==custom.setname c.items.append(dict( setname=custom.setname, active=custom.active, ready=custom.ready, current=maxver)) return render('/customsets.mako')
def index(self): when,valid,fct=gfs_weather.get_prognosis(datetime.utcnow()) lat=59.45862 lon=17.70680 c.qnh=1013 c.winddir=0 c.windvel=0 c.defaddata=self.load_ad_json(extra_airfields.frolunda) c.field=u"Frölunda" c.searchurl=h.url_for(controller='sufperformance',action='search') c.airport_load_url=h.url_for(controller='sufperformance',action='load') metar=metartaf.get_metar('ESSA') print "metar:",metar try: c.temp,dew=re.match(r".*\b(\d{2})/(\d{2})\b.*",metar.text).groups() print "c.temp:",c.temp if c.temp.startswith("M"): c.temp=-int(c.temp[1:]) else: c.temp=int(c.temp) except: c.temp=15 try: c.qnh=fct.get_qnh(lat,lon) if c.qnh<10: c.qnh=1013 c.winddir,c.windvel=fct.get_surfacewind(lat,lon) c.winddir=int(c.winddir) c.windvel=int(c.windvel) except: print traceback.format_exc() pass return render('/sufperformance.mako')
def index(self): host = request.headers.get('Host', None) if host: host = host.lower() if host in static_subhosts: try: ret = open( os.path.join(os.getenv('SWFP_ROOT'), static_subhosts[host])).read() response.headers['Content-Type'] = 'text/html' return ret except: print traceback.format_exc() return "An error occurred" c.expl = request.params.get("explanation", "") ua = request.headers.get('User-Agent', '').lower() c.browserwarningheader = None try: c.mem = find_free_mem() except Exception: c.mem = 0 if ua.count("msie") and not (ua.count("firefox") or ua.count("chrome")): #MSIE detect c.browserwarningheader = u"You are running Internet Explorer." c.browserwarning=u"This is not recommended, although it should work."+\ u"Please install <a style=\"color:#4040ff\" href=\"http://www.google.com/chrome/\">Google Chrome</a> "+\ u"or <a style=\"color:#4040ff\" href=\"http://www.firefox.com\">Mozilla Firefox</a>.<br/> It's easy!" return render('/splash.mako')
def index(self): host=request.headers.get('Host',None) if host: host=host.lower() if host in static_subhosts: try: ret=open(os.path.join(os.getenv('SWFP_ROOT'),static_subhosts[host])).read() response.headers['Content-Type'] = 'text/html' return ret except: print traceback.format_exc() return "An error occurred" c.expl=request.params.get("explanation","") ua=request.headers.get('User-Agent','').lower() c.browserwarningheader=None try: c.mem=find_free_mem() except Exception: c.mem=0 if ua.count("msie") and not (ua.count("firefox") or ua.count("chrome")): #MSIE detect c.browserwarningheader=u"You are running Internet Explorer." c.browserwarning=u"This is not recommended, although it should work."+\ u"Please install <a style=\"color:#4040ff\" href=\"http://www.google.com/chrome/\">Google Chrome</a> "+\ u"or <a style=\"color:#4040ff\" href=\"http://www.firefox.com\">Mozilla Firefox</a>.<br/> It's easy!"; return render('/splash.mako')
def enroutenotams(self): c.techroute, c.route = get_route(tripuser(), session['current_trip']) c.tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() if len(c.route) == 0 or len(c.techroute) == 0: redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) return c.trip = c.tripobj.trip for rt in c.route: rt.notampoints = dict() rt.notampoints.update( dict([(info['item']['notam'], info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos), 5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)): rt.notampoints[space['name']] = space c.thislink = h.url_for(controller='flightplan', action="enroutenotams") return render('/enroutenotams.mako')
def fuel(self): #routes=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) #tripobj=meta.Session.query(Trip).filter(sa.and_( # Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() # #c.trip=tripobj.trip #c.all_aircraft=list(meta.Session.query(Aircraft).filter(sa.and_( # Aircraft.user==session['user'])).order_by(Aircraft.aircraft).all()) #c.startfuel=0#tripobj.startfuel self.standard_prep(c) if c.tripobj.acobj==None: c.routes=[] c.acwarn=True c.ac=None c.endfuel=0 else: c.routes=c.techroute c.acwarn=False c.ac=c.tripobj.acobj if len(c.routes)>0: c.endfuel=c.routes[-1].accum_fuel_left else: c.endfuel=0 c.performance="ok" c.sharing=tripsharing.sharing_active() for rt in c.routes: if rt.performance!="ok": c.performance="notok" meta.Session.flush(); meta.Session.commit() return render('/fuel.mako')
def fuel(self): #routes=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) #tripobj=meta.Session.query(Trip).filter(sa.and_( # Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() # #c.trip=tripobj.trip #c.all_aircraft=list(meta.Session.query(Aircraft).filter(sa.and_( # Aircraft.user==session['user'])).order_by(Aircraft.aircraft).all()) #c.startfuel=0#tripobj.startfuel self.standard_prep(c) if c.tripobj.acobj == None: c.routes = [] c.acwarn = True c.ac = None c.endfuel = 0 else: c.routes = c.techroute c.acwarn = False c.ac = c.tripobj.acobj if len(c.routes) > 0: c.endfuel = c.routes[-1].accum_fuel_left else: c.endfuel = 0 c.performance = "ok" c.sharing = tripsharing.sharing_active() for rt in c.routes: if rt.performance != "ok": c.performance = "notok" meta.Session.flush() meta.Session.commit() return render('/fuel.mako')
def gpx(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname', None), exception=False): return "Internal error. Missing trip-name or user-session." waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all()) if len(waypoints) == 0: return redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) c.waypoints = [] for wp in waypoints: lat, lon = mapper.from_str(wp.pos) c.waypoints.append(dict(lat=lat, lon=lon, name=wp.waypoint)) #response.headers['Content-Type'] = 'application/xml' response.content_type = 'application/octet-stream' response.charset = "utf8" return render('/gpx.mako')
def index(self): if not 'user' in session: redirect(h.url_for(controller='mapview',action="index")) return None c.trips=meta.Session.query(Recording).filter( Recording.user==session['user']).order_by(sa.desc(Recording.start)).all() return render('/recordings.mako')
class SplashController(BaseController): def index(self): host = request.headers.get('Host', None) if host: host = host.lower() if host in static_subhosts: try: ret = open( os.path.join(os.getenv('SWFP_ROOT'), static_subhosts[host])).read() response.headers['Content-Type'] = 'text/html' return ret except: print traceback.format_exc() return "An error occurred" c.expl = request.params.get("explanation", "") ua = request.headers.get('User-Agent', '').lower() c.browserwarningheader = None try: c.mem = find_free_mem() except Exception: c.mem = 0 if ua.count("msie") and not (ua.count("firefox") or ua.count("chrome")): #MSIE detect c.browserwarningheader = u"You are running Internet Explorer." c.browserwarning=u"This is not recommended, although it should work."+\ u"Please install <a style=\"color:#4040ff\" href=\"http://www.google.com/chrome/\">Google Chrome</a> "+\ u"or <a style=\"color:#4040ff\" href=\"http://www.firefox.com\">Mozilla Firefox</a>.<br/> It's easy!" return render('/splash.mako') def surefail(self): raise Exception("THis failed.") def logout(self): del session['user'] if 'current_trip' in session: del session['current_trip'] session.clear() session.save() tripsharing.cancel() redirect(h.url_for(controller='splash', action="index")) def about(self): try: c.aipupdate = get_aip_download_time() except Exception, cause: c.aipupdate = None try: c.mapupdate = datetime.fromtimestamp(get_mtime()) except Exception: c.mapupdate = datetime(1970, 1, 1) return render('/about.mako')
def coordparse(self): val=request.params['val'] try: s=mapper.anyparse(val) c.pos=s c.deg,c.degmin,c.degminsec=mapper.to_all_formats(mapper.from_str(s)) print "Rendering mako coordpres" return render("/coordpres.mako") except Exception: print "returning empty string , coordpres" return ""
def coordparse(self): val = request.params['val'] try: s = mapper.anyparse(val) c.pos = s c.deg, c.degmin, c.degminsec = mapper.to_all_formats( mapper.from_str(s)) print "Rendering mako coordpres" return render("/coordpres.mako") except Exception: print "returning empty string , coordpres" return ""
def minutemarkings(self): self.standard_prep(c) scale = 250000 def total_seconds(td): return float( td.seconds) + td.days * 86400.0 + td.microseconds / 1e6 for r in c.route: try: subs = r.subs def get_d_at_time(dt): for sub in subs: if dt <= sub.arrive_dt: sub_time = dt - sub.depart_dt sub_seconds = total_seconds(sub_time) sub_hours = sub_seconds / 3600.0 return sub.relstartd + sub_hours * sub.gs return r.d curdt = copy(r.depart_dt) curdt = curdt.replace(second=60 * (curdt.second // 60), microsecond=0) if curdt < r.depart_dt: curdt += timedelta(0, 60) #gs_ms=(r.gs*1.8520)/3.6 #if gs_ms<1e-3: return "-" #meter_per_min=gs_ms*60.0 #map_meter_per_min=meter_per_min/scale #cm_per_min=100*map_meter_per_min #d=get_d_at_time(curdt) #get_ #marks.append("%.1f"%cur) #cur+=cm_per_min marks = [] while curdt < r.arrive_dt: d = get_d_at_time(curdt) meter = d * 1852.0 cm = meter * 100.0 mapcm = cm / scale marks.append("%.1f" % mapcm) curdt += timedelta(0, 60) r.marks = ", ".join(marks) + " cm" except Exception: r.marks = "-" return render("/minutemarkings.mako")
def kml(self,starttime): if not 'user' in session: return None user=session['user'] print "Rpar:",request.params start=int(starttime) startd=datetime.utcfromtimestamp(start) rec,=meta.Session.query(Recording).filter(sa.and_( Recording.user==session['user'], Recording.start==startd)).all() c.rec=load_recording(rec) c.start=startd c.zip=zip response.content_type = 'application/octet-stream' response.charset="utf8" return render("/kml.mako")
def share(self): if tripsharing.sharing_active(): c.error=u"The current trip has been shared with you by its creator. You cannot create new URLs for sharing it further. You can, however, send the same link you got, to anyone." else: if not 'current_trip' in session: c.error=u"There is no current trip that can be shared" else: c.trip=session['current_trip'] shares=meta.Session.query(SharedTrip).filter(sa.and_(SharedTrip.user==session['user'],SharedTrip.trip==session.get('current_trip',None))).all() if len(shares)==0: c.sharing=False else: share,=shares c.sharing=True c.sharelink="http://"+socket.gethostname()+"/mapview/shared?secret="+share.secret return render("/share.mako")
def document(self): """Render the error document""" resp = request.environ.get('pylons.original_response') if hasattr(resp,'status_int') and resp.status_int: code=repr(resp.status_int) else: code=repr(request.GET.get('code', '')) msg=request.GET.get('message', '') if msg and not code: what=msg elif not msg and code: what="code: %s"%(code,) else: what=":".join(x for x in [code,msg] if x) return render('/error.mako',extra_vars=dict(what=what))
def minutemarkings(self): self.standard_prep(c) scale=250000 def total_seconds(td): return float(td.seconds)+td.days*86400.0+td.microseconds/1e6 for r in c.route: try: subs=r.subs def get_d_at_time(dt): for sub in subs: if dt<=sub.arrive_dt: sub_time=dt-sub.depart_dt sub_seconds=total_seconds(sub_time) sub_hours=sub_seconds/3600.0 return sub.relstartd+sub_hours*sub.gs return r.d curdt=copy(r.depart_dt) curdt=curdt.replace(second=60*(curdt.second//60),microsecond=0) if curdt<r.depart_dt: curdt+=timedelta(0,60) #gs_ms=(r.gs*1.8520)/3.6 #if gs_ms<1e-3: return "-" #meter_per_min=gs_ms*60.0 #map_meter_per_min=meter_per_min/scale #cm_per_min=100*map_meter_per_min #d=get_d_at_time(curdt) #get_ #marks.append("%.1f"%cur) #cur+=cm_per_min marks=[] while curdt<r.arrive_dt: d=get_d_at_time(curdt) meter=d*1852.0 cm=meter*100.0 mapcm=cm/scale marks.append("%.1f"%mapcm) curdt+=timedelta(0,60) r.marks=", ".join(marks)+" cm" except Exception: r.marks="-" return render("/minutemarkings.mako")
def enroutenotams(self): c.techroute,c.route=get_route(tripuser(),session['current_trip']) c.tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() if len(c.route)==0 or len(c.techroute)==0: redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) return c.trip=c.tripobj.trip for rt in c.route: rt.notampoints=dict() rt.notampoints.update(dict([(info['item']['notam'],info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos),5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)): rt.notampoints[space['name']]=space c.thislink=h.url_for(controller='flightplan',action="enroutenotams") return render('/enroutenotams.mako')
def index(self): user=meta.Session.query(User).filter( User.user==session['user']).one() print "index as user:"******"User full name",user.fullname c.user=fullname c.password='' print "User realname:",user.realname c.phonenr=request.params.get('phonenr',user.phonenr) c.realname=request.params.get('realname',user.realname) c.initial=not user.isregistered c.notfastmap=not user.fastmap c.fillable=user.fillable return render('/profile.mako')
def index(self): user = meta.Session.query(User).filter( User.user == session['user']).one() print "index as user:"******"User full name", user.fullname c.user = fullname c.password = '' print "User realname:", user.realname c.phonenr = request.params.get('phonenr', user.phonenr) c.realname = request.params.get('realname', user.realname) c.initial = not user.isregistered c.notfastmap = not user.fastmap c.fillable = user.fillable return render('/profile.mako')
def share(self): if tripsharing.sharing_active(): c.error = u"The current trip has been shared with you by its creator. You cannot create new URLs for sharing it further. You can, however, send the same link you got, to anyone." else: if not 'current_trip' in session: c.error = u"There is no current trip that can be shared" else: c.trip = session['current_trip'] shares = meta.Session.query(SharedTrip).filter( sa.and_( SharedTrip.user == session['user'], SharedTrip.trip == session.get('current_trip', None))).all() if len(shares) == 0: c.sharing = False else: share, = shares c.sharing = True c.sharelink = "http://" + socket.gethostname( ) + "/mapview/shared?secret=" + share.secret return render("/share.mako")
def excel(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname',None),exception=False): return "Internal error. Missing trip-name or user-session." self.standard_prep(c) coding=request.params.get("encoding",'UTF8') allowed=set(["UTF16",'ISO8859-15','ISO8859-1','UTF8']) if not coding in allowed: coding='UTF8' c.waypoints=c.route response.content_type = 'application/octet-stream' response.charset=coding def fixup(val): if type(val)==float: return str(val).replace(".",",") return val c.fixup=fixup return render('/excel.mako')
def show_ctx(self): notams=meta.Session.query(Notam).filter( Notam.ordinal==int(request.params['notam'])).all() if len(notams)==0: return redirect(h.url_for(controller='notam',action="index")) notam,=notams c.backlink=request.params.get('backlink', h.url_for(controller="notam",action="index")) all_lines=list(notam.notamtext.splitlines()) startline=int(request.params['line']) endline=startline cnt=len(all_lines) while True: if endline>=cnt: break if all_lines[endline].strip()=="": break endline+=1 c.startlines=all_lines[:startline] c.midlines=all_lines[startline:endline] c.endlines=all_lines[endline:] return render('/notam_ctx.mako')
def gpx(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname',None),exception=False): return "Internal error. Missing trip-name or user-session." waypoints=list(meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==c.trip.trip)).order_by(Waypoint.ordering).all()) if len(waypoints)==0: return redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) c.waypoints=[] for wp in waypoints: lat,lon=mapper.from_str(wp.pos) c.waypoints.append(dict( lat=lat, lon=lon, name=wp.waypoint )) #response.headers['Content-Type'] = 'application/xml' response.content_type = 'application/octet-stream' response.charset="utf8" return render('/gpx.mako')
def index(self): when, valid, fct = gfs_weather.get_prognosis(datetime.utcnow()) lat = 59.45862 lon = 17.70680 c.qnh = 1013 c.winddir = 0 c.windvel = 0 c.defaddata = self.load_ad_json(extra_airfields.frolunda) c.field = u"Frölunda" c.searchurl = h.url_for(controller='sufperformance', action='search') c.airport_load_url = h.url_for(controller='sufperformance', action='load') metar = metartaf.get_metar('ESSA') print "metar:", metar try: c.temp, dew = re.match(r".*\b(\d{2})/(\d{2})\b.*", metar.text).groups() print "c.temp:", c.temp if c.temp.startswith("M"): c.temp = -int(c.temp[1:]) else: c.temp = int(c.temp) except: c.temp = 15 try: c.qnh = fct.get_qnh(lat, lon) if c.qnh < 10: c.qnh = 1013 c.winddir, c.windvel = fct.get_surfacewind(lat, lon) c.winddir = int(c.winddir) c.windvel = int(c.windvel) except: print traceback.format_exc() pass return render('/sufperformance.mako')
def excel(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname', None), exception=False): return "Internal error. Missing trip-name or user-session." self.standard_prep(c) coding = request.params.get("encoding", 'UTF8') allowed = set(["UTF16", 'ISO8859-15', 'ISO8859-1', 'UTF8']) if not coding in allowed: coding = 'UTF8' c.waypoints = c.route response.content_type = 'application/octet-stream' response.charset = coding def fixup(val): if type(val) == float: return str(val).replace(".", ",") return val c.fixup = fixup return render('/excel.mako')
def obstacles(self): routes, baseroute = get_route(tripuser(), session['current_trip']) tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() c.trip = tripobj.trip id2order = dict([(rt.a.id, rt.a.ordering) for rt in baseroute]) byidsorted = sorted(self.get_obstacles(routes).items(), key=lambda x: id2order.get(x[0], 0)) out = [] def classify(item): #print item vertlimit = 1000 if item.get('kind', None) == 'lowsun': return "#ffffb0" if item.get('kind', None) == 'terrain': vertlimit = 500 try: margin = item['closestalt'] - mapper.parse_elev(item['elev']) except Exception: return "#0000ff" #Unknown margin, unknown height if item['dist'] > 0.6 / 1.852: return None #Not really too close anyway if margin < 0: return "#ff3030" if margin < vertlimit: return "#ffb0b0" return None dupecheck = dict() for idx, items in byidsorted: for item in items: ident = (item['name'], item['pos'], item.get('elev', None)) dupecheck.setdefault(ident, []).append(item) bestdupe = dict() for ident, dupes in dupecheck.items(): best = min(dupes, key=lambda x: x['dist']) bestdupe[ident] = best for idx, items in byidsorted: cur = [] for item in items: dist_from_a = item['dist_from_a'] dist_from_b = item['dist_from_b'] if abs(dist_from_a) < 0.5: descr = "Near %s" % (item['a'].waypoint, ) elif abs(dist_from_b) < 0.5: descr = "Near %s" % (item['b'].waypoint, ) elif dist_from_a < dist_from_b: descr = "%.0fNM %s of %s" % ( dist_from_a, item['dir_from_a'], item['a'].waypoint) else: descr = "%.0fNM %s of %s" % ( dist_from_b, item['dir_from_b'], item['b'].waypoint) ident = (item['name'], item['pos'], item.get('elev', None)) best = bestdupe[ident] if not (best is item): continue #if ident in seen: continue #seen.add(ident) cur.append( dict( routepointdescr=descr, #dir_from_a=item['dir_from_a'], #fromwhat=fromwhat, kind=item.get('kind', None), bearing=item.get('bearing', None), along_nm=dist_from_a, dist=item['dist'], name=item['name'], closestalt=item['closestalt'], elev=item.get('elev', None))) cur[-1]['color'] = classify(cur[-1]) out.append((items[0]['a'].waypoint, sorted(cur, key=lambda x: x['along_nm']))) c.items = out return render('/obstacles.mako')
c.all_aircraft=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'])).all() if c.trip.acobj==None: c.ac=None c.advanced_model=False else: c.ac=c.trip.acobj if session.get('cur_aircraft',None)!=c.trip.acobj.aircraft: session['cur_aircraft']=c.trip.acobj.aircraft session.save() c.advanced_model=c.ac.advanced_model c.sharing=tripsharing.sharing_active() #print repr(c) return render('/flightplan.mako') def select_aircraft(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview',action="index")) if not tripsharing.sharing_active(): tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() tripobj.aircraft=request.params['change_aircraft'] if tripobj.aircraft.strip()=="--------": tripobj.aircraft=None else: for route in meta.Session.query(Route).filter(sa.and_( Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all(): acobj,=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.aircraft==tripobj.aircraft,Aircraft.user==session['user'])).all()
def ats(self): try: #waypoints=meta.Session.query(Waypoint).filter(sa.and_( # Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all() #c.waypoints=[] self.standard_prep(c) #print "Routes:",c.route def break_subtrips(routes): out = [] T = 0.0 for i, rt in enumerate(routes): out.append(rt) if rt.time_hours: T += rt.time_hours if rt.b.stay or i == len(routes) - 1: if len(out): yield dict(T=T), out T = 0.0 out = [] def format_cruise(tas): if tas > 999: tas = 999 if tas < 0: tas = 0 return "N%04d" % (tas, ) def format_alt(alt): try: alt = alt.upper().strip() if alt.startswith("FL"): ialt = int(float(alt[2:].strip())) return "F%03d" % (ialt, ) ialt = int(float(alt)) / 100 print "parsed alt %s" % (repr(alt, )), "as", ialt return "A%03d" % (ialt, ) except Exception: raise AtsException( "Bad altitude specification for some leg: <%s>" % (alt)) c.atstrips = [] last_fuel_left = None nr_persons = None for meta, routes in break_subtrips(c.route): print "===============New subtrip..............." spaces = set() fir_whenposname = [] accum_time = 0 #print "broke ruote",meta if len(routes) == 0: continue at = dict() at['T'] = meta['T'] waypoints = [routes[0].a] for rt in routes: waypoints.append(rt.b) wps = [] stay = routes[0].a.stay dep_ad = "ZZZZ" dep_ad_name = waypoints[0].waypoint dep_ad_coords = mapper.format_lfv_ats( *mapper.from_str(waypoints[0].pos)) dest_ad = "ZZZZ" dest_ad_name = waypoints[-1].waypoint dest_ad_coords = mapper.format_lfv_ats( *mapper.from_str(waypoints[-1].pos)) extra_remarks = [] lastwppos = None lastaltspeed = None for i, wp in enumerate(waypoints): print "Subtrip:", i, wp.waypoint at['T'] = meta['T'] lat, lon = mapper.from_str(wp.pos) if lastwppos: assert i >= 1 curpos = (lat, lon) crossing1 = airspace.get_fir_crossing( lastwppos, curpos) for sub in routes[i - 1].subs: if crossing1: posa,posb=mapper.merc2latlon(sub.subposa,13),\ mapper.merc2latlon(sub.subposb,13) crossing = airspace.get_fir_crossing( posa, posb) if crossing: fir, enterpos = crossing bearing, along = mapper.bearing_and_distance( posa, enterpos) if sub.gs > 1e-6: curtime = accum_time + along / sub.gs fir_whenposname.append( (curtime, enterpos, fir['icao'])) if sub.time != None: accum_time += sub.time else: accum_time = 9999 for space in get_any_space_on_line(lastwppos, curpos): spaces.add((space['name'], space.get('floor', "<Unknown>"), space.get('ceiling', "<Unknown>"))) lastwppos = (lat, lon) symbolicpos = None airport = None if i == 0 or i == len(waypoints) - 1: for ad in airspace.get_airfields(lat, lon, 11): if not ad['icao'].upper() in ['ZZZZ', 'ESVF']: airport = ad symbolicpos = ad['icao'].upper() if i == 0: dep_ad = ad['icao'].upper() if i == len(waypoints) - 1: dest_ad = ad['icao'].upper() break else: for sigp in airspace.get_sigpoints(lat, lon, 11): if sigp['kind'] == "sig. point": if len(sigp['name']) == 5: sigfound = sigp symbolicpos = sigp['name'] break if symbolicpos == None: symbolicpos = mapper.format_lfv_ats(lat, lon) if i < len(routes): altspeed = (format_alt(routes[i].altitude), format_cruise(routes[i].tas)) if lastaltspeed != None: if lastaltspeed != altspeed: alt, speed = altspeed symbolicpos += "/" + speed + alt lastaltspeed = altspeed wps.append( dict(name=wp.waypoint, airport=airport, symbolicpos="DCT " + symbolicpos, exactpos=mapper.format_lfv(lat, lon), decimalpos="%.5f,%.5f" % (lat, lon))) for when, pos, fir in fir_whenposname: hour, minute = divmod(int(60 * when), 60) extra_remarks.append("EET/%s%02d%02d" % (fir, hour, minute)) if dep_ad == "ZZZZ": extra_remarks.append( u"DEP/%s %s" % (dep_ad_coords, strip_accents(dep_ad_name.upper()))) if dest_ad == "ZZZZ": extra_remarks.append( u"DEST/%s %s" % (dest_ad_coords, strip_accents(dest_ad_name.upper()))) if stay.date_of_flight.strip(): dof = stay.date_of_flight.replace("-", "").strip() if len(dof) == 8 and dof.startswith("20"): dof = dof[2:] else: dof = routes[0].depart_dt.strftime("%y%m%d") print "dof:", dof if len(dof) != 6: raise AtsException( u"ATS flight plans need takeoff date for all takeoffs!" ) else: extra_remarks.append(u"DOF/%s" % (dof, )) if stay and stay.nr_persons: nr_persons = stay.nr_persons else: if nr_persons == None: raise AtsException( u"You must enter the the number of persons who will be flying!" ) tas = routes[0].tas altitude = routes[0].altitude at['wps'] = wps if any(rt.time_hours == None for rt in routes): raise AtsException( "TAS is less than headwind for some part of trip.") enroute_time = sum(rt.time_hours for rt in routes) fuel = last_fuel_left if stay and stay.fuel: fuel = stay.fuel if not c.ac: raise AtsException( "You must choose an aircraft type for this journey to be able to create an ATS flight plan" ) if c.ac.cruise_burn > 1e-3 and fuel: endurance = float(fuel) / float(c.ac.cruise_burn) else: endurance = 0.0 if endurance <= 0.0: if fuel == None: raise AtsException( "Enter a value for 'Fuel at takeoff'!") else: raise AtsException( "You do not have enough fuel for the entire journey! This means your endurance would be 0 or negative for one or more legs. Add a fuel stop, shorten the journey, or bring more fuel!" ) if not c.user.realname: raise AtsException( "You should enter your name under profile settings, for use as the name of the commander in the flight plan" ) phonenr = "" if c.user.phonenr: phonenr = c.user.phonenr fir_whenposname.sort() def eqp(x, s): x = "".join(re.findall('[A-Z]', x.upper())) if len(x) == 0: return s return x dummy = u""" FPL-SEVLI-VG -ULAC/L-V/C -EFKG1330 -N0075F065 DCT 5959N02016E DCT 5949N01936E DCT 5929N01818E DCT 5927N01742E -ZZZZ0130 -DEST/5927N01742E FRÖLUNDA RMK/BORDER CROSSING 40MIN AFTER TAKEOFF DOF/101002 ORGN/ESSAZPZX -E/0300 P/2 A/R W C/ANDERS MUSIKKA +4670123123""" atsfplan = u""" (FPL-%(acreg)s-%(flight_rules)s%(type_of_flight)s -%(actype)s/%(turbulence_category)s-%(equipment)s/%(transponder)s -%(dep_ad)s%(eobt)s -%(cruise_speed)s%(level)s %(route)s DCT -%(dest_ad)s%(ete)s -%(extra_remarks)s -E/%(endurance)s P/%(nr_passengers)s A/%(markings)s%(extra_equipment)s C/%(commander)s %(phonenr)s)""" % (dict( acreg=c.ac.aircraft.replace("-", ""), actype=c.ac.atstype, turbulence_category='L', flight_rules='V', type_of_flight='G', equipment=eqp(c.ac.com_nav_equipment, 'V'), transponder=eqp(c.ac.transponder_equipment, 'C'), extra_equipment=u" %s" % (c.ac.extra_equipment, ) if c.ac.extra_equipment else "", dep_ad=dep_ad, eobt=routes[0].depart_dt.strftime("%H%M"), cruise_speed=format_cruise(tas), level=format_alt(altitude), route=(" ".join("%s" % (w['symbolicpos'], ) for w in wps[1:-1])), dest_ad=dest_ad, ete=lfvclockfmt(enroute_time), extra_remarks=" ".join(extra_remarks), endurance=lfvclockfmt(endurance), nr_passengers=nr_persons, markings=c.ac.markings, commander=strip_accents(c.user.realname if c.user.realname else u"UNKNOWN").replace(" ", ""), phonenr=c.user.phonenr if c.user.phonenr else "")) at['atsfplan'] = atsfplan.strip() #print "Adding atstrip:",atsfplan at['spacesummary'] = spaces last_fuel_left = routes[-1].accum_fuel_left c.atstrips.append(at) c.atstrips = [at for at in c.atstrips if len(at['wps'])] #response.headers['Content-Type'] = 'application/xml' return render('/ats.mako') except AtsException, ats: redirect( h.url_for(controller='flightplan', action="index", flash=unicode(ats)))
def rename(self,setname): c.setname=setname return render('/customsetrename.mako')
def index(self,bad_values=dict(),orig=None): cur_acname=session.get('cur_aircraft',None) c.ac=None if cur_acname: cac=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'], Aircraft.aircraft==cur_acname)).all() if len(cac)==1: c.ac=cac[0] c.burn_warning=None c.all_aircraft=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'])).all() if len(c.all_aircraft) and c.ac==None: c.ac=c.all_aircraft[0] print "c.ac",c.ac if c.ac and c.ac.advanced_model: print "adv climb rate",c.ac.adv_climb_rate for prop in advprops: print "prop",prop,"val:",getattr(c.ac,prop) if all(getattr(c.ac,prop)==() for prop in advprops): #Default-values for Cessna 172 with 160hp engine. c.ac.adv_climb_rate= [770,725,675,630,580,535,485,440,390,345] c.ac.adv_climb_burn= [62, 60, 55, 50, 45, 42, 40, 37, 35, 33] c.ac.adv_climb_speed= [73, 73, 72, 72, 71, 71, 70, 69, 69, 68] c.ac.adv_cruise_burn= [32, 32, 32, 32, 32, 32, 30, 29,28.5,28] c.ac.adv_cruise_speed= [116,117,118,118,118,118,118,118,118,118] c.ac.adv_descent_rate= [400,400,400,400,400,400,400,400,400,400] c.ac.adv_descent_burn= [25, 25, 25, 25, 25, 25, 25, 25, 25, 25] c.ac.adv_descent_speed=[116,117,118,119,120,121,122,122,122,122] try: for idx,(cruise_burn,climb_burn) in enumerate(zip(c.ac.adv_cruise_burn,c.ac.adv_climb_burn)): if climb_burn<cruise_burn: c.burn_warning="You have entered a fuel consumption for climb that is lower than that for cruise (for altitude %d). Is this right?"%(idx*1000) break except Exception: print "Internal error in ac, burn check" pass for prop in advprops: val=getattr(c.ac,prop) if val==None: val=[] l=0 else: val=list(val) l=len(val) val.extend([0 for x in xrange(10-l)]) setattr(c.ac,prop,tuple(val)) c.adv_props=[ ("Cruise Speed (kt TAS)","adv_cruise_speed"), ("Cruise Consumption (L/h)","adv_cruise_burn"), ("Climb Speed (kt TAS)","adv_climb_speed"), ("Climb Consumption (L/h)","adv_climb_burn"), ("Climb Rate (fpm)","adv_climb_rate"), ("Descent Speed (kt TAS)","adv_descent_speed"), ("Descent Consumption (L/h)","adv_descent_burn"), ("Descent Rate (fpm)","adv_descent_rate") ] def getval(prop,alt): ialt=alt/1000 raw=getattr(c.ac,prop)[ialt] s="%.1f"%(raw,) if s.endswith(".0"): return s[:-2] return s c.getval=getval else: if c.ac: if c.ac.climb_burn<c.ac.cruise_burn: c.burn_warning="You have entered a fuel consumption for climb that is lower than that for cruise. Is this right?" def get_msgerror(x): msgs=set() for alt in xrange(0,10000,1000): msg=bad_values.get((x,alt),None) if msg: msgs.add(msg) return "<span style=\"background-color:#ffd0d0\">" + cgi.escape(", ".join(msgs)) + "</span>" c.aircraft_name_error=bad_values.get('aircraft',None) c.msgerror=get_msgerror c.fmterror=lambda x,alt=0:'style="background:#ff8080;' if bad_values.get((x,alt),None) else '' c.newly_added=False if request.params.get('flash','')=='new': c.flash='A new aircraft was added! Enter its registration/name and other info below.' c.newly_added=True else: c.flash='' if c.ac: c.orig_aircraft=c.ac.aircraft else: c.orig_aircraft='' if orig!=None: c.orig_aircraft=orig return render('/aircraft.mako')
def index(self): print "Index called", session.get('zoom',-1) #print "index called",request.params #user=meta.Session.query(User).filter( # User.user==tripuser()).one() user=meta.Session.query(User).filter( User.user==session['user']).one() ua=request.headers.get('User-Agent','').lower() c.ie=False if ua.count("msie") and not (ua.count("firefox") or ua.count("chrom") or ua.count("safari")): c.ie=True #print "IE mode:",c.ie c.all_trips=list(meta.Session.query(Trip).filter(Trip.user==session['user']).all()) print "current trip:",session.get('current_trip',None) if not ('current_trip' in session) or session['current_trip']==None: if user.lasttrip!=None: print "Reusing lasttrip:",user.lasttrip session['current_trip']=user.lasttrip if 'current_trip' in session and meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(), Trip.trip==session['current_trip'] )).count()==0: session['current_trip']=None if not 'current_trip' in session or session['current_trip']==None: trips=meta.Session.query(Trip).filter( Trip.user==tripuser()).all() if len(trips)==0: trip = Trip(tripuser(), "Default Trip") meta.Session.add(trip) meta.Session.flush() meta.Session.commit() else: trip=min(trips,key=lambda x:x.trip) #Select first trip, alphabetically - we have no better idea. session['current_trip']=trip.trip session.save() trip=None if session.get('current_trip',None)!=user.lasttrip: user.lasttrip=session.get('current_trip',None) print "Storing lasttrip=",user.lasttrip meta.Session.flush() meta.Session.commit() c.mapvariant=session.get('mapvariant',"airspace") self.set_pos_zoom() zoomlevel=session['zoom'] if c.mapvariant=="elev": if zoomlevel>8: session['zoom']=8 session.save() try: session['last_pos']=mapper.latlon2merc(mapper.merc2latlon(session['last_pos'],zoomlevel),8) except Exception: session['last_pos']=mapper.latlon2merc((59,18),8) print "Setting session last pos to 59,18",session['last_pos'] zoomlevel=8 print "Last pos is:",mapper.merc2latlon(session['last_pos'],zoomlevel) c.merc_x,c.merc_y=session['last_pos'] c.merc5_limx1,c.merc5_limy1,c.merc5_limx2,c.merc5_limy2=merc_limits(5,conservative=False,hd=True) c.waypoints=list(meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all()) c.tripname=session['current_trip'] c.showarea=session.get('showarea','') c.showtrack=session.get('showtrack',None)!=None c.fastmap=user.fastmap; #print "Zoomlevel active: ",zoomlevel c.zoomlevel=zoomlevel c.dynamic_id='' c.sharing=tripsharing.sharing_active() c.mtime=maptilereader.get_mtime() for way in c.waypoints: print "Name:",way.waypoint if len(c.waypoints): c.next_waypoint_id=max([way.id for way in c.waypoints])+1 else: c.next_waypoint_id=100 assert type(c.next_waypoint_id)==int if c.sharing: c.shared_by=tripuser() if session.get('showarea',''): c.dynamic_id=session.get('showarea_id','') if session.get('showtrack',''): if hasattr(session['showtrack'],'dynamic_id'): c.dynamic_id=session['showtrack'].dynamic_id return render('/mapview.mako')
def printable(self): extended = False if request.params.get('extended', False): extended = True self.standard_prep(c) self.get_freqs(c.route) if extended: c.origroute = c.route c.route = c.techroute for rt in c.origroute: for sub in rt.subs: sub.freqset = rt.freqset sub.is_start = False sub.is_end = False rt.subs[-1].is_end = True rt.subs[0].is_start = True else: for rt in c.route: rt.is_end = True rt.is_start = True rt.what = '' for rt in c.route: rt.notampoints = set() rt.notampoints.update( set([ info['item']['notam'] for info in get_notampoints_on_line( mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos), 5) ])) for rt in c.route: rt.maxobstelev = obstacle_free.get_obstacle_free_height_on_line( mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)) try: rt.startelev = float( airspace.get_pos_elev(mapper.from_str(rt.a.pos))) except: rt.startelev = float(9999) try: rt.endelev = float( airspace.get_pos_elev(mapper.from_str(rt.b.pos))) except: rt.endelev = float(9999) #for obst in obsts: # print "obst:",obst for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)): rt.notampoints.add(space['name']) if len(c.route) > 0: poss = [mapper.from_str(c.route[0].a.pos)] poss += [mapper.from_str(r.b.pos) for r in c.route] dta, dtb = [c.route[0].a.dt, c.route[-1].b.dt] if dtb == None: c.sunset = "unknown" else: print "sunrise:", dta, dtb fall, what = sunrise.earliestsunset([dta, dtb], poss) if what != None: c.sunset = what elif fall != None: c.sunset = fall.strftime("%H:%MZ") else: c.sunset = "unknown" lat, lon = mapper.from_str(c.route[0].a.pos) c.sunrise = sunrise.sunrise_str(dta, lat, lon) return render('/printable.mako')
def view(self,setname,version,flash="",data=None): version=int(version) c.flash=flash hits=meta.Session.query(CustomSet).filter(sa.and_( CustomSet.user==session['user'], CustomSet.setname==setname, CustomSet.version==version)).all() prev=meta.Session.query(CustomSet).filter(sa.and_( CustomSet.user==session['user'], CustomSet.setname==setname, CustomSet.version==version-1)).all() next=meta.Session.query(CustomSet).filter(sa.and_( CustomSet.user==session['user'], CustomSet.setname==setname, CustomSet.version==version+1)).all() try: customset,=meta.Session.query(CustomSets).filter(sa.and_( CustomSets.user==session['user'], CustomSets.setname==setname)).all() except: customset=None print "pn",repr(prev),repr(next) if data!=None: c.data=data else: if len(hits)==0: c.data=""" { "obstacles":[ {"name":"Construction Work", "pos":"59,18", "kind":"Crane", "elev":1234, "height":123 } ], "sigpoints":[ {"name":"TestPunkt", "pos":"5920N1810E", "kind":"sig.point" } ], "airfields":[ {"name":"TestPunkt", "pos":"5920N1810E", "kind":"sig.point", "icao":"ABCD", "elev":123 }], "airspaces":[ { "points":"590000N0180000E-600000N0180000E-600000N0183000E-590000N0183000E", "name":"Test-area", "floor":"GND", "ceiling":"FL55", "type":"TMA", "freqs":[["Pahittat Callsign",123.456],["Ett annat pahittat callsign",111.111]] } ] } """ else: c.data=hits[0].data c.cur=version c.setname=setname if customset: c.active=(customset.active==version) c.ready=(customset.ready==version) else: c.active=False c.ready=False c.haveprev=len(prev)>0 c.havenext=len(next)>0 #print "Havenext:",c.havenext c.data=unescape_string_newlines_only(c.data).replace("\n","\r\n") return render('/customset.mako')
def show(self): ad = request.params['ad'] cksum = request.params['checksum'] chartobj = None for adobj in ec.get_airfields(): bb = False if adobj['name'] == ad and 'adcharts' in adobj: for adchart in adobj['adcharts'].values(): if adchart['checksum'] == cksum: chartobj = adchart bb = True break if bb: break else: self.error("No such airport/picture " + ad + "/" + cksum) projs = meta.Session.query(AirportProjection).filter( sa.and_( AirportProjection.user == session['user'], AirportProjection.airport == ad, AirportProjection.mapchecksum == adchart['checksum'])).all() c.markers = meta.Session.query(AirportMarker).filter( sa.and_( AirportMarker.user == session['user'], AirportMarker.airport == ad, AirportMarker.mapchecksum == adchart['checksum'])).order_by( AirportMarker.latitude, AirportMarker.longitude, AirportMarker.x, AirportMarker.y).all() if not projs: proj = AirportProjection() proj.user = session['user'] proj.airport = ad proj.mapchecksum = str(adchart['checksum']) proj.updated = datetime.utcnow() proj.matrix = (1, 0, 0, 1, 0, 0) proj.scale = None proj.north = None meta.Session.add(proj) meta.Session.flush() meta.Session.commit() else: proj, = projs proj.mapchecksum = str(proj.mapchecksum) if all([x == 0 for x in proj.matrix[4:6]]): projmatrix = self.invent_matrix(proj.mapchecksum, adchart['variant']) else: projmatrix = proj.matrix A = projmatrix[0:4] T = projmatrix[4:6] transform = customproj.Transform(A, T) c.matrix = projmatrix c.initial_scroll_x = request.params.get("scroll_x", 0) c.initial_scroll_y = request.params.get("scroll_y", 0) c.maptype = request.params.get("maptype", "chart") c.variant = adchart['variant'] c.curadmarker = session.get('curadmarker', (0, 0)) c.img = adchart['blobname'] + "," + adchart['checksum'] c.flash = None c.ad = ad c.mapchecksum = adchart['checksum'] c.mapsize = adchart.get('mapsize', (210, 297)) c.scale = proj.scale if proj.scale != None else "" c.north = proj.north if proj.north != None else "" c.runways = [] c.arp = transform.to_pixels(mapper.from_str(adobj['pos'])) arp1m = mapper.latlon2merc(mapper.from_str(adobj['pos']), 17) arp2m = mapper.latlon2merc(mapper.from_str(adobj['pos']), 17) arp1m = (arp1m[0], arp1m[1] - 250) arp2m = (arp2m[0] + 250, arp2m[1]) c.arp1 = transform.to_pixels(mapper.merc2latlon(arp1m, 17)) c.arp2 = transform.to_pixels(mapper.merc2latlon(arp2m, 17)) def dist(x, y): return math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2) c.ratio = abs(dist(c.arp, c.arp1) - dist(c.arp, c.arp2)) / max( dist(c.arp, c.arp1), dist(c.arp, c.arp2)) c.transform_reasonable = True x, y = c.arp if x < -200 or y < -200 or x >= 4000 or y >= 4000: c.transform_reasonable = False c.revmarkers = [] c.width, c.height = chartobj['render_width'], chartobj['render_height'] try: c.base_coords=\ [mapper.latlon2merc(transform.to_latlon((0,0)),13), mapper.latlon2merc(transform.to_latlon((c.width,0)),13), mapper.latlon2merc(transform.to_latlon((0,c.height)),13), mapper.latlon2merc(transform.to_latlon((c.width,c.height)),13)] except Exception: print "problem with basecoords:", traceback.format_exc() c.base_coords = [(0, 0) for x in xrange(4)] for mark in c.markers: lat, lon = transform.to_latlon((mark.x, mark.y)) if mark.latitude: lat = mark.latitude if mark.longitude: lon = mark.longitude pos = transform.to_pixels((lat, lon)) c.revmarkers.append(pos) for rwy in adobj.get('runways', []): ends = rwy['ends'] latlon1 = mapper.from_str(ends[0]['pos']) latlon2 = mapper.from_str(ends[1]['pos']) print rwy, "Runway pos", latlon1, " to ", latlon2 p1 = transform.to_pixels(latlon1) p2 = transform.to_pixels(latlon2) for p in [p1, p2]: x, y = p if x < -200 or y < -200 or x >= 4000 or y >= 4000: c.transform_reasonable = False c.runways.append( ((int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])))) c.random = md5.md5(pickle.dumps(projmatrix)).hexdigest() return render('/airportproj.mako')
def index(self): ack_cnt = meta.Session.query(NotamAck.appearnotam,NotamAck.appearline,sa.func.count('*').label('acks')).filter(NotamAck.user==session.get('user',None)).group_by(NotamAck.appearnotam,NotamAck.appearline).subquery() c.items=meta.Session.query(NotamUpdate,ack_cnt.c.acks,Notam.downloaded).outerjoin( (ack_cnt,sa.and_( NotamUpdate.appearnotam==ack_cnt.c.appearnotam, NotamUpdate.appearline==ack_cnt.c.appearline))).outerjoin( (Notam,Notam.ordinal==NotamUpdate.appearnotam) ).order_by(sa.desc(Notam.downloaded)).filter( NotamUpdate.disappearnotam==sa.null()).all() c.categories=set([notamupdate.category for notamupdate,acks,downloaded in c.items]) user=meta.Session.query(User).filter(User.user==session['user']).one() c.showobst=user.showobst def vandalize(x): x=x.replace(u"Å",u"A") x=x.replace(u"Ä",u"A") x=x.replace(u"Ö",u"O") return x for air in get_airfields(): c.categories.add(vandalize(u"%s/%s"%(air['icao'].upper(),air['name'].upper()))) c.sel_cat=set(x.category for x in meta.Session.query(NotamCategoryFilter).filter(NotamCategoryFilter.user==session['user'])) c.shown=[] c.show_cnt=0 c.hide_cnt=0 c.countries=[ dict(name="Sweden",sel=False,short="ES"), dict(name="Finland",sel=False,short="EF"), dict(name="Estonia",sel=False,short="EE"), dict(name="Latvia",sel=False,short="EV"), dict(name="Denmark",sel=False,short="EK"), ] if 1: for ct in meta.Session.query(NotamCountryFilter).filter( NotamCountryFilter.user==session['user']).all(): for countrydict in c.countries: if countrydict['name']==ct.country: countrydict['sel']=True selcountries=set() for ct in c.countries: if ct['sel']: selcountries.add(ct['short']) if len(selcountries)==0: selcountries=None ms=[] ms.append(re.compile(r".*\bOBST\s+ERECTED\b.*")) ms.append(re.compile(r".*TURBINE?S?\s+ERECTED\b.*")) ms.append(re.compile(r".*\bMASTS?\s+ERECTED\b.*")) ms.append(re.compile(r".*\bCRANES?\s+ERECTED\b.*")) ms.append(re.compile(r".*LIGHTS?.*OUT\s+OF\s+SERVICE.*",re.DOTALL)) for notamupdate,acks,downloaded in c.items: if not c.showobst: match=False for m in ms: if m.match(notamupdate.text): match=True break if match: c.hide_cnt+=1 continue if (len(c.sel_cat)==0 or notamupdate.category in c.sel_cat) and \ (selcountries==None or notamupdate.category==None or notamupdate.category[:2] in selcountries): c.shown.append((notamupdate,acks,downloaded)) c.show_cnt+=1 else: c.hide_cnt+=1 print "Start rendering mako" return render('/notam.mako')
def ats(self): try: #waypoints=meta.Session.query(Waypoint).filter(sa.and_( # Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all() #c.waypoints=[] self.standard_prep(c) #print "Routes:",c.route def break_subtrips(routes): out=[] T=0.0 for i,rt in enumerate(routes): out.append(rt) if rt.time_hours: T+=rt.time_hours if rt.b.stay or i==len(routes)-1: if len(out): yield dict(T=T),out T=0.0 out=[] def format_cruise(tas): if tas>999: tas=999 if tas<0: tas=0 return "N%04d"%(tas,) def format_alt(alt): try: alt=alt.upper().strip() if alt.startswith("FL"): ialt=int(float(alt[2:].strip())) return "F%03d"%(ialt,) ialt=int(float(alt))/100 print "parsed alt %s"%(repr(alt,)),"as",ialt return "A%03d"%(ialt,) except Exception: raise AtsException("Bad altitude specification for some leg: <%s>"%(alt)) c.atstrips=[] last_fuel_left=None nr_persons=None for meta,routes in break_subtrips(c.route): print "===============New subtrip..............." spaces=set() fir_whenposname=[] accum_time=0 #print "broke ruote",meta if len(routes)==0: continue at=dict() at['T']=meta['T'] waypoints=[routes[0].a] for rt in routes: waypoints.append(rt.b) wps=[] stay=routes[0].a.stay dep_ad="ZZZZ" dep_ad_name=waypoints[0].waypoint dep_ad_coords=mapper.format_lfv_ats(*mapper.from_str(waypoints[0].pos)) dest_ad="ZZZZ" dest_ad_name=waypoints[-1].waypoint dest_ad_coords=mapper.format_lfv_ats(*mapper.from_str(waypoints[-1].pos)) extra_remarks=[] lastwppos=None lastaltspeed=None for i,wp in enumerate(waypoints): print "Subtrip:",i,wp.waypoint at['T']=meta['T'] lat,lon=mapper.from_str(wp.pos) if lastwppos: assert i>=1 curpos=(lat,lon) crossing1=airspace.get_fir_crossing(lastwppos,curpos) for sub in routes[i-1].subs: if crossing1: posa,posb=mapper.merc2latlon(sub.subposa,13),\ mapper.merc2latlon(sub.subposb,13) crossing=airspace.get_fir_crossing(posa,posb) if crossing: fir,enterpos=crossing bearing,along=mapper.bearing_and_distance(posa,enterpos) if sub.gs>1e-6: curtime=accum_time+along/sub.gs fir_whenposname.append((curtime,enterpos,fir['icao'])) if sub.time!=None: accum_time+=sub.time else: accum_time=9999 for space in get_any_space_on_line(lastwppos,curpos): spaces.add((space['name'],space.get('floor',"<Unknown>"),space.get('ceiling',"<Unknown>"))) lastwppos=(lat,lon) symbolicpos=None airport=None if i==0 or i==len(waypoints)-1: for ad in airspace.get_airfields(lat,lon,11): if not ad['icao'].upper() in ['ZZZZ','ESVF']: airport=ad symbolicpos=ad['icao'].upper() if i==0: dep_ad=ad['icao'].upper() if i==len(waypoints)-1: dest_ad=ad['icao'].upper() break else: for sigp in airspace.get_sigpoints(lat,lon,11): if sigp['kind']=="sig. point": if len(sigp['name'])==5: sigfound=sigp symbolicpos=sigp['name'] break if symbolicpos==None: symbolicpos=mapper.format_lfv_ats(lat,lon) if i<len(routes): altspeed=(format_alt(routes[i].altitude),format_cruise(routes[i].tas)) if lastaltspeed!=None: if lastaltspeed!=altspeed: alt,speed=altspeed symbolicpos+="/"+speed+alt lastaltspeed=altspeed wps.append(dict( name=wp.waypoint, airport=airport, symbolicpos="DCT "+symbolicpos, exactpos=mapper.format_lfv(lat,lon), decimalpos="%.5f,%.5f"%(lat,lon) )) for when,pos,fir in fir_whenposname: hour,minute=divmod(int(60*when),60) extra_remarks.append("EET/%s%02d%02d"%(fir,hour,minute)) if dep_ad=="ZZZZ": extra_remarks.append(u"DEP/%s %s"%(dep_ad_coords,strip_accents(dep_ad_name.upper()))) if dest_ad=="ZZZZ": extra_remarks.append(u"DEST/%s %s"%(dest_ad_coords,strip_accents(dest_ad_name.upper()))) if stay.date_of_flight.strip(): dof=stay.date_of_flight.replace("-","").strip() if len(dof)==8 and dof.startswith("20"): dof=dof[2:] else: dof=routes[0].depart_dt.strftime("%y%m%d") print "dof:",dof if len(dof)!=6: raise AtsException(u"ATS flight plans need takeoff date for all takeoffs!") else: extra_remarks.append(u"DOF/%s"%(dof,)) if stay and stay.nr_persons: nr_persons=stay.nr_persons else: if nr_persons==None: raise AtsException(u"You must enter the the number of persons who will be flying!") tas=routes[0].tas altitude=routes[0].altitude at['wps']=wps if any(rt.time_hours==None for rt in routes): raise AtsException("TAS is less than headwind for some part of trip.") enroute_time=sum(rt.time_hours for rt in routes) fuel=last_fuel_left if stay and stay.fuel: fuel=stay.fuel if not c.ac: raise AtsException("You must choose an aircraft type for this journey to be able to create an ATS flight plan") if c.ac.cruise_burn>1e-3 and fuel: endurance=float(fuel)/float(c.ac.cruise_burn) else: endurance=0.0 if endurance<=0.0: if fuel==None: raise AtsException("Enter a value for 'Fuel at takeoff'!") else: raise AtsException("You do not have enough fuel for the entire journey! This means your endurance would be 0 or negative for one or more legs. Add a fuel stop, shorten the journey, or bring more fuel!") if not c.user.realname: raise AtsException("You should enter your name under profile settings, for use as the name of the commander in the flight plan") phonenr="" if c.user.phonenr: phonenr=c.user.phonenr fir_whenposname.sort() def eqp(x,s): x="".join(re.findall('[A-Z]',x.upper())) if len(x)==0: return s return x dummy=u""" FPL-SEVLI-VG -ULAC/L-V/C -EFKG1330 -N0075F065 DCT 5959N02016E DCT 5949N01936E DCT 5929N01818E DCT 5927N01742E -ZZZZ0130 -DEST/5927N01742E FRÖLUNDA RMK/BORDER CROSSING 40MIN AFTER TAKEOFF DOF/101002 ORGN/ESSAZPZX -E/0300 P/2 A/R W C/ANDERS MUSIKKA +4670123123""" atsfplan=u""" (FPL-%(acreg)s-%(flight_rules)s%(type_of_flight)s -%(actype)s/%(turbulence_category)s-%(equipment)s/%(transponder)s -%(dep_ad)s%(eobt)s -%(cruise_speed)s%(level)s %(route)s DCT -%(dest_ad)s%(ete)s -%(extra_remarks)s -E/%(endurance)s P/%(nr_passengers)s A/%(markings)s%(extra_equipment)s C/%(commander)s %(phonenr)s)"""%(dict( acreg=c.ac.aircraft.replace("-",""), actype=c.ac.atstype, turbulence_category='L', flight_rules='V', type_of_flight='G', equipment=eqp(c.ac.com_nav_equipment,'V'), transponder=eqp(c.ac.transponder_equipment,'C'), extra_equipment=u" %s"%(c.ac.extra_equipment,) if c.ac.extra_equipment else "", dep_ad=dep_ad, eobt=routes[0].depart_dt.strftime("%H%M"), cruise_speed=format_cruise(tas), level=format_alt(altitude), route=(" ".join("%s"%(w['symbolicpos'],) for w in wps[1:-1])), dest_ad=dest_ad, ete=lfvclockfmt(enroute_time), extra_remarks=" ".join(extra_remarks), endurance=lfvclockfmt(endurance), nr_passengers=nr_persons, markings=c.ac.markings, commander=strip_accents(c.user.realname if c.user.realname else u"UNKNOWN").replace(" ",""), phonenr=c.user.phonenr if c.user.phonenr else "")) at['atsfplan']=atsfplan.strip() #print "Adding atstrip:",atsfplan at['spacesummary']=spaces last_fuel_left=routes[-1].accum_fuel_left c.atstrips.append(at) c.atstrips=[at for at in c.atstrips if len(at['wps'])] #response.headers['Content-Type'] = 'application/xml' return render('/ats.mako') except AtsException,ats: redirect(h.url_for(controller='flightplan',action="index",flash=unicode(ats)))
def index(self): print "Index called", session.get('zoom', -1) #print "index called",request.params #user=meta.Session.query(User).filter( # User.user==tripuser()).one() user = meta.Session.query(User).filter( User.user == session['user']).one() ua = request.headers.get('User-Agent', '').lower() c.ie = False if ua.count("msie") and not (ua.count("firefox") or ua.count("chrom") or ua.count("safari")): c.ie = True #print "IE mode:",c.ie c.all_trips = list( meta.Session.query(Trip).filter( Trip.user == session['user']).all()) print "current trip:", session.get('current_trip', None) if not ('current_trip' in session) or session['current_trip'] == None: if user.lasttrip != None: print "Reusing lasttrip:", user.lasttrip session['current_trip'] = user.lasttrip if 'current_trip' in session and meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).count() == 0: session['current_trip'] = None if not 'current_trip' in session or session['current_trip'] == None: trips = meta.Session.query(Trip).filter( Trip.user == tripuser()).all() if len(trips) == 0: trip = Trip(tripuser(), "Default Trip") meta.Session.add(trip) meta.Session.flush() meta.Session.commit() else: trip = min( trips, key=lambda x: x.trip ) #Select first trip, alphabetically - we have no better idea. session['current_trip'] = trip.trip session.save() trip = None if session.get('current_trip', None) != user.lasttrip: user.lasttrip = session.get('current_trip', None) print "Storing lasttrip=", user.lasttrip meta.Session.flush() meta.Session.commit() c.mapvariant = session.get('mapvariant', "airspace") self.set_pos_zoom() zoomlevel = session['zoom'] if c.mapvariant == "elev": if zoomlevel > 8: session['zoom'] = 8 session.save() try: session['last_pos'] = mapper.latlon2merc( mapper.merc2latlon(session['last_pos'], zoomlevel), 8) except Exception: session['last_pos'] = mapper.latlon2merc((59, 18), 8) print "Setting session last pos to 59,18", session[ 'last_pos'] zoomlevel = 8 print "Last pos is:", mapper.merc2latlon(session['last_pos'], zoomlevel) c.merc_x, c.merc_y = session['last_pos'] c.merc5_limx1, c.merc5_limy1, c.merc5_limx2, c.merc5_limy2 = merc_limits( 5, conservative=False, hd=True) c.waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == session['current_trip'])).order_by( Waypoint.ordering).all()) c.tripname = session['current_trip'] c.showarea = session.get('showarea', '') c.showtrack = session.get('showtrack', None) != None c.fastmap = user.fastmap #print "Zoomlevel active: ",zoomlevel c.zoomlevel = zoomlevel c.dynamic_id = '' c.sharing = tripsharing.sharing_active() c.mtime = maptilereader.get_mtime() for way in c.waypoints: print "Name:", way.waypoint if len(c.waypoints): c.next_waypoint_id = max([way.id for way in c.waypoints]) + 1 else: c.next_waypoint_id = 100 assert type(c.next_waypoint_id) == int if c.sharing: c.shared_by = tripuser() if session.get('showarea', ''): c.dynamic_id = session.get('showarea_id', '') if session.get('showtrack', ''): if hasattr(session['showtrack'], 'dynamic_id'): c.dynamic_id = session['showtrack'].dynamic_id return render('/mapview.mako')
def printable(self): extended=False if request.params.get('extended',False): extended=True self.standard_prep(c) self.get_freqs(c.route) if extended: c.origroute=c.route c.route=c.techroute for rt in c.origroute: for sub in rt.subs: sub.freqset=rt.freqset sub.is_start=False sub.is_end=False rt.subs[-1].is_end=True rt.subs[0].is_start=True else: for rt in c.route: rt.is_end=True rt.is_start=True rt.what='' for rt in c.route: rt.notampoints=set() rt.notampoints.update(set([info['item']['notam'] for info in get_notampoints_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos),5)])) for rt in c.route: rt.maxobstelev=obstacle_free.get_obstacle_free_height_on_line( mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)) try: rt.startelev=float(airspace.get_pos_elev(mapper.from_str(rt.a.pos))) except: rt.startelev=float(9999) try: rt.endelev=float(airspace.get_pos_elev(mapper.from_str(rt.b.pos))) except: rt.endelev=float(9999) #for obst in obsts: # print "obst:",obst for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)): rt.notampoints.add(space['name']) if len(c.route)>0: poss=[mapper.from_str(c.route[0].a.pos)] poss+=[mapper.from_str(r.b.pos) for r in c.route] dta,dtb=[c.route[0].a.dt,c.route[-1].b.dt] if dtb==None: c.sunset="unknown" else: print "sunrise:",dta,dtb fall,what=sunrise.earliestsunset([dta,dtb],poss) if what!=None: c.sunset=what elif fall!=None: c.sunset=fall.strftime("%H:%MZ") else: c.sunset="unknown" lat,lon=mapper.from_str(c.route[0].a.pos) c.sunrise=sunrise.sunrise_str(dta,lat,lon) return render('/printable.mako')
def index(self,flash=None): user=meta.Session.query(User).filter( User.user==session['user']).one() c.worklist=self.get_worklist() c.flash=flash return render('/airportsproj.mako')
def obstacles(self): routes,baseroute=get_route(tripuser(),session['current_trip']) tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() c.trip=tripobj.trip id2order=dict([(rt.a.id,rt.a.ordering) for rt in baseroute]) byidsorted=sorted(self.get_obstacles(routes).items(),key=lambda x:id2order.get(x[0],0)) out=[] def classify(item): #print item vertlimit=1000 if item.get('kind',None)=='lowsun': return "#ffffb0" if item.get('kind',None)=='terrain': vertlimit=500 try: margin=item['closestalt']-mapper.parse_elev(item['elev']) except Exception: return "#0000ff" #Unknown margin, unknown height if item['dist']>0.6/1.852: return None #Not really too close anyway if margin<0: return "#ff3030" if margin<vertlimit: return "#ffb0b0" return None dupecheck=dict() for idx,items in byidsorted: for item in items: ident=(item['name'],item['pos'],item.get('elev',None)) dupecheck.setdefault(ident,[]).append(item) bestdupe=dict() for ident,dupes in dupecheck.items(): best=min(dupes,key=lambda x:x['dist']) bestdupe[ident]=best for idx,items in byidsorted: cur=[] for item in items: dist_from_a=item['dist_from_a'] dist_from_b=item['dist_from_b'] if abs(dist_from_a)<0.5: descr="Near %s"%(item['a'].waypoint,) elif abs(dist_from_b)<0.5: descr="Near %s"%(item['b'].waypoint,) elif dist_from_a<dist_from_b: descr="%.0fNM %s of %s"%(dist_from_a,item['dir_from_a'],item['a'].waypoint) else: descr="%.0fNM %s of %s"%(dist_from_b,item['dir_from_b'],item['b'].waypoint) ident=(item['name'],item['pos'],item.get('elev',None)) best=bestdupe[ident] if not (best is item): continue #if ident in seen: continue #seen.add(ident) cur.append(dict( routepointdescr=descr, #dir_from_a=item['dir_from_a'], #fromwhat=fromwhat, kind=item.get('kind',None), bearing=item.get('bearing',None), along_nm=dist_from_a, dist=item['dist'], name=item['name'], closestalt=item['closestalt'], elev=item.get('elev',None))) cur[-1]['color']=classify(cur[-1]) out.append((items[0]['a'].waypoint,sorted(cur,key=lambda x:x['along_nm']))) c.items=out return render('/obstacles.mako')
def show(self): ad=request.params['ad'] cksum=request.params['checksum'] chartobj=None for adobj in ec.get_airfields(): bb=False if adobj['name']==ad and 'adcharts' in adobj: for adchart in adobj['adcharts'].values(): if adchart['checksum']==cksum: chartobj=adchart bb=True break if bb: break else: self.error("No such airport/picture "+ad+"/"+cksum) projs=meta.Session.query(AirportProjection).filter(sa.and_( AirportProjection.user==session['user'], AirportProjection.airport==ad, AirportProjection.mapchecksum==adchart['checksum'])).all() c.markers=meta.Session.query(AirportMarker).filter(sa.and_( AirportMarker.user==session['user'], AirportMarker.airport==ad, AirportMarker.mapchecksum==adchart['checksum'])).order_by(AirportMarker.latitude,AirportMarker.longitude,AirportMarker.x,AirportMarker.y).all() if not projs: proj=AirportProjection() proj.user=session['user'] proj.airport=ad proj.mapchecksum=str(adchart['checksum']) proj.updated=datetime.utcnow() proj.matrix=(1,0,0,1,0,0) proj.scale=None proj.north=None meta.Session.add(proj) meta.Session.flush() meta.Session.commit() else: proj,=projs proj.mapchecksum=str(proj.mapchecksum) if all([x==0 for x in proj.matrix[4:6]]): projmatrix=self.invent_matrix(proj.mapchecksum,adchart['variant']) else: projmatrix=proj.matrix A=projmatrix[0:4] T=projmatrix[4:6] transform=customproj.Transform(A,T) c.matrix=projmatrix c.initial_scroll_x=request.params.get("scroll_x",0) c.initial_scroll_y=request.params.get("scroll_y",0) c.maptype=request.params.get("maptype","chart") c.variant=adchart['variant'] c.curadmarker=session.get('curadmarker',(0,0)) c.img=adchart['blobname']+","+adchart['checksum'] c.flash=None c.ad=ad c.mapchecksum=adchart['checksum'] c.mapsize=adchart.get('mapsize',(210,297)) c.scale=proj.scale if proj.scale!=None else "" c.north=proj.north if proj.north!=None else "" c.runways=[] c.arp=transform.to_pixels(mapper.from_str(adobj['pos'])) arp1m=mapper.latlon2merc(mapper.from_str(adobj['pos']),17) arp2m=mapper.latlon2merc(mapper.from_str(adobj['pos']),17) arp1m=(arp1m[0],arp1m[1]-250) arp2m=(arp2m[0]+250,arp2m[1]) c.arp1=transform.to_pixels(mapper.merc2latlon(arp1m,17)) c.arp2=transform.to_pixels(mapper.merc2latlon(arp2m,17)) def dist(x,y): return math.sqrt((x[0]-y[0])**2+(x[1]-y[1])**2) c.ratio=abs(dist(c.arp,c.arp1)-dist(c.arp,c.arp2))/max(dist(c.arp,c.arp1),dist(c.arp,c.arp2)); c.transform_reasonable=True x,y=c.arp if x<-200 or y<-200 or x>=4000 or y>=4000: c.transform_reasonable=False c.revmarkers=[] c.width,c.height=chartobj['render_width'],chartobj['render_height'] try: c.base_coords=\ [mapper.latlon2merc(transform.to_latlon((0,0)),13), mapper.latlon2merc(transform.to_latlon((c.width,0)),13), mapper.latlon2merc(transform.to_latlon((0,c.height)),13), mapper.latlon2merc(transform.to_latlon((c.width,c.height)),13)] except Exception: print "problem with basecoords:",traceback.format_exc() c.base_coords=[(0,0) for x in xrange(4)] for mark in c.markers: lat,lon=transform.to_latlon((mark.x,mark.y)) if mark.latitude: lat=mark.latitude if mark.longitude: lon=mark.longitude pos=transform.to_pixels((lat,lon)) c.revmarkers.append(pos) for rwy in adobj.get('runways',[]): ends=rwy['ends'] latlon1=mapper.from_str(ends[0]['pos']) latlon2=mapper.from_str(ends[1]['pos']) print rwy,"Runway pos",latlon1," to ",latlon2 p1=transform.to_pixels(latlon1) p2=transform.to_pixels(latlon2) for p in [p1,p2]: x,y=p if x<-200 or y<-200 or x>=4000 or y>=4000: c.transform_reasonable=False c.runways.append(( (int(p1[0]),int(p1[1])), (int(p2[0]),int(p2[1])) )) c.random=md5.md5(pickle.dumps(projmatrix)).hexdigest() return render('/airportproj.mako')
c.all_aircraft = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'])).all() if c.trip.acobj == None: c.ac = None c.advanced_model = False else: c.ac = c.trip.acobj if session.get('cur_aircraft', None) != c.trip.acobj.aircraft: session['cur_aircraft'] = c.trip.acobj.aircraft session.save() c.advanced_model = c.ac.advanced_model c.sharing = tripsharing.sharing_active() #print repr(c) return render('/flightplan.mako') def select_aircraft(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview', action="index")) if not tripsharing.sharing_active(): tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() tripobj.aircraft = request.params['change_aircraft'] if tripobj.aircraft.strip() == "--------": tripobj.aircraft = None else: for route in meta.Session.query(Route).filter( sa.and_(
def index(self, flash=None): user = meta.Session.query(User).filter( User.user == session['user']).one() c.worklist = self.get_worklist() c.flash = flash return render('/airportsproj.mako')
def index(self, bad_values=dict(), orig=None): cur_acname = session.get('cur_aircraft', None) c.ac = None if cur_acname: cac = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'], Aircraft.aircraft == cur_acname)).all() if len(cac) == 1: c.ac = cac[0] c.burn_warning = None c.all_aircraft = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'])).all() if len(c.all_aircraft) and c.ac == None: c.ac = c.all_aircraft[0] print "c.ac", c.ac if c.ac and c.ac.advanced_model: print "adv climb rate", c.ac.adv_climb_rate for prop in advprops: print "prop", prop, "val:", getattr(c.ac, prop) if all(getattr(c.ac, prop) == () for prop in advprops): #Default-values for Cessna 172 with 160hp engine. c.ac.adv_climb_rate = [ 770, 725, 675, 630, 580, 535, 485, 440, 390, 345 ] c.ac.adv_climb_burn = [62, 60, 55, 50, 45, 42, 40, 37, 35, 33] c.ac.adv_climb_speed = [73, 73, 72, 72, 71, 71, 70, 69, 69, 68] c.ac.adv_cruise_burn = [ 32, 32, 32, 32, 32, 32, 30, 29, 28.5, 28 ] c.ac.adv_cruise_speed = [ 116, 117, 118, 118, 118, 118, 118, 118, 118, 118 ] c.ac.adv_descent_rate = [ 400, 400, 400, 400, 400, 400, 400, 400, 400, 400 ] c.ac.adv_descent_burn = [ 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 ] c.ac.adv_descent_speed = [ 116, 117, 118, 119, 120, 121, 122, 122, 122, 122 ] try: for idx, (cruise_burn, climb_burn) in enumerate( zip(c.ac.adv_cruise_burn, c.ac.adv_climb_burn)): if climb_burn < cruise_burn: c.burn_warning = "You have entered a fuel consumption for climb that is lower than that for cruise (for altitude %d). Is this right?" % ( idx * 1000) break except Exception: print "Internal error in ac, burn check" pass for prop in advprops: val = getattr(c.ac, prop) if val == None: val = [] l = 0 else: val = list(val) l = len(val) val.extend([0 for x in xrange(10 - l)]) setattr(c.ac, prop, tuple(val)) c.adv_props = [("Cruise Speed (kt TAS)", "adv_cruise_speed"), ("Cruise Consumption (L/h)", "adv_cruise_burn"), ("Climb Speed (kt TAS)", "adv_climb_speed"), ("Climb Consumption (L/h)", "adv_climb_burn"), ("Climb Rate (fpm)", "adv_climb_rate"), ("Descent Speed (kt TAS)", "adv_descent_speed"), ("Descent Consumption (L/h)", "adv_descent_burn"), ("Descent Rate (fpm)", "adv_descent_rate")] def getval(prop, alt): ialt = alt / 1000 raw = getattr(c.ac, prop)[ialt] s = "%.1f" % (raw, ) if s.endswith(".0"): return s[:-2] return s c.getval = getval else: if c.ac: if c.ac.climb_burn < c.ac.cruise_burn: c.burn_warning = "You have entered a fuel consumption for climb that is lower than that for cruise. Is this right?" def get_msgerror(x): msgs = set() for alt in xrange(0, 10000, 1000): msg = bad_values.get((x, alt), None) if msg: msgs.add(msg) return "<span style=\"background-color:#ffd0d0\">" + cgi.escape( ", ".join(msgs)) + "</span>" c.aircraft_name_error = bad_values.get('aircraft', None) c.msgerror = get_msgerror c.fmterror = lambda x, alt=0: 'style="background:#ff8080;' if bad_values.get( (x, alt), None) else '' c.newly_added = False if request.params.get('flash', '') == 'new': c.flash = 'A new aircraft was added! Enter its registration/name and other info below.' c.newly_added = True else: c.flash = '' if c.ac: c.orig_aircraft = c.ac.aircraft else: c.orig_aircraft = '' if orig != None: c.orig_aircraft = orig return render('/aircraft.mako')