Beispiel #1
0
def plans_query(request, st_start, st_end, when):
	
	try:
		when = datetime.strptime(when, '%Y-%m-%dT%H:%M:%S')
		st_start, = Station.search(st_start)
		st_end, = Station.search(st_end)
	except ValueError:
		raise
		raise Redirect(reverse('kolstat-plans-new'))

	connections = wrapper.make_query(st_start, st_end, when)

	return dict(conn = connections, source = st_start, destination = st_end, when = when)
Beispiel #2
0
def import_couple(yaml, mode):
	for field in ('station', 'trains'):
		if field not in yaml:
			raise ValueError('Zły yaml - brak "{field}"'.format(field = field))

	trains = yaml['trains']
	station_name = yaml['station']
	
	(t1 ,), (t2 ,) = list(map(Train.search, trains))
	s, = Station.search(station_name)

	print(t1, t2)

	to_add = []

	for tt in t1.timetables():
		try:
			st = tt.stops().get(station = s)
		except TrainStop.DoesNotExist:
			continue
		try:
			st2 = t2.timetables().get(date = tt.date).stops().get(station = s)
		except TrainTimetable.DoesNotExist as xxx_todo_changeme:
			TrainStop.DoesNotExist = xxx_todo_changeme
			continue

		print(tt.date)

		to_add.append(TrainCouple(stop1 = st2, stop2 = st))
		to_add.append(TrainCouple(stop1 = st, stop2 = st2))

	TrainCouple.objects.bulk_create(to_add)
Beispiel #3
0
def station_show(request, station = None):
	if request.method == 'POST':
		if 'station' in request.POST:
			station = request.POST['station']
	
	if station is None:
		raise Redirect(reverse('kolstat-stations'))

	
	st = Station.search(station)
	if len(st) == 0 or len(st) > 1:
		raise Redirect(reverse('kolstat-stations'))

	st, = st

	stops = st.next_departures(5)

	return dict(station = st, stops = stops)
Beispiel #4
0
def favourites(request):
	all_picto = FavPictogram.objects.order_by('name')
	were_errors = False

	pictos = []
	for pic in all_picto:
		error = None
		new_station = None
		try:
			current = request.user.get_profile().userfavouritestation_set.get(pictogram = pic).station
		except UserFavouriteStation.DoesNotExist:
			current = None

		if request.method == 'POST':
			if pic.name in request.POST:
				st_name = request.POST[pic.name]
				if st_name:
					try:
						new_station, = Station.search(st_name)
					except ValueError:
						error = 'Brak takiej stacji.'
						were_errors = True

		definition = (pic, current, error, new_station)

		pictos.append(definition)

	if request.method != 'POST' or were_errors:
		return dict(pictos = pictos, errors = were_errors)
	
	current = request.user.get_profile().userfavouritestation_set.all().delete()
	for p, _, _, st in pictos:
		if st is not None:
			UserFavouriteStation.objects.create(profile = request.user.get_profile(), station = st, pictogram = p)
	
	raise Redirect(reverse('user-profile'))
Beispiel #5
0
	def clean(self, value):
		try:
			st, = Station.search(value)
			return st
		except ValueError:
			raise forms.ValidationError('Brak takiej stacji')
