Extract journey information.
436656
def _info(self) -> Optional[str]:
        """"""
        try:
            return str(html.unescape(self.journey.InfoTextList.InfoText.get("text")))
        except AttributeError:
            return None
123889
def get_routes(departure, dest, vehicle='vlakbus', time='', date=''):
    """"""

    def _get_leaf_element(table, path):
        """Returns leaf element's text in given path"""
        res = table.xpath(path + '/*[not(*)]')
        if res:
            return res[0].text
        return table.xpath(path + '/text()')[0]

    if time == '':
        time = datetime.datetime.now().strftime('%H:%M')

    if date == '':
        date = datetime.datetime.now().strftime('%d.%m.%Y')

    try:
        req = requests.get(CPSK_URL.format(vehicle),
                           params={'date': date, 'time': time, 'f': departure,
                                   't': dest, 'submit': 'true'})
    except:
        return False

    tree = html.fromstring(req.text)
    html_tables = tree.xpath('//div[@id="main-res-inner"]/table/tbody')
    routes = []

    for table in html_tables:
        drive = Drive()
        datalen = len(table.xpath('./tr'))

        prevdate = ''
        for i in range(1, datalen-1):
            line = Line()
            trf = './tr[' + str(i) + ']'
            trt = './tr[' + str(i+1) + ']'
            line.f = _get_leaf_element(table, trf + '/td[3]')
            line.t = _get_leaf_element(table, trt + '/td[3]')
            line.departure = _get_leaf_element(table, trf + '/td[5]')
            line.arrival = _get_leaf_element(table, trt + '/td[4]')
            line.vehicle = table.xpath(trf + '/td[7]/img[1]')[0] \
                                .get('title').replace('Autobus', 'Bus')
            if line.vehicle == 'Presun':
                line.walk_duration = table.xpath(trf + '/td[7]/text()')[0] \
                    .replace('Presun asi ', '')

            delay = table.xpath(trf + '/td[7]/div[1]/' +
                                'span[@class!="nodelay"]/text()')
            if delay and delay[0] is not u'Aktuálne bez meškania':
                mins = delay[0].replace(u'Aktuálne meškanie ', '') \
                               .replace(u' minúty', '') \
                               .replace(u' minútu', '') \
                               .replace(u' minút', '')

                minstr = 'minutes' if mins is not '1' else 'minute'

                line.delay = ' ({0} {1} delay)'.format(mins, minstr)

            platform = table.xpath(trf + '/td[6]/span[1]/text()')
            platform2 = table.xpath(trf + '/td[6]/table/tr[1]/' +
                                    'td[1]/span[1]/text()')
            if platform:
                line.platform = '[{0}]'.format(platform[0])
            elif platform2:
                line.platform = '[{0}]'.format(platform2[0])

            _date = table.xpath(trf + '/td[2]/text()')[0]
            if _date is not ' ':
                prevdate = _date
            line.date = prevdate

            drive.lines.append(line)

        drive.duration = table.xpath('./tr[' + str(datalen) +
                                     ']/td[3]/p/strong[1]/text()')[0]

        try:
            drive.distance = table.xpath('./tr[' + str(datalen) +
                                         ']/td[3]/p/strong[2]/text()')[0]
        except IndexError:
            drive.distance = 'Distance not known'

        routes.append(drive)

    return routes
413352
def ReadPathInfo(self, client_id, path_type, components, timestamp=None):
    """"""
    try:
      path_record = self.path_records[(client_id, path_type, components)]
      return path_record.GetPathInfo(timestamp=timestamp)
    except KeyError:
      raise db.UnknownPathError(
          client_id=client_id, path_type=path_type, components=components)
934833
def ImportTrips(self, trips_file):
    ""
    for trip_id, trip_starttime, line, strli, direction,  \
        stoptime_id, schedule_id, daytype_id, restriction_id,  \
        dest_station_id, dest_stop_id, trip_type in  \
        ReadCSV(trips_file,
            ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR',
             'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',
             'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):
      if trip_type != '1':
        print("skipping Trip ", trip_id, line, direction, \
              dest_station_id, trip_type)
        continue  # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other
      trip = Trip()
      #The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009
      # to prevent overwritingimported trips when we key them by trip.id
      # we should make trip.id unique, by combining trip_id and line
      trip.id = ("%s_%s") % (trip_id, line)
      trip.starttime = int(trip_starttime)
      trip.route = self.routes[line]
      dest_station = self.stations[dest_station_id]
      pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
      trip.pattern = self.patterns[pattern_id]
      trip.stoptimes = trip.pattern.stoptimes[stoptime_id]
      if restriction_id:
        service_id = u'VB%s.%s' % (schedule_id, restriction_id)
      else:
        service_id = u'C%s.%s' % (schedule_id, daytype_id)
      trip.service_id = service_id
      assert len(self.services[service_id]) > 0
      assert not trip.id in self.trips
      self.trips[trip.id] = trip
130255
def _get_result_paths(self, data):
        """"""
        result = {}
        result['FASTA'] = ResultPath(Path=self._get_seqs_outfile())
        result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile())
        return result
