Exemplo n.º 1
0
def direct_route(source, dest):
    '''Search for trains between source & dest & returns a list of dictionary containing train metadata'''

    source_trn = []
    with db.opendb(db.MAINDB) as sch:
        sch._exec("SELECT train FROM schedule WHERE station=(?)", (source, ))
        t = sch._fetchone()
        while t != None:
            source_trn.append(t['train'])
            t = sch._fetchone()
        #print(source_trn)
    if (source_trn == []):
        return []

    dest_trn = []
    with db.opendb(db.MAINDB) as sch:
        sch._exec("SELECT train FROM schedule WHERE station=(?)", (dest, ))
        t = sch._fetchone()
        while t != None:
            dest_trn.append(t['train'])
            t = sch._fetchone()

    if (dest_trn == []):
        return []
    #print(dest_trn)
    return_list = []
    for i in range(len(source_trn)):
        trn = source_trn[i]
        if (trn in dest_trn):
            if (comes_after(trn, source, dest)):
                return_list.append(db.train_metadata(trn))

    return return_list
Exemplo n.º 2
0
def comes_after(train, source, dest):
    '''Checks that source comes before dest in the train's path'''

    with db.opendb(db.MAINDB) as stnlist:
        stnlist._exec("SELECT station from schedule WHERE train=(?)",
                      (train, ))
        array = []
        t = stnlist._fetchone()
        while (t != None):
            array.append(t['station'])
            t = stnlist._fetchone()

    if (array == []):
        return 0

    try:
        a = array.index(source)
        b = array.index(dest)
    except ValueError:
        return 0

    if (a < b):
        return 1
    else:
        return 0
Exemplo n.º 3
0
def get_trains(code,hours):
    try:
        hours=int(hours)
    except ValueError:
        hours=0
    else:
        if(hours>=6):
            hours=6
    seconds=3600*hours
    now=int(seconds_since_midnight())
    code=code.upper()
    t=[]
    with db.opendb(db.MAINDB) as tr:
        tr._exec('SELECT train,arrival,departure FROM schedule WHERE station=(?)',(code,))

        t=tr._fetchall()
    
    for i in t:
        i['departure']=toseconds(i)
    
    lst=[]
    for i in t:
        ts=i['departure']
        sub=ts-now
        if sub<seconds and sub>0:
            #print(i['train'],ts)
            lst.append(i['train'])

    if now+seconds>86400:
        seconds=seconds-86400-now
        now=0
    
    if now==0:
        for i in t:
            ts=i['departure']
            sub=ts-now
            if sub<seconds and sub>0:
                lst.append(i['train'])
    rem=[]
    for i in range(len(lst)):
        with db.opendb(db.TRAINDB) as tr:
            tr._exec("SELECT days FROM train WHERE number=(?)",(lst[i],))
            t=tr._fetchall()
            if weekday() not in t[0]['days']:
                rem.append(i)
    map(lambda i: lst.remove(i),rem)
    return format_result_json(lst,code)
Exemplo n.º 4
0
def format_result_json(p):
    d={}
    d['response_code']=200
    d['train_start_date']={}
    d['pnr']=p['pnr']
    #d['coach_position']=0 # For backwards comptability
    d['doj']=strip_inline_space(p['doj'])
    d['train_num']=p['number'][1:]
    train_md=db.train_metadata(d['train_num'])
    d['train_name']=train_md['name']
    t={}
    if not p['error']:
        date=[int(dt) for dt in d['doj'].split('-')]
        traveldate=datetime(date[2],date[1],date[0])
        with db.opendb(db.MAINDB) as sch:
            sch._exec("SELECT * FROM schedule WHERE train=(?) AND station=(?)",(d['train_num'],p['boarding']))
            stn_sch=sch._fetchone()
            if stn_sch!=None:
                runday=stn_sch['day']-1
                start_date=traveldate-timedelta(days=runday)
                t['year']=start_date.year
                t['month']=start_date.month
                t['day']=start_date.day
    d['train_start_date']=t
    d['from_station']={}
    stn_md=db.station_metadata(p['from'])
    d['from_station']['code']=stn_md['code']
    d['from_station']['name']=stn_md['fullname']
    d['to_station']={}
    stn_md=db.station_metadata(p['to'])
    d['to_station']['code']=stn_md['code']
    d['to_station']['name']=stn_md['fullname']
    d['reservation_upto']={}
    stn_md=db.station_metadata(p['upto'])
    d['reservation_upto']['code']=stn_md['code']
    d['reservation_upto']['name']=stn_md['fullname']
    d['boarding_point']={}
    stn_md=db.station_metadata(p['boarding'])
    d['boarding_point']['code']=stn_md['code']
    d['boarding_point']['name']=stn_md['fullname']
    d['class']=p['class']
    d['error']=p['error']
    d['chart_prepared']=p['chart']
    d['total_passengers']=p['total']
    d['passengers']=[]
    
    curr_status=p['current_status']
    book_status=p['booking_status']
    coach_position=p['coach_position']
    for i in range(p['total']):
        t={}
        t['no']=i+1
        t['booking_status']=strip_inline_space(book_status[i])
        t['current_status']=strip_inline_space(curr_status[i])
        t['coach_position']=coach_position[i]
        d['passengers'].append(t)

    d=json.dumps(d,indent=4)
    return d