Beispiel #6
0
def acquire(name, conn = None):
	if name.startswith('R '):
		name = name[2:]
	if conn is None:
		conn = http.client.HTTPConnection(SERVER)
	conn.request('GET', '/bin/trainsearch.exe/pn?trainname={}'.format(urllib.parse.quote(name)))
	resp = conn.getresponse()

	data = resp.read()

	res = re.findall(REGEXP.format(server = SERVER), data, re.DOTALL | re.MULTILINE)

	variants_rel = {}
	variants = {}
	variants_no = 0

	for dkod, nr, skad, dokad, dnikursowania in res:
		if not the_same(nr.strip(), name):
			continue

		skad = normalize(skad)
		dokad = normalize(dokad)

		if not polskie(skad) or not polskie(dokad):
			continue

		dnikursowania = normalize(dnikursowania).strip()
		
		vrel = skad, dokad

		variant = None

		for k, v in list(variants_rel.items()):
			if skad in k or dokad in k:
				nk = list(k)
				if skad not in k:
					nk.append(skad)
				if dokad not in k:
					nk.append(dokad)

				nk = tuple(nk)

				del variants_rel[k]
				variants_rel[nk] = v
				variant = v
				

		if variant is None:
			variants_no += 1
			variant = chr(variants_no + 64)
			variants[variant] = ({}, {}, [], [], 1)
			variants_rel[vrel] = variant

		result, roz, ss, dd, rk = variants[variant]
		
		_, wazne = dnikursowania.split('kursuje:')
		pd = parse_dni(wazne.strip())

		arr = Station.search(dokad)[0].hafasID
		dep = Station.search(skad)[0].hafasID
		
		url = '/bin/traininfo.exe/pn/{}?L=vs_java3'.format(dkod)
		conn.request('GET', url)
		resp = conn.getresponse()
		data = resp.read()
		
		dom = minidom.parseString('<main>{}</main>'.format(data))
		main,  = dom.childNodes
		elems = main.getElementsByTagName('St')
		first = elems[0]
		
		deptime = first.getAttribute('depTime')
		
		if dep not in ss:
			ss.append(dep)

		if arr not in dd:
			dd.append(arr)

		for day in pd:
			tt = "1{:0>9}{:0>9}{}{}".format(dep,arr,day.strftime('%Y%m%d'),deptime.replace(':',''))
			tt = "{:x}".format( int(tt))
			result[day] = tt
			roz[day] = rk

		rk += 1

		variants[variant] = (result, roz, ss, dd, rk)

	return {v: dict(source = ss, destination = dd, ids = result, roz = roz) for v, (result, roz, ss, dd, _) in list(variants.items()) }
Beispiel #7
0
#!/usr/bin/env python2
# coding: utf-8

import os,sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings'
sys.path.extend(('../..', '../../..'))

from kolstatapp.models import Station
from .make_query import make_simple_query
from datetime import datetime

radom, = Station.search("Radom")
ruda_wielka, = Station.search("Warszawa Wschodnia")
now = datetime(2013, 1, 11, 4, 57)

ans = make_simple_query(radom, ruda_wielka, now)
from pprint import pprint
pprint(ans)
Beispiel #8
0
#!/usr/bin/env python3
# coding: utf-8

import os,sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings'
sys.path.extend(('../..', '../../..'))

from kolstatapp.models import Station
from normal_to_hafas import Hafas

nazwa = input('Podaj nazwę stacji: ')
hs = Hafas.searchStation(nazwa)[0]
print(hs.toString())
try:
	s, = Station.search(hs.externalId)
	print(s.id)
	sys.exit(0)
except ValueError:
	s = Station()