1190379
def fetch(destination):
    """"""
    with io.open(destination, mode="w", encoding="utf-8") as dest:
        for url in TLE_URLS:
            response = urlopen(url)
            dest.write(response.read().decode("utf-8"))
139061
def calc_all_routes_info(self, npaths=3, real_time=True, stop_at_bounds=False, time_delta=0):
        """"""

        routes = self.get_route(npaths, time_delta)
        results = {route['routeName']: self._add_up_route(route['results'], real_time=real_time, stop_at_bounds=stop_at_bounds) for route in routes}
        route_time = [route[0] for route in results.values()]
        route_distance = [route[1] for route in results.values()]
        self.log.info('Time %.2f - %.2f minutes, distance %.2f - %.2f km.', min(route_time), max(route_time), min(route_distance), max(route_distance))
        return results
121519
def _departure(self) -> datetime:
        """"""
        departure_time = datetime.strptime(
            self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M"
        ).time()
        if departure_time > (self.now - timedelta(hours=1)).time():
            return datetime.combine(self.now.date(), departure_time)
        return datetime.combine(self.now.date() + timedelta(days=1), departure_time)
1239225
def Extract_Checkpoints(self):
		'''
			
		'''

		# Make sure page is available
		if self.page is None:
			raise Exception("The HTML data was not fetched due to some reasons")

		# Check for invalid tracking number
		if 'Invalid number / data not currently available' in self.page:
			raise ValueError('Invalid number/data not currently available')

		# Checkpoints extraction begins here 
		
		soup = BeautifulSoup(self.page,'html.parser')
		
		# Assign the current status of the shipment - self.status

		current_status = soup.find('span',id='spnCurrentStatusValue').text.strip()
		if current_status == 'Supporting Document Returned to Shipper':	
			self.status = 'R'
		elif current_status == 'Delivered':
			self.status = 'C'
		else:											 # The shipment is in Transit
			self.status = 'T'

		# Get all rows of the Checkpoints table (no particular order)
		rows = soup.findAll('div',{'class':'fullWidth odd leftFloat bottomGreyBorder'})
		rows += soup.findAll('div',{'class':'fullWidth even leftFloat bottomGreyBorder'})

		for row in rows:
			# Get the data

			location = row.find('div',{'class':'leftFloat thirdWidth'}).string.strip()
			date_time = row.find('div',{'class':'leftFloat shipmentSummaryLabel'}).string.strip()
			status = row.find('div',{'class':'leftFloat shipmentHistoryActivityLabel'}).string.strip()

			# Clean it
			location = self.remove_non_ascii(location)
			date_time_format = "%d-%b-%Y %H:%M"
			date_time = parse(self.remove_non_ascii(date_time))
			status = self.remove_non_ascii(status)

			# Add it to the checkpoint list
			self.tracking_data.append({'status':status,'date':date_time,'location':location})

		self.tracking_data = sorted(self.tracking_data, key=lambda k: k['date'])
403329
def make_data():
    """"""
    I,d = multidict({1:80, 2:270, 3:250, 4:160, 5:180})            # demand
    J,M,f = multidict({1:[500,1000], 2:[500,1000], 3:[500,1000]}) # capacity, fixed costs
    c = {(1,1):4,  (1,2):6,  (1,3):9,    # transportation costs
         (2,1):5,  (2,2):4,  (2,3):7,
         (3,1):6,  (3,2):3,  (3,3):4,
         (4,1):8,  (4,2):5,  (4,3):3,
         (5,1):10, (5,2):8,  (5,3):4,
         }
    return I,J,d,M,f,c
327830
def trips_process_xml():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    xml_str = body.get('xml_str')
    tp = trips.process_xml(xml_str)
    return _stmts_from_proc(tp)