Exemplo n.º 5
0
def fuzzyfullname(word):
    with db.opendb(db.STNDB) as stn:
        stn._exec("SELECT code,fullname FROM slist")
        t=stn._fetchall()
        word=word.upper()
        for i in t:
            if word in i['fullname'].upper():
                return i['code']
        return ""
Exemplo n.º 6
0
def fuzzyfullname(word):
    with db.opendb(db.STNDB) as stn:
        stn._exec("SELECT code,fullname FROM slist")
        t = stn._fetchall()
        word = word.upper()
        for i in t:
            if word in i['fullname'].upper():
                return i['code']
        return ""
Exemplo n.º 7
0
def stnsuggest(word):
    with db.opendb(db.STNDB) as stn:
        stn._exec("SELECT code,fullname FROM slist")
        t = stn._fetchall()
        word = word.upper()
        l = []
        for i in t:
            if word in i['fullname']:
                l.append(i)
        return l
Exemplo n.º 8
0
def numsuggest(num):
    with db.opendb(db.TRAINDB) as train:
        train._exec("SELECT number FROM train")
        t = train._fetchall()
        t = (loco['number'] for loco in t)
        l = []
        for i in t:
            if i.startswith(num):
                l.append(i)
        return l
def stnsuggest(word):
    with db.opendb(db.STNDB) as stn:
        stn._exec("SELECT code,fullname FROM slist")
        t=stn._fetchall()
        word=word.upper()
        l=[]
        for i in t:
            if word in i['fullname']:
                l.append(i)
        return l
Exemplo n.º 10
0
def get_trains(code, hours):
    seconds = 3600 * int(hours)
    now = int(seconds_since_midnight())
    code = code.upper()
    t = []
    with db.opendb(db.MAINDB) as tr:
        tr._exec(
            'SELECT train,arrival,departure FROM schedule WHERE station=(?)',
            (code, ))

        t = tr._fetchall()

    for i in t:
        i['departure'] = toseconds(i)

    lst = []
    for i in t:
        ts = i['departure']
        sub = ts - now
        if sub < seconds and sub > 0:
            #print(i['train'],ts)
            lst.append(i['train'])

    if now + seconds > 86400:
        seconds = seconds - 86400 - now
        now = 0

    if now == 0:
        for i in t:
            ts = i['departure']
            sub = ts - now
            if sub < seconds and sub > 0:
                lst.append(i['train'])
    rem = []
    for i in range(len(lst)):
        with db.opendb(db.TRAINDB) as tr:
            tr._exec("SELECT days FROM train WHERE number=(?)", (lst[i], ))
            t = tr._fetchall()
            if weekday() not in t[0]['days']:
                rem.append(i)
    map(lambda i: lst.remove(i), rem)
    return format_result_json(lst, code)
Exemplo n.º 11
0
def namesuggest(name):
    name = name.upper()
    with db.opendb(db.TRAINDB) as train:
        train._exec("SELECT name FROM train")
        t = train._fetchall()
        t = (loco['name'] for loco in t)
        l = []
        for i in t:
            if i.startswith(name):
                l.append(i)
        return l
def numsuggest(num):
    with db.opendb(db.TRAINDB) as train:
        train._exec("SELECT number FROM train")
        t=train._fetchall()
        t=(loco['number'] for loco in t)
        l=[]
        for i in t:
            if i.startswith(num):
                train._exec("SELECT name FROM train WHERE number=(?)",(i,))
                name=train._fetchone()
                l.append(i+' ('+name['name']+')')
        return l