gsk = int(input('gsk: '))
s.gskID = gsk
s.hafasID = hs.externalId
s.name = hs.name
print(s)
s.save()
print(s.id)
Beispiel #9
0
def import_train(yaml, mode, dijkstra_lock, mysql_lock):
	train = Train()

	name = yaml['name']
	category, number = name.split(' ')

	try:
		with mysql_lock:
			t, = train.search(name, variant = yaml['variant'])
	except ValueError:
		pass
	else:
		if mode == 'force' or True:
			t.delete()
		else:
			return


	with mysql_lock:
		train.category = TrainCategory.objects.get(name = category)
	
	train.number = number
	train.variant = yaml['variant']

	with mysql_lock:
		train.save()

	operations = yaml['operations']

	for oper in operations:
		if oper['mode'] == 'interval':
			start = oper['from']
			end = oper['to']
			dates = [ end ]
			while start != end:
				dates.append(start)
				start += DZIEN
		elif oper['mode'] == 'single':
			dates = [ oper['date'] ]
		elif oper['mode'] == 'multi':
			dates = oper['dates']

		timetable = oper['timetable']
		
		tts = []
		for i in dates:
			tts.append(TrainTimetable(train = train, date =i))
		
		with mysql_lock:
			TrainTimetable.objects.bulk_create(tts)

		tts = train.traintimetable_set.all()
		ttbd = {}

		for x in tts:
			ttbd[x.date] = x

		stops = []

		tt = ttbd[dates[0]]

		i = 1
		prev = None
		arr_over = False

		for description in timetable:
			stop = TrainStop(timetable = tt)
			try:
				stop.station = Station.search(description['station'])[0]
			except IndexError:
				print(description)
				raise
			if 'departure' in description:
				stop.departure = datetime.combine(tt.date, time_from_yaml(description.get('departure', None)))
			if 'arrival' in description:
				stop.arrival = datetime.combine(tt.date, time_from_yaml(description.get('arrival', None)))
			stop.track = description.get('track', None)
			stop.platform = description.get('platform', None)
			stop.order = i

			if prev is not None:
				if arr_over or stop.arrival < prev.departure:
#					stop.arrival_overnight = 1
					arr_over = True
			
			if arr_over or (stop.arrival is not None and stop.departure is not None and stop.arrival > stop.departure):
#				stop.departure_overnight = 1
				arr_over = True

			if prev is None:
				stop.distance = 0.0
			else:
				dijkstra_lock.acquire()
				stop.distance = prev.distance + Dijkstra.length(prev.station.gskID, stop.station.gskID)
				dijkstra_lock.release()

			prev = stop

			stops.append(stop)

			i += 1

		with mysql_lock:
			TrainStop.objects.bulk_create(stops)

		cursor = connection.cursor()

		for d, tt in ttbd.items():
			if d == dates[0]: continue
			tto = ttbd[dates[0]]
			ttn = ttbd[d]

			with mysql_lock:
				cursor.execute(''' INSERT INTO kolstatapp_trainstop (timetable_id, station_id, arrival, departure, track, platform, distance, "order") SELECT {0}, station_id, arrival + '{2} days', departure + '{2} days', track, platform, distance, "order" FROM kolstatapp_trainstop WHERE timetable_id = {1}'''.format(ttn.pk, tto.pk, (d - dates[0]).days))

		with mysql_lock:
			transaction.commit_unless_managed()
Beispiel #10
0
# coding: utf-8
import os,sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings'
sys.path.extend(('../../../', '../../../../'))

from kolstatapp.models import Train, Discount, TrainStop, Station
from datetime import date

discounts = Discount.objects.all()

KM6014, = Train.search('KM 6014')
TLK31108, = Train.search('TLK 31108')
TLK15117, = Train.search('TLK 15117')

RW, = Station.search('Ruda Wielka')
RA, = Station.search('Radom')
WW, = Station.search('Warszawa Wschodnia')
GD, = Station.search('Gdynia Główna')

dzien = date(2013, 1, 3)

Ruda_Wielka = TrainStop.objects.get(timetable__date = dzien, timetable__train = KM6014, station = RW)
Radom1 = TrainStop.objects.get(timetable__date = dzien, timetable__train = KM6014, station = RA)

Radom2 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK31108, station = RA)
WW1 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK31108, station = WW)

WW2 = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK15117, station = WW)
Gdynia = TrainStop.objects.get(timetable__date = dzien, timetable__train = TLK15117, station = GD)
Beispiel #11
0
#!/usr/bin/env python2
# coding: utf-8

import os,sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'kolstat.settings'
sys.path.extend(('../..', '../../..'))

from kolstatapp.models import Station
from .make_query import make_simple_query
from datetime import datetime

for x in sys.argv[1:]:
		
	try:
		if x.isdigit():
			radom, = Station.objects.filter(pk = int(x))
		else:
			radom, = Station.search(x)
	except ValueError:
		print("NOPE")
	else:
		print(radom.pk, radom.name)