880033
def journey_options(origin:      str,
                    destination: str,
                    via:         t.Optional[str]=None,
                    before:      t.Optional[int]=None,
                    after:       t.Optional[int]=None,
                    time:        t.Optional[datetime]=None,
                    hsl:         t.Optional[bool]=None,
                    year_card:   t.Optional[bool]=None) -> (
                        snug.Query[t.List[Journey]]):
    """"""
    return snug.GET('treinplanner', params={
        'fromStation':     origin,
        'toStation':       destination,
        'viaStation':      via,
        'previousAdvices': before,
        'nextAdvices':     after,
        'dateTime':        time,
        'hslAllowed':      hsl,
        'yearCard':        year_card,
    })
280547
def extract(self, destination):
        """"""
        with zipfile.ZipFile(self.archive, 'r') as zip_ref:
            zip_ref.extractall(destination)
1282647
def get_known_transports():
    """"""
    if not hasattr(get_known_transports, "cache"):
        setattr(
            get_known_transports,
            "cache",
            {
                e.name: e.load()
                for e in pkg_resources.iter_entry_points("workflows.transport")
            },
        )
    return get_known_transports.cache.copy()
1373647
private RouteDoc extractDocInfo(RouteMeta routeMeta) {
        RouteDoc routeDoc = new RouteDoc();
        routeDoc.setGroup(routeMeta.getGroup());
        routeDoc.setPath(routeMeta.getPath());
        routeDoc.setDescription(routeMeta.getName());
        routeDoc.setType(routeMeta.getType().name().toLowerCase());
        routeDoc.setMark(routeMeta.getExtra());

        return routeDoc;
    }
123596
function extractTravelPlan(data) {
  let plans = []
  let getPlan = searchPlan => plans.find(plan => samePlan(plan, searchPlan))

  data.folders.forEach(folder => {
    let cents = folder.cents
    if (folder.cents === undefined) { return }
    let from = stationDataFromId(folder.departure_station_id, data)
    let to = stationDataFromId(folder.arrival_station_id, data)
    let departure = (new Date(folder.departure_date)).toISOString()
    let arrival = (new Date(folder.arrival_date)).toISOString()

    let tripId = folder.trip_ids[0]
    let trip = data.trips.find(trip => trip.id === tripId)
    let segments = trip.segment_ids.map(segmentId =>
      data.segments.find(segment => segment.id === segmentId)
    )
    let legs = segments.map(segment => ({
      from: stationDataFromId(segment.departure_station_id, data),
      to: stationDataFromId(segment.arrival_station_id, data),
      departure: (new Date(segment.departure_date)).toISOString(),
      arrival: (new Date(segment.arrival_date)).toISOString(),
    }))
    let searchPlan = {fares: [], legs}
    let plan = getPlan(searchPlan)

    if (plan === undefined) {
      plan = searchPlan
      plans.push(plan)

    } else if
      // If that price is already in the plan, no need to add to it.
      (plan.fares.find(fare => fare.price[0].cents === cents) !== undefined) {
      return
    }


    plan.fares.push({
      price: [{ cents: folder.cents, currency: folder.currency }],
      class: travelClass(folder.travel_class),
      flexibility: flexibility(folder.flexibility),
    })
  })
  return plans
}
958834
async def get_departures(self):
        """"""
        from .common import CommonFunctions
        common = CommonFunctions(self.loop, self.session)
        departures = []
        endpoint = '{}/StopVisit/GetDepartures/{}'.format(BASE_URL,
                                                          str(self.stopid))
        data = await common.api_call(endpoint)
        for entries in data or []:
            try:
                data = entries['MonitoredVehicleJourney']
                if self.destination is not None:
                    if data['DestinationName'] == self.destination:
                        data = entries['MonitoredVehicleJourney']
                        line = data['LineRef']
                        destinationname = data['DestinationName']
                        monitored = data['MonitoredCall']
                        time = monitored['ExpectedDepartureTime']
                        departures.append({"time": time,
                                           "line": line,
                                           "destination": destinationname})
                else:
                    data = entries['MonitoredVehicleJourney']
                    line = data['LineRef']
                    destinationname = data['DestinationName']
                    monitored = data['MonitoredCall']
                    time = monitored['ExpectedDepartureTime']
                    departures.append({"time": time,
                                       "line": line,
                                       "destination": destinationname})
            except (TypeError, KeyError, IndexError) as error:
                LOGGER.error('Error connecting to Ruter, %s', error)
        self._departures = await common.sort_data(departures, 'time')