Exemplo n.º 13
0
def nearby_stn(qcode,point):
    if (point[0]==None or point[1]==None) or (point[0]==0.0 and point[1]==0.0): return
    radius=25 #km (search within this radius)
    m=[]
    with db.opendb(db.STNDB) as cdb:
        cdb._exec("SELECT code,lat,lng FROM slist WHERE code!=(?)",(qcode,))
        while(1):
            t=cdb._fetchone()
            if(t==None):
                break
            if(distance(point,(t['lat'],t['lng']))<=radius):
                m.append(t['code']) #append the nearby station code
    return m
Exemplo n.º 14
0
def nearby_stn(qcode, point):
    if (point[0] == None or point[1] == None) or (point[0] == 0.0
                                                  and point[1] == 0.0):
        return
    radius = 25  #km (search within this radius)
    m = []
    with db.opendb(db.STNDB) as cdb:
        cdb._exec("SELECT code,lat,lng FROM slist WHERE code!=(?)", (qcode, ))
        while (1):
            t = cdb._fetchone()
            if (t == None):
                break
            if (distance(point, (t['lat'], t['lng'])) <= radius):
                m.append(t['code'])  #append the nearby station code
    return m
def namesuggest(name):
    name=name.upper()
    with db.opendb(db.TRAINDB) as train:
        train._exec("SELECT name FROM train")
        t=train._fetchall()
        t=(loco['name'] for loco in t)
        l=[]
        cnt=Counter()
        d={}
        for i in t:
            if i.startswith(name):
                cnt[i]+=1
                train._exec("SELECT number FROM train WHERE name=(?)",(i,))
                if cnt[i]==1:
                    nums=train._fetchall()
                    d[i]=nums
                num=d[i][0]
                if cnt[i]>1:
                    num=d[i][cnt[i]-1]
                    
                l.append(i+' ('+num['number']+')')
        return l
Exemplo n.º 16
0
def train_route(num):
    with db.opendb(db.TRAINDB) as train:
        m=train.metadata(num)
    with db.opendb(db.MAINDB) as train:
        s=getschedule(train,num)
    return format_result_json(m,s)
Exemplo n.º 17
0
def station_metadata(stn):
    with db.opendb(db.STNDB) as station:
        m=station.metadata(stn)
        return m
Exemplo n.º 18
0
Arquivo: menu.py Projeto: uniite/imd
# Modified 12/9 for use with new imd_dbe

print "importing db"
import db as imd_db
#Songs > : imd_menu_goto("songs")
#Artists > : imd_menu_goto("artists")
#Albums > : imd_menu_goto("albums")
#Genres > : imd_menu_goto("genres")
#Settings > : imd_goto_menu("settings")
print "opening db"
imd_db.opendb()

print "menu.py done loading"

def home ():
	# Main "Home" Menu
	return ["Home", [("Songs", "songs()"), ("Artists", "artists()"), ("Albums", "albums()"), ("Genres", "genres()")]]

def artists (genre = None):
	if genre == None:
		temp = imd_db.getrecs()
		items = set()
	else:
		temp = imd_db.getrecs(genre = genre)
		items = set([("All Songs", "songs(genre = '%s')" % genre )])
	for item in temp:
		items.add((item.artist, "albums(artist = '%s')" % item.artist))
	# Return sorted list...same as all the others
	items = list(items)
	items.sort()
	return ["Artists", items]
Exemplo n.º 19
0
def nametonum(n):
    with db.opendb(db.TRAINDB) as train:
        m=train.metadata(n)
        return m['number']
Exemplo n.º 20
0
def fuzzycode(word):
    with db.opendb(db.STNDB) as stn:
        return stn.fuzzy(word)
Exemplo n.º 21
0
def fuzzycode(word):
    with db.opendb(db.STNDB) as stn:
        return stn.fuzzy(word)
Exemplo n.º 22
0
def fuzzy(word):
    with db.opendb(db.TRAINDB) as train:
        return train.fuzzy(word)
Exemplo n.º 23
0
def numtoname(n):
    with db.opendb(db.TRAINDB) as train:
        m=train.metadata(n)
        return m['name']
Exemplo n.º 24
0
def train_route(num):
    with db.opendb(db.TRAINDB) as train:
        m=train.metadata(num)
    with db.opendb(db.MAINDB) as train:
        s=getschedule(train,num)
    return format_result_json(m,s)
Exemplo n.º 25
0
def station_metadata(stn):
    with db.opendb(db.STNDB) as station:
        m=station.metadata(stn)
        return m