Skip to content

Instantly share code, notes, and snippets.

@pkociepka
Last active February 3, 2019 22:22
Show Gist options
  • Select an option

  • Save pkociepka/f0d878e4c461f1b9cf12b8f98d18d935 to your computer and use it in GitHub Desktop.

Select an option

Save pkociepka/f0d878e4c461f1b9cf12b8f98d18d935 to your computer and use it in GitHub Desktop.
from collections import defaultdict
from ftplib import FTP
from random import randint
import re
import requests
POSITIONS_URL = "http://91.223.13.70/internetservice/geoserviceDispatcher/services/vehicleinfo/vehicles"
BLOCKS_URL = "ztp.krakow.pl"
BLOCKS_FILE = "RETR VehiclePositions_A.pb"
def optimalDistance(x, y):
# returns such delta that x + delta = y (for most cases)
distances = defaultdict(lambda: 0)
for x_i in x:
for y_j in y:
distances[y_j - x_i] += 1
return sorted(list(distances.items()), key=lambda x: x[1], reverse=True)[0][0]
def getPositions():
return [x for x in requests.get(POSITIONS_URL).json()['vehicles'] if 'isDeleted' not in x.keys() or not x["isDeleted"]]
def getBlocks():
filename = str(randint(1, 10e6))
with FTP(BLOCKS_URL) as ftp:
ftp.login()
ftp.retrbinary(BLOCKS_FILE, open(filename, 'wb').write)
with open(filename, encoding="latin1") as pb_file:
data = pb_file.read()
blocks = [x[6:] for x in re.findall("block_[0-9]+", data)]
trips = [x[5:] for x in re.findall("trip_[0-9]+", data)]
numbers = [x[1:] for x in re.findall("\x05[A-Z]{2}[0-9]{3}", data)]
result = dict()
for i in range(len(blocks)):
result[4096*int(blocks[i])+int(trips[i])] = numbers[i]
return result
positions = getPositions()
blocksToSideNums = getBlocks()
delta = optimalDistance([int(x['tripId']) for x in positions], list(blocksToSideNums.keys()))
print(delta)
newPositions = []
for position in positions:
expected_block = int(position['tripId']) + delta
if expected_block in blocksToSideNums.keys():
newPositions.append({
'name': position['name'],
'id': position['id'],
'tripId': position['tripId'],
'blockId': expected_block,
'sideNumber': blocksToSideNums[expected_block]
})
print(newPositions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment