id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
238,900 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.IsActiveOn | def IsActiveOn(self, date, date_object=None):
"""Test if this service period is active on a date.
Args:
date: a string of form "YYYYMMDD"
date_object: a date object representing the same date as date.
This parameter is optional, and present only for performance
reasons.
If the caller constructs the date string from a date object
that date object can be passed directly, thus avoiding the
costly conversion from string to date object.
Returns:
True iff this service is active on date.
"""
if date in self.date_exceptions:
exception_type, _ = self.date_exceptions[date]
if exception_type == self._EXCEPTION_TYPE_ADD:
return True
else:
return False
if (self.start_date and self.end_date and self.start_date <= date and
date <= self.end_date):
if date_object is None:
date_object = util.DateStringToDateObject(date)
return self.day_of_week[date_object.weekday()]
return False | python | def IsActiveOn(self, date, date_object=None):
if date in self.date_exceptions:
exception_type, _ = self.date_exceptions[date]
if exception_type == self._EXCEPTION_TYPE_ADD:
return True
else:
return False
if (self.start_date and self.end_date and self.start_date <= date and
date <= self.end_date):
if date_object is None:
date_object = util.DateStringToDateObject(date)
return self.day_of_week[date_object.weekday()]
return False | [
"def",
"IsActiveOn",
"(",
"self",
",",
"date",
",",
"date_object",
"=",
"None",
")",
":",
"if",
"date",
"in",
"self",
".",
"date_exceptions",
":",
"exception_type",
",",
"_",
"=",
"self",
".",
"date_exceptions",
"[",
"date",
"]",
"if",
"exception_type",
... | Test if this service period is active on a date.
Args:
date: a string of form "YYYYMMDD"
date_object: a date object representing the same date as date.
This parameter is optional, and present only for performance
reasons.
If the caller constructs the date string from a date object
that date object can be passed directly, thus avoiding the
costly conversion from string to date object.
Returns:
True iff this service is active on date. | [
"Test",
"if",
"this",
"service",
"period",
"is",
"active",
"on",
"a",
"date",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L192-L218 |
238,901 | google/transitfeed | transitfeed/serviceperiod.py | ServicePeriod.ActiveDates | def ActiveDates(self):
"""Return dates this service period is active as a list of "YYYYMMDD"."""
(earliest, latest) = self.GetDateRange()
if earliest is None:
return []
dates = []
date_it = util.DateStringToDateObject(earliest)
date_end = util.DateStringToDateObject(latest)
delta = datetime.timedelta(days=1)
while date_it <= date_end:
date_it_string = date_it.strftime("%Y%m%d")
if self.IsActiveOn(date_it_string, date_it):
dates.append(date_it_string)
date_it = date_it + delta
return dates | python | def ActiveDates(self):
(earliest, latest) = self.GetDateRange()
if earliest is None:
return []
dates = []
date_it = util.DateStringToDateObject(earliest)
date_end = util.DateStringToDateObject(latest)
delta = datetime.timedelta(days=1)
while date_it <= date_end:
date_it_string = date_it.strftime("%Y%m%d")
if self.IsActiveOn(date_it_string, date_it):
dates.append(date_it_string)
date_it = date_it + delta
return dates | [
"def",
"ActiveDates",
"(",
"self",
")",
":",
"(",
"earliest",
",",
"latest",
")",
"=",
"self",
".",
"GetDateRange",
"(",
")",
"if",
"earliest",
"is",
"None",
":",
"return",
"[",
"]",
"dates",
"=",
"[",
"]",
"date_it",
"=",
"util",
".",
"DateStringToD... | Return dates this service period is active as a list of "YYYYMMDD". | [
"Return",
"dates",
"this",
"service",
"period",
"is",
"active",
"as",
"a",
"list",
"of",
"YYYYMMDD",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L220-L234 |
238,902 | google/transitfeed | transitfeed/agency.py | Agency.Validate | def Validate(self, problems=default_problem_reporter):
"""Validate attribute values and this object's internal consistency.
Returns:
True iff all validation checks passed.
"""
found_problem = False
found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty(
self, self._REQUIRED_FIELD_NAMES, problems))
or found_problem)
found_problem = self.ValidateAgencyUrl(problems) or found_problem
found_problem = self.ValidateAgencyLang(problems) or found_problem
found_problem = self.ValidateAgencyTimezone(problems) or found_problem
found_problem = self.ValidateAgencyFareUrl(problems) or found_problem
found_problem = self.ValidateAgencyEmail(problems) or found_problem
return not found_problem | python | def Validate(self, problems=default_problem_reporter):
found_problem = False
found_problem = ((not util.ValidateRequiredFieldsAreNotEmpty(
self, self._REQUIRED_FIELD_NAMES, problems))
or found_problem)
found_problem = self.ValidateAgencyUrl(problems) or found_problem
found_problem = self.ValidateAgencyLang(problems) or found_problem
found_problem = self.ValidateAgencyTimezone(problems) or found_problem
found_problem = self.ValidateAgencyFareUrl(problems) or found_problem
found_problem = self.ValidateAgencyEmail(problems) or found_problem
return not found_problem | [
"def",
"Validate",
"(",
"self",
",",
"problems",
"=",
"default_problem_reporter",
")",
":",
"found_problem",
"=",
"False",
"found_problem",
"=",
"(",
"(",
"not",
"util",
".",
"ValidateRequiredFieldsAreNotEmpty",
"(",
"self",
",",
"self",
".",
"_REQUIRED_FIELD_NAME... | Validate attribute values and this object's internal consistency.
Returns:
True iff all validation checks passed. | [
"Validate",
"attribute",
"values",
"and",
"this",
"object",
"s",
"internal",
"consistency",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/agency.py#L88-L104 |
238,903 | google/transitfeed | misc/import_ch_zurich.py | ConvertCH1903 | def ConvertCH1903(x, y):
"Converts coordinates from the 1903 Swiss national grid system to WGS-84."
yb = (x - 600000.0) / 1e6;
xb = (y - 200000.0) / 1e6;
lam = 2.6779094 \
+ 4.728982 * yb \
+ 0.791484 * yb * xb \
+ 0.1306 * yb * xb * xb \
- 0.0436 * yb * yb * yb
phi = 16.9023892 \
+ 3.238372 * xb \
- 0.270978 * yb * yb \
- 0.002582 * xb * xb \
- 0.0447 * yb * yb * xb \
- 0.0140 * xb * xb * xb
return (phi * 100.0 / 36.0, lam * 100.0 / 36.0) | python | def ConvertCH1903(x, y):
"Converts coordinates from the 1903 Swiss national grid system to WGS-84."
yb = (x - 600000.0) / 1e6;
xb = (y - 200000.0) / 1e6;
lam = 2.6779094 \
+ 4.728982 * yb \
+ 0.791484 * yb * xb \
+ 0.1306 * yb * xb * xb \
- 0.0436 * yb * yb * yb
phi = 16.9023892 \
+ 3.238372 * xb \
- 0.270978 * yb * yb \
- 0.002582 * xb * xb \
- 0.0447 * yb * yb * xb \
- 0.0140 * xb * xb * xb
return (phi * 100.0 / 36.0, lam * 100.0 / 36.0) | [
"def",
"ConvertCH1903",
"(",
"x",
",",
"y",
")",
":",
"yb",
"=",
"(",
"x",
"-",
"600000.0",
")",
"/",
"1e6",
"xb",
"=",
"(",
"y",
"-",
"200000.0",
")",
"/",
"1e6",
"lam",
"=",
"2.6779094",
"+",
"4.728982",
"*",
"yb",
"+",
"0.791484",
"*",
"yb",... | Converts coordinates from the 1903 Swiss national grid system to WGS-84. | [
"Converts",
"coordinates",
"from",
"the",
"1903",
"Swiss",
"national",
"grid",
"system",
"to",
"WGS",
"-",
"84",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L96-L111 |
238,904 | google/transitfeed | misc/import_ch_zurich.py | EncodeForCSV | def EncodeForCSV(x):
"Encodes one value for CSV."
k = x.encode('utf-8')
if ',' in k or '"' in k:
return '"%s"' % k.replace('"', '""')
else:
return k | python | def EncodeForCSV(x):
"Encodes one value for CSV."
k = x.encode('utf-8')
if ',' in k or '"' in k:
return '"%s"' % k.replace('"', '""')
else:
return k | [
"def",
"EncodeForCSV",
"(",
"x",
")",
":",
"k",
"=",
"x",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"','",
"in",
"k",
"or",
"'\"'",
"in",
"k",
":",
"return",
"'\"%s\"'",
"%",
"k",
".",
"replace",
"(",
"'\"'",
",",
"'\"\"'",
")",
"else",
":",
"r... | Encodes one value for CSV. | [
"Encodes",
"one",
"value",
"for",
"CSV",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L114-L120 |
238,905 | google/transitfeed | misc/import_ch_zurich.py | WriteRow | def WriteRow(stream, values):
"Writes one row of comma-separated values to stream."
stream.write(','.join([EncodeForCSV(val) for val in values]))
stream.write('\n') | python | def WriteRow(stream, values):
"Writes one row of comma-separated values to stream."
stream.write(','.join([EncodeForCSV(val) for val in values]))
stream.write('\n') | [
"def",
"WriteRow",
"(",
"stream",
",",
"values",
")",
":",
"stream",
".",
"write",
"(",
"','",
".",
"join",
"(",
"[",
"EncodeForCSV",
"(",
"val",
")",
"for",
"val",
"in",
"values",
"]",
")",
")",
"stream",
".",
"write",
"(",
"'\\n'",
")"
] | Writes one row of comma-separated values to stream. | [
"Writes",
"one",
"row",
"of",
"comma",
"-",
"separated",
"values",
"to",
"stream",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L123-L126 |
238,906 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportStations | def ImportStations(self, station_file, adv_file):
"Imports the rec_ort.mdv file."
for id, name, x, y, uic_code in \
ReadCSV(station_file, ['ORT_NR', 'ORT_NAME',
'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):
station = Station()
station.id = id
station.position = self.coord_converter(float(x), float(y))
station.uic_code = ''
if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':
station.uic_code = uic_code
station.name, station.city = self.DemangleName(name)
station.country = 'CH'
station.url = 'http://fahrplan.zvv.ch/?to.0=' + \
urllib.quote(name.encode('iso-8859-1'))
station.advertised_lines = set()
self.stations[id] = station
for station_id, line_id in ReadCSV(adv_file, ['ORT_NR', 'LI_NR']):
if station_id in self.stations:
# Line ids in this file have leading zeroes, remove.
self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
else:
print("Warning, advertised lines file references " \
"unknown station, id " + station_id) | python | def ImportStations(self, station_file, adv_file):
"Imports the rec_ort.mdv file."
for id, name, x, y, uic_code in \
ReadCSV(station_file, ['ORT_NR', 'ORT_NAME',
'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):
station = Station()
station.id = id
station.position = self.coord_converter(float(x), float(y))
station.uic_code = ''
if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':
station.uic_code = uic_code
station.name, station.city = self.DemangleName(name)
station.country = 'CH'
station.url = 'http://fahrplan.zvv.ch/?to.0=' + \
urllib.quote(name.encode('iso-8859-1'))
station.advertised_lines = set()
self.stations[id] = station
for station_id, line_id in ReadCSV(adv_file, ['ORT_NR', 'LI_NR']):
if station_id in self.stations:
# Line ids in this file have leading zeroes, remove.
self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
else:
print("Warning, advertised lines file references " \
"unknown station, id " + station_id) | [
"def",
"ImportStations",
"(",
"self",
",",
"station_file",
",",
"adv_file",
")",
":",
"for",
"id",
",",
"name",
",",
"x",
",",
"y",
",",
"uic_code",
"in",
"ReadCSV",
"(",
"station_file",
",",
"[",
"'ORT_NR'",
",",
"'ORT_NAME'",
",",
"'ORT_POS_X'",
",",
... | Imports the rec_ort.mdv file. | [
"Imports",
"the",
"rec_ort",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L207-L230 |
238,907 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportRoutes | def ImportRoutes(self, s):
"Imports the rec_lin_ber.mdv file."
# the line id is really qualified with an area_id (BEREICH_NR), but the
# table of advertised lines does not include area. Fortunately, it seems
# that line ids are unique across all areas, so we can just throw it away.
for line_id, name in \
ReadCSV(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']):
route = Route()
route.id = line_id
route.name = name
route.color = "FFFFFF"
route.color_text = "000000"
if name in TRAM_LINES:
route.type = TYPE_TRAM
route.color = TRAM_LINES[name][0]
route.color_text = TRAM_LINES[name][1]
else:
route.type = TYPE_BUS
if route.name[0:1]=="N":
route.color = "000000"
route.color_text = "FFFF00"
self.routes[route.id] = route | python | def ImportRoutes(self, s):
"Imports the rec_lin_ber.mdv file."
# the line id is really qualified with an area_id (BEREICH_NR), but the
# table of advertised lines does not include area. Fortunately, it seems
# that line ids are unique across all areas, so we can just throw it away.
for line_id, name in \
ReadCSV(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']):
route = Route()
route.id = line_id
route.name = name
route.color = "FFFFFF"
route.color_text = "000000"
if name in TRAM_LINES:
route.type = TYPE_TRAM
route.color = TRAM_LINES[name][0]
route.color_text = TRAM_LINES[name][1]
else:
route.type = TYPE_BUS
if route.name[0:1]=="N":
route.color = "000000"
route.color_text = "FFFF00"
self.routes[route.id] = route | [
"def",
"ImportRoutes",
"(",
"self",
",",
"s",
")",
":",
"# the line id is really qualified with an area_id (BEREICH_NR), but the",
"# table of advertised lines does not include area. Fortunately, it seems",
"# that line ids are unique across all areas, so we can just throw it away.",
"for",
... | Imports the rec_lin_ber.mdv file. | [
"Imports",
"the",
"rec_lin_ber",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L232-L253 |
238,908 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportPatterns | def ImportPatterns(self, s):
"Imports the lid_verlauf.mdv file."
for line, strli, direction, seq, station_id in \
ReadCSV(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']):
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
pattern = self.patterns.get(pattern_id, None)
if not pattern:
pattern = Pattern()
pattern.id = pattern_id
pattern.stops = []
pattern.stoptimes = {}
self.patterns[pattern_id] = pattern
seq = int(seq) - 1
if len(pattern.stops) <= seq:
pattern.stops.extend([None] * (seq - len(pattern.stops) + 1))
pattern.stops[seq] = station_id | python | def ImportPatterns(self, s):
"Imports the lid_verlauf.mdv file."
for line, strli, direction, seq, station_id in \
ReadCSV(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']):
pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction)
pattern = self.patterns.get(pattern_id, None)
if not pattern:
pattern = Pattern()
pattern.id = pattern_id
pattern.stops = []
pattern.stoptimes = {}
self.patterns[pattern_id] = pattern
seq = int(seq) - 1
if len(pattern.stops) <= seq:
pattern.stops.extend([None] * (seq - len(pattern.stops) + 1))
pattern.stops[seq] = station_id | [
"def",
"ImportPatterns",
"(",
"self",
",",
"s",
")",
":",
"for",
"line",
",",
"strli",
",",
"direction",
",",
"seq",
",",
"station_id",
"in",
"ReadCSV",
"(",
"s",
",",
"[",
"'LI_NR'",
",",
"'STR_LI_VAR'",
",",
"'LI_RI_NR'",
",",
"'LI_LFD_NR'",
",",
"'O... | Imports the lid_verlauf.mdv file. | [
"Imports",
"the",
"lid_verlauf",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L255-L270 |
238,909 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportBoarding | def ImportBoarding(self, drop_off_file):
"Reads the bedverb.mdv file."
for trip_id, seq, code in \
ReadCSV(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']):
key = (trip_id, int(seq) - 1)
if code == 'A':
self.pickup_type[key] = '1' # '1' = no pick-up
elif code == 'E':
self.drop_off_type[key] = '1' # '1' = no drop-off
elif code == 'B' :
# 'B' just means that rider needs to push a button to have the driver
# stop. We don't encode this for now.
pass
else:
raise ValueError('Unexpected code in bedverb.mdv; '
'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) | python | def ImportBoarding(self, drop_off_file):
"Reads the bedverb.mdv file."
for trip_id, seq, code in \
ReadCSV(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']):
key = (trip_id, int(seq) - 1)
if code == 'A':
self.pickup_type[key] = '1' # '1' = no pick-up
elif code == 'E':
self.drop_off_type[key] = '1' # '1' = no drop-off
elif code == 'B' :
# 'B' just means that rider needs to push a button to have the driver
# stop. We don't encode this for now.
pass
else:
raise ValueError('Unexpected code in bedverb.mdv; '
'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) | [
"def",
"ImportBoarding",
"(",
"self",
",",
"drop_off_file",
")",
":",
"for",
"trip_id",
",",
"seq",
",",
"code",
"in",
"ReadCSV",
"(",
"drop_off_file",
",",
"[",
"'FRT_FID'",
",",
"'LI_LFD_NR'",
",",
"'BEDVERB_CODE'",
"]",
")",
":",
"key",
"=",
"(",
"tri... | Reads the bedverb.mdv file. | [
"Reads",
"the",
"bedverb",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L272-L287 |
238,910 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportTrafficRestrictions | def ImportTrafficRestrictions(self, restrictions_file):
"Reads the vb_regio.mdv file."
ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8]))
MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6])
for schedule, id, bitmask, start_date, end_date in \
ReadCSV(restrictions_file,
['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']):
id = u"VB%s.%s" % (schedule, id)
bitmask = bitmask.strip()
dates = {}
# This is ugly as hell, I know. I briefly explain what I do:
# 8 characters in the bitmask equal a month ( 8 * 4bits = 32, no month has
# more than 31 days, so it's ok).
# Then I check if the current day of the month is in the bitmask (by
# shifting the bit by x days and comparing it to the bitmask).
# If so I calculate back what year month and actual day I am in
# (very disgusting) and mark that date...
for i in range(MonthNr(end_date) - MonthNr(start_date)+1):
mask=int(bitmask[i*8:i*8+8], 16)
for d in range(32):
if 1 << d & mask:
year=int(start_date[0:4])+ ((int(start_date[4:6]) + i -1 )) / 12
month=((int(start_date[4:6]) + i-1 ) % 12) +1
day=d+1
cur_date = str(year)+("0"+str(month))[-2:]+("0"+str(day))[-2:]
dates[int(cur_date)] = 1
self.services[id] = dates.keys()
self.services[id].sort() | python | def ImportTrafficRestrictions(self, restrictions_file):
"Reads the vb_regio.mdv file."
ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8]))
MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6])
for schedule, id, bitmask, start_date, end_date in \
ReadCSV(restrictions_file,
['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']):
id = u"VB%s.%s" % (schedule, id)
bitmask = bitmask.strip()
dates = {}
# This is ugly as hell, I know. I briefly explain what I do:
# 8 characters in the bitmask equal a month ( 8 * 4bits = 32, no month has
# more than 31 days, so it's ok).
# Then I check if the current day of the month is in the bitmask (by
# shifting the bit by x days and comparing it to the bitmask).
# If so I calculate back what year month and actual day I am in
# (very disgusting) and mark that date...
for i in range(MonthNr(end_date) - MonthNr(start_date)+1):
mask=int(bitmask[i*8:i*8+8], 16)
for d in range(32):
if 1 << d & mask:
year=int(start_date[0:4])+ ((int(start_date[4:6]) + i -1 )) / 12
month=((int(start_date[4:6]) + i-1 ) % 12) +1
day=d+1
cur_date = str(year)+("0"+str(month))[-2:]+("0"+str(day))[-2:]
dates[int(cur_date)] = 1
self.services[id] = dates.keys()
self.services[id].sort() | [
"def",
"ImportTrafficRestrictions",
"(",
"self",
",",
"restrictions_file",
")",
":",
"ParseDate",
"=",
"lambda",
"x",
":",
"datetime",
".",
"date",
"(",
"int",
"(",
"x",
"[",
":",
"4",
"]",
")",
",",
"int",
"(",
"x",
"[",
"4",
":",
"6",
"]",
")",
... | Reads the vb_regio.mdv file. | [
"Reads",
"the",
"vb_regio",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L310-L338 |
238,911 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportStopTimes | def ImportStopTimes(self, stoptimes_file):
"Imports the lid_fahrzeitart.mdv file."
for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \
ReadCSV(stoptimes_file,
['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',
'FGR_NR', 'FZT_REL', 'HZEIT']):
pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]
stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])
seq = int(seq) - 1
drive_secs = int(drive_secs)
wait_secs = int(wait_secs)
assert len(stoptimes) == seq # fails if seq not in order
stoptimes.append((drive_secs, wait_secs)) | python | def ImportStopTimes(self, stoptimes_file):
"Imports the lid_fahrzeitart.mdv file."
for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \
ReadCSV(stoptimes_file,
['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR',
'FGR_NR', 'FZT_REL', 'HZEIT']):
pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)]
stoptimes = pattern.stoptimes.setdefault(stoptime_id, [])
seq = int(seq) - 1
drive_secs = int(drive_secs)
wait_secs = int(wait_secs)
assert len(stoptimes) == seq # fails if seq not in order
stoptimes.append((drive_secs, wait_secs)) | [
"def",
"ImportStopTimes",
"(",
"self",
",",
"stoptimes_file",
")",
":",
"for",
"line",
",",
"strli",
",",
"direction",
",",
"seq",
",",
"stoptime_id",
",",
"drive_secs",
",",
"wait_secs",
"in",
"ReadCSV",
"(",
"stoptimes_file",
",",
"[",
"'LI_NR'",
",",
"'... | Imports the lid_fahrzeitart.mdv file. | [
"Imports",
"the",
"lid_fahrzeitart",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L340-L352 |
238,912 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.ImportTrips | def ImportTrips(self, trips_file):
"Imports the rec_frt.mdv 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 | python | def ImportTrips(self, trips_file):
"Imports the rec_frt.mdv 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 | [
"def",
"ImportTrips",
"(",
"self",
",",
"trips_file",
")",
":",
"for",
"trip_id",
",",
"trip_starttime",
",",
"line",
",",
"strli",
",",
"direction",
",",
"stoptime_id",
",",
"schedule_id",
",",
"daytype_id",
",",
"restriction_id",
",",
"dest_station_id",
",",... | Imports the rec_frt.mdv file. | [
"Imports",
"the",
"rec_frt",
".",
"mdv",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L354-L385 |
238,913 | google/transitfeed | misc/import_ch_zurich.py | DivaImporter.Write | def Write(self, outpath):
"Writes a .zip file in Google Transit format."
out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED)
for filename, func in [('agency.txt', self.WriteAgency),
('calendar.txt', self.WriteCalendar),
('calendar_dates.txt', self.WriteCalendarDates),
('routes.txt', self.WriteRoutes),
('trips.txt', self.WriteTrips),
('stops.txt', self.WriteStations),
('stop_times.txt', self.WriteStopTimes)]:
s = cStringIO.StringIO()
func(s)
out.writestr(filename, s.getvalue())
out.close() | python | def Write(self, outpath):
"Writes a .zip file in Google Transit format."
out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED)
for filename, func in [('agency.txt', self.WriteAgency),
('calendar.txt', self.WriteCalendar),
('calendar_dates.txt', self.WriteCalendarDates),
('routes.txt', self.WriteRoutes),
('trips.txt', self.WriteTrips),
('stops.txt', self.WriteStations),
('stop_times.txt', self.WriteStopTimes)]:
s = cStringIO.StringIO()
func(s)
out.writestr(filename, s.getvalue())
out.close() | [
"def",
"Write",
"(",
"self",
",",
"outpath",
")",
":",
"out",
"=",
"zipfile",
".",
"ZipFile",
"(",
"outpath",
",",
"mode",
"=",
"\"w\"",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"filename",
",",
"func",
"in",
"[",
"(",
"'a... | Writes a .zip file in Google Transit format. | [
"Writes",
"a",
".",
"zip",
"file",
"in",
"Google",
"Transit",
"format",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/import_ch_zurich.py#L387-L400 |
238,914 | google/transitfeed | examples/table.py | TransposeTable | def TransposeTable(table):
"""Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]]
"""
transposed = []
rows = len(table)
cols = max(len(row) for row in table)
for x in range(cols):
transposed.append([])
for y in range(rows):
if x < len(table[y]):
transposed[x].append(table[y][x])
else:
transposed[x].append(None)
return transposed | python | def TransposeTable(table):
transposed = []
rows = len(table)
cols = max(len(row) for row in table)
for x in range(cols):
transposed.append([])
for y in range(rows):
if x < len(table[y]):
transposed[x].append(table[y][x])
else:
transposed[x].append(None)
return transposed | [
"def",
"TransposeTable",
"(",
"table",
")",
":",
"transposed",
"=",
"[",
"]",
"rows",
"=",
"len",
"(",
"table",
")",
"cols",
"=",
"max",
"(",
"len",
"(",
"row",
")",
"for",
"row",
"in",
"table",
")",
"for",
"x",
"in",
"range",
"(",
"cols",
")",
... | Transpose a list of lists, using None to extend all input lists to the
same length.
For example:
>>> TransposeTable(
[ [11, 12, 13],
[21, 22],
[31, 32, 33, 34]])
[ [11, 21, 31],
[12, 22, 32],
[13, None, 33],
[None, None, 34]] | [
"Transpose",
"a",
"list",
"of",
"lists",
"using",
"None",
"to",
"extend",
"all",
"input",
"lists",
"to",
"the",
"same",
"length",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/table.py#L65-L90 |
238,915 | google/transitfeed | transitfeed/util.py | CheckVersion | def CheckVersion(problems, latest_version=None):
"""
Check if there is a newer version of transitfeed available.
Args:
problems: if a new version is available, a NewVersionAvailable problem will
be added
latest_version: if specified, override the latest version read from the
project page
"""
if not latest_version:
timeout = 20
socket.setdefaulttimeout(timeout)
request = urllib2.Request(LATEST_RELEASE_VERSION_URL)
try:
response = urllib2.urlopen(request)
content = response.read()
m = re.search(r'version=(\d+\.\d+\.\d+)', content)
if m:
latest_version = m.group(1)
except urllib2.HTTPError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server: Reason: %s [%s].' %
(e.reason, e.code))
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
except urllib2.URLError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server. Reason: %s.' % e.reason)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
if not latest_version:
description = ('During the new-version check, we had trouble parsing the '
'contents of %s.' % LATEST_RELEASE_VERSION_URL)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
newest_version = _MaxVersion([latest_version, __version__])
if __version__ != newest_version:
problems.NewVersionAvailable(newest_version) | python | def CheckVersion(problems, latest_version=None):
if not latest_version:
timeout = 20
socket.setdefaulttimeout(timeout)
request = urllib2.Request(LATEST_RELEASE_VERSION_URL)
try:
response = urllib2.urlopen(request)
content = response.read()
m = re.search(r'version=(\d+\.\d+\.\d+)', content)
if m:
latest_version = m.group(1)
except urllib2.HTTPError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server: Reason: %s [%s].' %
(e.reason, e.code))
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
except urllib2.URLError as e:
description = ('During the new-version check, we failed to reach '
'transitfeed server. Reason: %s.' % e.reason)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
if not latest_version:
description = ('During the new-version check, we had trouble parsing the '
'contents of %s.' % LATEST_RELEASE_VERSION_URL)
problems.OtherProblem(
description=description, type=errors.TYPE_NOTICE)
return
newest_version = _MaxVersion([latest_version, __version__])
if __version__ != newest_version:
problems.NewVersionAvailable(newest_version) | [
"def",
"CheckVersion",
"(",
"problems",
",",
"latest_version",
"=",
"None",
")",
":",
"if",
"not",
"latest_version",
":",
"timeout",
"=",
"20",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"LATEST_R... | Check if there is a newer version of transitfeed available.
Args:
problems: if a new version is available, a NewVersionAvailable problem will
be added
latest_version: if specified, override the latest version read from the
project page | [
"Check",
"if",
"there",
"is",
"a",
"newer",
"version",
"of",
"transitfeed",
"available",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L180-L225 |
238,916 | google/transitfeed | transitfeed/util.py | EncodeUnicode | def EncodeUnicode(text):
"""
Optionally encode text and return it. The result should be safe to print.
"""
if type(text) == type(u''):
return text.encode(OUTPUT_ENCODING)
else:
return text | python | def EncodeUnicode(text):
if type(text) == type(u''):
return text.encode(OUTPUT_ENCODING)
else:
return text | [
"def",
"EncodeUnicode",
"(",
"text",
")",
":",
"if",
"type",
"(",
"text",
")",
"==",
"type",
"(",
"u''",
")",
":",
"return",
"text",
".",
"encode",
"(",
"OUTPUT_ENCODING",
")",
"else",
":",
"return",
"text"
] | Optionally encode text and return it. The result should be safe to print. | [
"Optionally",
"encode",
"text",
"and",
"return",
"it",
".",
"The",
"result",
"should",
"be",
"safe",
"to",
"print",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L238-L245 |
238,917 | google/transitfeed | transitfeed/util.py | ValidateYesNoUnknown | def ValidateYesNoUnknown(value, column_name=None, problems=None):
"""Validates a value "0" for uknown, "1" for yes, and "2" for no."""
if IsEmpty(value) or IsValidYesNoUnknown(value):
return True
else:
if problems:
problems.InvalidValue(column_name, value)
return False | python | def ValidateYesNoUnknown(value, column_name=None, problems=None):
if IsEmpty(value) or IsValidYesNoUnknown(value):
return True
else:
if problems:
problems.InvalidValue(column_name, value)
return False | [
"def",
"ValidateYesNoUnknown",
"(",
"value",
",",
"column_name",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"IsEmpty",
"(",
"value",
")",
"or",
"IsValidYesNoUnknown",
"(",
"value",
")",
":",
"return",
"True",
"else",
":",
"if",
"problems",
... | Validates a value "0" for uknown, "1" for yes, and "2" for no. | [
"Validates",
"a",
"value",
"0",
"for",
"uknown",
"1",
"for",
"yes",
"and",
"2",
"for",
"no",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L437-L444 |
238,918 | google/transitfeed | transitfeed/util.py | FindUniqueId | def FindUniqueId(dic):
"""Return a string not used as a key in the dictionary dic"""
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | python | def FindUniqueId(dic):
name = str(len(dic))
while name in dic:
# Use bigger numbers so it is obvious when an id is picked randomly.
name = str(random.randint(1000000, 999999999))
return name | [
"def",
"FindUniqueId",
"(",
"dic",
")",
":",
"name",
"=",
"str",
"(",
"len",
"(",
"dic",
")",
")",
"while",
"name",
"in",
"dic",
":",
"# Use bigger numbers so it is obvious when an id is picked randomly.",
"name",
"=",
"str",
"(",
"random",
".",
"randint",
"("... | Return a string not used as a key in the dictionary dic | [
"Return",
"a",
"string",
"not",
"used",
"as",
"a",
"key",
"in",
"the",
"dictionary",
"dic"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L449-L455 |
238,919 | google/transitfeed | transitfeed/util.py | DateStringToDateObject | def DateStringToDateObject(date_string):
"""Return a date object for a string "YYYYMMDD"."""
# If this becomes a bottleneck date objects could be cached
if re.match('^\d{8}$', date_string) == None:
return None
try:
return datetime.date(int(date_string[0:4]), int(date_string[4:6]),
int(date_string[6:8]))
except ValueError:
return None | python | def DateStringToDateObject(date_string):
# If this becomes a bottleneck date objects could be cached
if re.match('^\d{8}$', date_string) == None:
return None
try:
return datetime.date(int(date_string[0:4]), int(date_string[4:6]),
int(date_string[6:8]))
except ValueError:
return None | [
"def",
"DateStringToDateObject",
"(",
"date_string",
")",
":",
"# If this becomes a bottleneck date objects could be cached",
"if",
"re",
".",
"match",
"(",
"'^\\d{8}$'",
",",
"date_string",
")",
"==",
"None",
":",
"return",
"None",
"try",
":",
"return",
"datetime",
... | Return a date object for a string "YYYYMMDD". | [
"Return",
"a",
"date",
"object",
"for",
"a",
"string",
"YYYYMMDD",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L473-L482 |
238,920 | google/transitfeed | transitfeed/util.py | FloatStringToFloat | def FloatStringToFloat(float_string, problems=None):
"""Convert a float as a string to a float or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^[+-]?\d+(\.\d+)?$", float_string)
# Will raise TypeError if the string can't be parsed
parsed_value = float(float_string)
if "x" in float_string:
# This is needed because Python 2.4 does not complain about float("0x20").
# But it does complain about float("0b10"), so this should be enough.
raise ValueError()
if not match and problems is not None:
# Does not match the regex, but it's a float according to Python
problems.InvalidFloatValue(float_string)
return parsed_value | python | def FloatStringToFloat(float_string, problems=None):
# Will raise TypeError unless a string
match = re.match(r"^[+-]?\d+(\.\d+)?$", float_string)
# Will raise TypeError if the string can't be parsed
parsed_value = float(float_string)
if "x" in float_string:
# This is needed because Python 2.4 does not complain about float("0x20").
# But it does complain about float("0b10"), so this should be enough.
raise ValueError()
if not match and problems is not None:
# Does not match the regex, but it's a float according to Python
problems.InvalidFloatValue(float_string)
return parsed_value | [
"def",
"FloatStringToFloat",
"(",
"float_string",
",",
"problems",
"=",
"None",
")",
":",
"# Will raise TypeError unless a string",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^[+-]?\\d+(\\.\\d+)?$\"",
",",
"float_string",
")",
"# Will raise TypeError if the string can't be ... | Convert a float as a string to a float or raise an exception | [
"Convert",
"a",
"float",
"as",
"a",
"string",
"to",
"a",
"float",
"or",
"raise",
"an",
"exception"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L484-L499 |
238,921 | google/transitfeed | transitfeed/util.py | NonNegIntStringToInt | def NonNegIntStringToInt(int_string, problems=None):
"""Convert an non-negative integer string to an int or raise an exception"""
# Will raise TypeError unless a string
match = re.match(r"^(?:0|[1-9]\d*)$", int_string)
# Will raise ValueError if the string can't be parsed
parsed_value = int(int_string)
if parsed_value < 0:
raise ValueError()
elif not match and problems is not None:
# Does not match the regex, but it's an int according to Python
problems.InvalidNonNegativeIntegerValue(int_string)
return parsed_value | python | def NonNegIntStringToInt(int_string, problems=None):
# Will raise TypeError unless a string
match = re.match(r"^(?:0|[1-9]\d*)$", int_string)
# Will raise ValueError if the string can't be parsed
parsed_value = int(int_string)
if parsed_value < 0:
raise ValueError()
elif not match and problems is not None:
# Does not match the regex, but it's an int according to Python
problems.InvalidNonNegativeIntegerValue(int_string)
return parsed_value | [
"def",
"NonNegIntStringToInt",
"(",
"int_string",
",",
"problems",
"=",
"None",
")",
":",
"# Will raise TypeError unless a string",
"match",
"=",
"re",
".",
"match",
"(",
"r\"^(?:0|[1-9]\\d*)$\"",
",",
"int_string",
")",
"# Will raise ValueError if the string can't be parse... | Convert an non-negative integer string to an int or raise an exception | [
"Convert",
"an",
"non",
"-",
"negative",
"integer",
"string",
"to",
"an",
"int",
"or",
"raise",
"an",
"exception"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L501-L514 |
238,922 | google/transitfeed | transitfeed/util.py | ApproximateDistance | def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2):
"""Compute approximate distance between two points in meters. Assumes the
Earth is a sphere."""
# TODO: change to ellipsoid approximation, such as
# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/
lat1 = math.radians(degree_lat1)
lng1 = math.radians(degree_lng1)
lat2 = math.radians(degree_lat2)
lng2 = math.radians(degree_lng2)
dlat = math.sin(0.5 * (lat2 - lat1))
dlng = math.sin(0.5 * (lng2 - lng1))
x = dlat * dlat + dlng * dlng * math.cos(lat1) * math.cos(lat2)
return EARTH_RADIUS * (2 * math.atan2(math.sqrt(x),
math.sqrt(max(0.0, 1.0 - x)))) | python | def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2):
# TODO: change to ellipsoid approximation, such as
# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/
lat1 = math.radians(degree_lat1)
lng1 = math.radians(degree_lng1)
lat2 = math.radians(degree_lat2)
lng2 = math.radians(degree_lng2)
dlat = math.sin(0.5 * (lat2 - lat1))
dlng = math.sin(0.5 * (lng2 - lng1))
x = dlat * dlat + dlng * dlng * math.cos(lat1) * math.cos(lat2)
return EARTH_RADIUS * (2 * math.atan2(math.sqrt(x),
math.sqrt(max(0.0, 1.0 - x)))) | [
"def",
"ApproximateDistance",
"(",
"degree_lat1",
",",
"degree_lng1",
",",
"degree_lat2",
",",
"degree_lng2",
")",
":",
"# TODO: change to ellipsoid approximation, such as",
"# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/",
"lat1",
"=",
"math",
".",
"radians",
... | Compute approximate distance between two points in meters. Assumes the
Earth is a sphere. | [
"Compute",
"approximate",
"distance",
"between",
"two",
"points",
"in",
"meters",
".",
"Assumes",
"the",
"Earth",
"is",
"a",
"sphere",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L517-L530 |
238,923 | google/transitfeed | transitfeed/util.py | ApproximateDistanceBetweenStops | def ApproximateDistanceBetweenStops(stop1, stop2):
"""Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere."""
if (stop1.stop_lat is None or stop1.stop_lon is None or
stop2.stop_lat is None or stop2.stop_lon is None):
return None
return ApproximateDistance(stop1.stop_lat, stop1.stop_lon,
stop2.stop_lat, stop2.stop_lon) | python | def ApproximateDistanceBetweenStops(stop1, stop2):
if (stop1.stop_lat is None or stop1.stop_lon is None or
stop2.stop_lat is None or stop2.stop_lon is None):
return None
return ApproximateDistance(stop1.stop_lat, stop1.stop_lon,
stop2.stop_lat, stop2.stop_lon) | [
"def",
"ApproximateDistanceBetweenStops",
"(",
"stop1",
",",
"stop2",
")",
":",
"if",
"(",
"stop1",
".",
"stop_lat",
"is",
"None",
"or",
"stop1",
".",
"stop_lon",
"is",
"None",
"or",
"stop2",
".",
"stop_lat",
"is",
"None",
"or",
"stop2",
".",
"stop_lon",
... | Compute approximate distance between two stops in meters. Assumes the
Earth is a sphere. | [
"Compute",
"approximate",
"distance",
"between",
"two",
"stops",
"in",
"meters",
".",
"Assumes",
"the",
"Earth",
"is",
"a",
"sphere",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L532-L539 |
238,924 | google/transitfeed | transitfeed/util.py | CsvUnicodeWriter.writerow | def writerow(self, row):
"""Write row to the csv file. Any unicode strings in row are encoded as
utf-8."""
encoded_row = []
for s in row:
if isinstance(s, unicode):
encoded_row.append(s.encode("utf-8"))
else:
encoded_row.append(s)
try:
self.writer.writerow(encoded_row)
except Exception as e:
print('error writing %s as %s' % (row, encoded_row))
raise e | python | def writerow(self, row):
encoded_row = []
for s in row:
if isinstance(s, unicode):
encoded_row.append(s.encode("utf-8"))
else:
encoded_row.append(s)
try:
self.writer.writerow(encoded_row)
except Exception as e:
print('error writing %s as %s' % (row, encoded_row))
raise e | [
"def",
"writerow",
"(",
"self",
",",
"row",
")",
":",
"encoded_row",
"=",
"[",
"]",
"for",
"s",
"in",
"row",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"encoded_row",
".",
"append",
"(",
"s",
".",
"encode",
"(",
"\"utf-8\"",
")",
... | Write row to the csv file. Any unicode strings in row are encoded as
utf-8. | [
"Write",
"row",
"to",
"the",
"csv",
"file",
".",
"Any",
"unicode",
"strings",
"in",
"row",
"are",
"encoded",
"as",
"utf",
"-",
"8",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L549-L562 |
238,925 | google/transitfeed | transitfeed/util.py | EndOfLineChecker.next | def next(self):
"""Return next line without end of line marker or raise StopIteration."""
try:
next_line = next(self._f)
except StopIteration:
self._FinalCheck()
raise
self._line_number += 1
m_eol = re.search(r"[\x0a\x0d]*$", next_line)
if m_eol.group() == "\x0d\x0a":
self._crlf += 1
if self._crlf <= 5:
self._crlf_examples.append(self._line_number)
elif m_eol.group() == "\x0a":
self._lf += 1
if self._lf <= 5:
self._lf_examples.append(self._line_number)
elif m_eol.group() == "":
# Should only happen at the end of the file
try:
next(self._f)
raise RuntimeError("Unexpected row without new line sequence")
except StopIteration:
# Will be raised again when EndOfLineChecker.next() is next called
pass
else:
self._problems.InvalidLineEnd(
codecs.getencoder('string_escape')(m_eol.group())[0],
(self._name, self._line_number))
next_line_contents = next_line[0:m_eol.start()]
for seq, name in INVALID_LINE_SEPARATOR_UTF8.items():
if next_line_contents.find(seq) != -1:
self._problems.OtherProblem(
"Line contains %s" % name,
context=(self._name, self._line_number))
return next_line_contents | python | def next(self):
try:
next_line = next(self._f)
except StopIteration:
self._FinalCheck()
raise
self._line_number += 1
m_eol = re.search(r"[\x0a\x0d]*$", next_line)
if m_eol.group() == "\x0d\x0a":
self._crlf += 1
if self._crlf <= 5:
self._crlf_examples.append(self._line_number)
elif m_eol.group() == "\x0a":
self._lf += 1
if self._lf <= 5:
self._lf_examples.append(self._line_number)
elif m_eol.group() == "":
# Should only happen at the end of the file
try:
next(self._f)
raise RuntimeError("Unexpected row without new line sequence")
except StopIteration:
# Will be raised again when EndOfLineChecker.next() is next called
pass
else:
self._problems.InvalidLineEnd(
codecs.getencoder('string_escape')(m_eol.group())[0],
(self._name, self._line_number))
next_line_contents = next_line[0:m_eol.start()]
for seq, name in INVALID_LINE_SEPARATOR_UTF8.items():
if next_line_contents.find(seq) != -1:
self._problems.OtherProblem(
"Line contains %s" % name,
context=(self._name, self._line_number))
return next_line_contents | [
"def",
"next",
"(",
"self",
")",
":",
"try",
":",
"next_line",
"=",
"next",
"(",
"self",
".",
"_f",
")",
"except",
"StopIteration",
":",
"self",
".",
"_FinalCheck",
"(",
")",
"raise",
"self",
".",
"_line_number",
"+=",
"1",
"m_eol",
"=",
"re",
".",
... | Return next line without end of line marker or raise StopIteration. | [
"Return",
"next",
"line",
"without",
"end",
"of",
"line",
"marker",
"or",
"raise",
"StopIteration",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L610-L646 |
238,926 | google/transitfeed | upgrade_translations.py | read_first_available_value | def read_first_available_value(filename, field_name):
"""Reads the first assigned value of the given field in the CSV table.
"""
if not os.path.exists(filename):
return None
with open(filename, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
value = row.get(field_name)
if value:
return value
return None | python | def read_first_available_value(filename, field_name):
if not os.path.exists(filename):
return None
with open(filename, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
value = row.get(field_name)
if value:
return value
return None | [
"def",
"read_first_available_value",
"(",
"filename",
",",
"field_name",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"None",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"csvfile",
":",
"reade... | Reads the first assigned value of the given field in the CSV table. | [
"Reads",
"the",
"first",
"assigned",
"value",
"of",
"the",
"given",
"field",
"in",
"the",
"CSV",
"table",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L162-L173 |
238,927 | google/transitfeed | upgrade_translations.py | OldTranslations._find_feed_language | def _find_feed_language(self):
"""Find feed language based specified feed_info.txt or agency.txt.
"""
self.feed_language = (
read_first_available_value(
os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or
read_first_available_value(
os.path.join(self.src_dir, 'agency.txt'), 'agency_lang'))
if not self.feed_language:
raise Exception(
'Cannot find feed language in feed_info.txt and agency.txt')
print('\tfeed language: %s' % self.feed_language) | python | def _find_feed_language(self):
self.feed_language = (
read_first_available_value(
os.path.join(self.src_dir, 'feed_info.txt'), 'feed_lang') or
read_first_available_value(
os.path.join(self.src_dir, 'agency.txt'), 'agency_lang'))
if not self.feed_language:
raise Exception(
'Cannot find feed language in feed_info.txt and agency.txt')
print('\tfeed language: %s' % self.feed_language) | [
"def",
"_find_feed_language",
"(",
"self",
")",
":",
"self",
".",
"feed_language",
"=",
"(",
"read_first_available_value",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"src_dir",
",",
"'feed_info.txt'",
")",
",",
"'feed_lang'",
")",
"or",
"read_fir... | Find feed language based specified feed_info.txt or agency.txt. | [
"Find",
"feed",
"language",
"based",
"specified",
"feed_info",
".",
"txt",
"or",
"agency",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L196-L207 |
238,928 | google/transitfeed | upgrade_translations.py | OldTranslations._read_translations | def _read_translations(self):
"""Read from the old translations.txt.
"""
print('Reading original translations')
self.translations_map = {}
n_translations = 0
with open(os.path.join(self.src_dir, 'translations.txt'),
'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.translations_map.setdefault(
row['trans_id'], {})[row['lang']] = row['translation']
n_translations += 1
print('\ttotal original translations: %s' % n_translations) | python | def _read_translations(self):
print('Reading original translations')
self.translations_map = {}
n_translations = 0
with open(os.path.join(self.src_dir, 'translations.txt'),
'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
self.translations_map.setdefault(
row['trans_id'], {})[row['lang']] = row['translation']
n_translations += 1
print('\ttotal original translations: %s' % n_translations) | [
"def",
"_read_translations",
"(",
"self",
")",
":",
"print",
"(",
"'Reading original translations'",
")",
"self",
".",
"translations_map",
"=",
"{",
"}",
"n_translations",
"=",
"0",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"sr... | Read from the old translations.txt. | [
"Read",
"from",
"the",
"old",
"translations",
".",
"txt",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L209-L222 |
238,929 | google/transitfeed | upgrade_translations.py | OldTranslations._find_context_dependent_names | def _find_context_dependent_names(self):
"""Finds texts whose translation depends on context.
Example.
Here the word "Palacio" is translated from Spanish to English in
multiple ways. Feed language is es (Spanish).
trans_id,lang,translation
stop-name-1,es,Palacio
stop-name-1,en,Palace
headsign-1,es,Palacio
headsign-1,en,To Palace
"""
n_occurences_of_original = {}
for trans_id, translations in self.translations_map.items():
try:
original_name = translations[self.feed_language]
except KeyError:
raise Exception(
'No translation in feed language for %s, available: %s' %
(trans_id, translations))
n_occurences_of_original[original_name] = (
n_occurences_of_original.get(original_name, 0) +
1)
self.context_dependent_names = set(
name
for name, occur in n_occurences_of_original.items()
if occur > 1)
print('Total context-dependent translations: %d' %
len(self.context_dependent_names)) | python | def _find_context_dependent_names(self):
n_occurences_of_original = {}
for trans_id, translations in self.translations_map.items():
try:
original_name = translations[self.feed_language]
except KeyError:
raise Exception(
'No translation in feed language for %s, available: %s' %
(trans_id, translations))
n_occurences_of_original[original_name] = (
n_occurences_of_original.get(original_name, 0) +
1)
self.context_dependent_names = set(
name
for name, occur in n_occurences_of_original.items()
if occur > 1)
print('Total context-dependent translations: %d' %
len(self.context_dependent_names)) | [
"def",
"_find_context_dependent_names",
"(",
"self",
")",
":",
"n_occurences_of_original",
"=",
"{",
"}",
"for",
"trans_id",
",",
"translations",
"in",
"self",
".",
"translations_map",
".",
"items",
"(",
")",
":",
"try",
":",
"original_name",
"=",
"translations"... | Finds texts whose translation depends on context.
Example.
Here the word "Palacio" is translated from Spanish to English in
multiple ways. Feed language is es (Spanish).
trans_id,lang,translation
stop-name-1,es,Palacio
stop-name-1,en,Palace
headsign-1,es,Palacio
headsign-1,en,To Palace | [
"Finds",
"texts",
"whose",
"translation",
"depends",
"on",
"context",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L224-L254 |
238,930 | google/transitfeed | upgrade_translations.py | TranslationsConverter.convert_translations | def convert_translations(self, dest_dir):
"""
Converts translations to the new format and stores at dest_dir.
"""
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
total_translation_rows = 0
with open(os.path.join(dest_dir, 'translations.txt'),
'w+b') as out_file:
writer = csv.DictWriter(
out_file, fieldnames=NEW_TRANSLATIONS_FIELDS)
writer.writeheader()
for filename in sorted(os.listdir(self.src_dir)):
if not (filename.endswith('.txt') and
os.path.isfile(os.path.join(self.src_dir, filename))):
print('Skipping %s' % filename)
continue
table_name = filename[:-len('.txt')]
if table_name == 'translations':
continue
total_translation_rows += self._translate_table(
dest_dir, table_name, writer)
print('Total translation rows: %s' % total_translation_rows) | python | def convert_translations(self, dest_dir):
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
total_translation_rows = 0
with open(os.path.join(dest_dir, 'translations.txt'),
'w+b') as out_file:
writer = csv.DictWriter(
out_file, fieldnames=NEW_TRANSLATIONS_FIELDS)
writer.writeheader()
for filename in sorted(os.listdir(self.src_dir)):
if not (filename.endswith('.txt') and
os.path.isfile(os.path.join(self.src_dir, filename))):
print('Skipping %s' % filename)
continue
table_name = filename[:-len('.txt')]
if table_name == 'translations':
continue
total_translation_rows += self._translate_table(
dest_dir, table_name, writer)
print('Total translation rows: %s' % total_translation_rows) | [
"def",
"convert_translations",
"(",
"self",
",",
"dest_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dest_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"dest_dir",
")",
"total_translation_rows",
"=",
"0",
"with",
"open",
"(",
"os",
... | Converts translations to the new format and stores at dest_dir. | [
"Converts",
"translations",
"to",
"the",
"new",
"format",
"and",
"stores",
"at",
"dest_dir",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L264-L286 |
238,931 | google/transitfeed | upgrade_translations.py | TranslationsConverter._translate_table | def _translate_table(self, dest_dir, table_name, translations_writer):
"""
Converts translations to the new format for a single table.
"""
in_filename = os.path.join(self.src_dir, '%s.txt' % table_name)
if not os.path.exists(in_filename):
raise Exception('No %s' % table_name)
out_filename = os.path.join(dest_dir, '%s.txt' % table_name)
with open(in_filename, 'rb') as in_file:
reader = csv.DictReader(in_file)
if not reader.fieldnames or not any_translatable_field(
reader.fieldnames):
print('Copying %s with no translatable columns' % table_name)
shutil.copy(in_filename, out_filename)
return 0
table_translator = TableTranslator(
table_name, reader.fieldnames, self.old_translations,
translations_writer)
with open(out_filename, 'w+b') as out_file:
writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
writer.writerow(table_translator.translate_row(row))
table_translator.write_for_field_values()
print('\ttranslation rows: %s' %
table_translator.total_translation_rows)
return table_translator.total_translation_rows | python | def _translate_table(self, dest_dir, table_name, translations_writer):
in_filename = os.path.join(self.src_dir, '%s.txt' % table_name)
if not os.path.exists(in_filename):
raise Exception('No %s' % table_name)
out_filename = os.path.join(dest_dir, '%s.txt' % table_name)
with open(in_filename, 'rb') as in_file:
reader = csv.DictReader(in_file)
if not reader.fieldnames or not any_translatable_field(
reader.fieldnames):
print('Copying %s with no translatable columns' % table_name)
shutil.copy(in_filename, out_filename)
return 0
table_translator = TableTranslator(
table_name, reader.fieldnames, self.old_translations,
translations_writer)
with open(out_filename, 'w+b') as out_file:
writer = csv.DictWriter(out_file, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
writer.writerow(table_translator.translate_row(row))
table_translator.write_for_field_values()
print('\ttranslation rows: %s' %
table_translator.total_translation_rows)
return table_translator.total_translation_rows | [
"def",
"_translate_table",
"(",
"self",
",",
"dest_dir",
",",
"table_name",
",",
"translations_writer",
")",
":",
"in_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"src_dir",
",",
"'%s.txt'",
"%",
"table_name",
")",
"if",
"not",
"os",
... | Converts translations to the new format for a single table. | [
"Converts",
"translations",
"to",
"the",
"new",
"format",
"for",
"a",
"single",
"table",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/upgrade_translations.py#L288-L316 |
238,932 | google/transitfeed | transitfeed/loader.py | Loader._DetermineFormat | def _DetermineFormat(self):
"""Determines whether the feed is in a form that we understand, and
if so, returns True."""
if self._zip:
# If zip was passed to __init__ then path isn't used
assert not self._path
return True
if not isinstance(self._path, basestring) and hasattr(self._path, 'read'):
# A file-like object, used for testing with a StringIO file
self._zip = zipfile.ZipFile(self._path, mode='r')
return True
if not os.path.exists(self._path):
self._problems.FeedNotFound(self._path)
return False
if self._path.endswith('.zip'):
try:
self._zip = zipfile.ZipFile(self._path, mode='r')
except IOError: # self._path is a directory
pass
except zipfile.BadZipfile:
self._problems.UnknownFormat(self._path)
return False
if not self._zip and not os.path.isdir(self._path):
self._problems.UnknownFormat(self._path)
return False
return True | python | def _DetermineFormat(self):
if self._zip:
# If zip was passed to __init__ then path isn't used
assert not self._path
return True
if not isinstance(self._path, basestring) and hasattr(self._path, 'read'):
# A file-like object, used for testing with a StringIO file
self._zip = zipfile.ZipFile(self._path, mode='r')
return True
if not os.path.exists(self._path):
self._problems.FeedNotFound(self._path)
return False
if self._path.endswith('.zip'):
try:
self._zip = zipfile.ZipFile(self._path, mode='r')
except IOError: # self._path is a directory
pass
except zipfile.BadZipfile:
self._problems.UnknownFormat(self._path)
return False
if not self._zip and not os.path.isdir(self._path):
self._problems.UnknownFormat(self._path)
return False
return True | [
"def",
"_DetermineFormat",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip",
":",
"# If zip was passed to __init__ then path isn't used",
"assert",
"not",
"self",
".",
"_path",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_path",
",",
"basestr... | Determines whether the feed is in a form that we understand, and
if so, returns True. | [
"Determines",
"whether",
"the",
"feed",
"is",
"in",
"a",
"form",
"that",
"we",
"understand",
"and",
"if",
"so",
"returns",
"True",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L69-L99 |
238,933 | google/transitfeed | transitfeed/loader.py | Loader._GetFileNames | def _GetFileNames(self):
"""Returns a list of file names in the feed."""
if self._zip:
return self._zip.namelist()
else:
return os.listdir(self._path) | python | def _GetFileNames(self):
if self._zip:
return self._zip.namelist()
else:
return os.listdir(self._path) | [
"def",
"_GetFileNames",
"(",
"self",
")",
":",
"if",
"self",
".",
"_zip",
":",
"return",
"self",
".",
"_zip",
".",
"namelist",
"(",
")",
"else",
":",
"return",
"os",
".",
"listdir",
"(",
"self",
".",
"_path",
")"
] | Returns a list of file names in the feed. | [
"Returns",
"a",
"list",
"of",
"file",
"names",
"in",
"the",
"feed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L101-L106 |
238,934 | google/transitfeed | transitfeed/loader.py | Loader._GetUtf8Contents | def _GetUtf8Contents(self, file_name):
"""Check for errors in file_name and return a string for csv reader."""
contents = self._FileContents(file_name)
if not contents: # Missing file
return
# Check for errors that will prevent csv.reader from working
if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,
codecs.BOM_UTF16_LE):
self._problems.FileFormat("appears to be encoded in utf-16", (file_name, ))
# Convert and continue, so we can find more errors
contents = codecs.getdecoder('utf-16')(contents)[0].encode('utf-8')
null_index = contents.find('\0')
if null_index != -1:
# It is easier to get some surrounding text than calculate the exact
# row_num
m = re.search(r'.{,20}\0.{,20}', contents, re.DOTALL)
self._problems.FileFormat(
"contains a null in text \"%s\" at byte %d" %
(codecs.getencoder('string_escape')(m.group()), null_index + 1),
(file_name, ))
return
# strip out any UTF-8 Byte Order Marker (otherwise it'll be
# treated as part of the first column name, causing a mis-parse)
contents = contents.lstrip(codecs.BOM_UTF8)
return contents | python | def _GetUtf8Contents(self, file_name):
contents = self._FileContents(file_name)
if not contents: # Missing file
return
# Check for errors that will prevent csv.reader from working
if len(contents) >= 2 and contents[0:2] in (codecs.BOM_UTF16_BE,
codecs.BOM_UTF16_LE):
self._problems.FileFormat("appears to be encoded in utf-16", (file_name, ))
# Convert and continue, so we can find more errors
contents = codecs.getdecoder('utf-16')(contents)[0].encode('utf-8')
null_index = contents.find('\0')
if null_index != -1:
# It is easier to get some surrounding text than calculate the exact
# row_num
m = re.search(r'.{,20}\0.{,20}', contents, re.DOTALL)
self._problems.FileFormat(
"contains a null in text \"%s\" at byte %d" %
(codecs.getencoder('string_escape')(m.group()), null_index + 1),
(file_name, ))
return
# strip out any UTF-8 Byte Order Marker (otherwise it'll be
# treated as part of the first column name, causing a mis-parse)
contents = contents.lstrip(codecs.BOM_UTF8)
return contents | [
"def",
"_GetUtf8Contents",
"(",
"self",
",",
"file_name",
")",
":",
"contents",
"=",
"self",
".",
"_FileContents",
"(",
"file_name",
")",
"if",
"not",
"contents",
":",
"# Missing file",
"return",
"# Check for errors that will prevent csv.reader from working",
"if",
"l... | Check for errors in file_name and return a string for csv reader. | [
"Check",
"for",
"errors",
"in",
"file_name",
"and",
"return",
"a",
"string",
"for",
"csv",
"reader",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L118-L145 |
238,935 | google/transitfeed | transitfeed/loader.py | Loader._HasFile | def _HasFile(self, file_name):
"""Returns True if there's a file in the current feed with the
given file_name in the current feed."""
if self._zip:
return file_name in self._zip.namelist()
else:
file_path = os.path.join(self._path, file_name)
return os.path.exists(file_path) and os.path.isfile(file_path) | python | def _HasFile(self, file_name):
if self._zip:
return file_name in self._zip.namelist()
else:
file_path = os.path.join(self._path, file_name)
return os.path.exists(file_path) and os.path.isfile(file_path) | [
"def",
"_HasFile",
"(",
"self",
",",
"file_name",
")",
":",
"if",
"self",
".",
"_zip",
":",
"return",
"file_name",
"in",
"self",
".",
"_zip",
".",
"namelist",
"(",
")",
"else",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
"."... | Returns True if there's a file in the current feed with the
given file_name in the current feed. | [
"Returns",
"True",
"if",
"there",
"s",
"a",
"file",
"in",
"the",
"current",
"feed",
"with",
"the",
"given",
"file_name",
"in",
"the",
"current",
"feed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/loader.py#L375-L382 |
238,936 | google/transitfeed | transitfeed/route.py | Route.AddTrip | def AddTrip(self, schedule=None, headsign=None, service_period=None,
trip_id=None):
"""Add a trip to this route.
Args:
schedule: a Schedule object which will hold the new trip or None to use
the schedule of this route.
headsign: headsign of the trip as a string
service_period: a ServicePeriod object or None to use
schedule.GetDefaultServicePeriod()
trip_id: optional trip_id for the new trip
Returns:
a new Trip object
"""
if schedule is None:
assert self._schedule is not None
schedule = self._schedule
if trip_id is None:
trip_id = util.FindUniqueId(schedule.trips)
if service_period is None:
service_period = schedule.GetDefaultServicePeriod()
trip_class = self.GetGtfsFactory().Trip
trip_obj = trip_class(route=self, headsign=headsign,
service_period=service_period, trip_id=trip_id)
schedule.AddTripObject(trip_obj)
return trip_obj | python | def AddTrip(self, schedule=None, headsign=None, service_period=None,
trip_id=None):
if schedule is None:
assert self._schedule is not None
schedule = self._schedule
if trip_id is None:
trip_id = util.FindUniqueId(schedule.trips)
if service_period is None:
service_period = schedule.GetDefaultServicePeriod()
trip_class = self.GetGtfsFactory().Trip
trip_obj = trip_class(route=self, headsign=headsign,
service_period=service_period, trip_id=trip_id)
schedule.AddTripObject(trip_obj)
return trip_obj | [
"def",
"AddTrip",
"(",
"self",
",",
"schedule",
"=",
"None",
",",
"headsign",
"=",
"None",
",",
"service_period",
"=",
"None",
",",
"trip_id",
"=",
"None",
")",
":",
"if",
"schedule",
"is",
"None",
":",
"assert",
"self",
".",
"_schedule",
"is",
"not",
... | Add a trip to this route.
Args:
schedule: a Schedule object which will hold the new trip or None to use
the schedule of this route.
headsign: headsign of the trip as a string
service_period: a ServicePeriod object or None to use
schedule.GetDefaultServicePeriod()
trip_id: optional trip_id for the new trip
Returns:
a new Trip object | [
"Add",
"a",
"trip",
"to",
"this",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/route.py#L69-L95 |
238,937 | google/transitfeed | transitfeed/route.py | Route.GetPatternIdTripDict | def GetPatternIdTripDict(self):
"""Return a dictionary that maps pattern_id to a list of Trip objects."""
d = {}
for t in self._trips:
d.setdefault(t.pattern_id, []).append(t)
return d | python | def GetPatternIdTripDict(self):
d = {}
for t in self._trips:
d.setdefault(t.pattern_id, []).append(t)
return d | [
"def",
"GetPatternIdTripDict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"t",
"in",
"self",
".",
"_trips",
":",
"d",
".",
"setdefault",
"(",
"t",
".",
"pattern_id",
",",
"[",
"]",
")",
".",
"append",
"(",
"t",
")",
"return",
"d"
] | Return a dictionary that maps pattern_id to a list of Trip objects. | [
"Return",
"a",
"dictionary",
"that",
"maps",
"pattern_id",
"to",
"a",
"list",
"of",
"Trip",
"objects",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/route.py#L113-L118 |
238,938 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.GetGtfsClassByFileName | def GetGtfsClassByFileName(self, filename):
"""Returns the transitfeed class corresponding to a GTFS file.
Args:
filename: The filename whose class is to be returned
Raises:
NonStandardMapping if the specified filename has more than one
corresponding class
"""
if filename not in self._file_mapping:
return None
mapping = self._file_mapping[filename]
class_list = mapping['classes']
if len(class_list) > 1:
raise problems.NonStandardMapping(filename)
else:
return self._class_mapping[class_list[0]] | python | def GetGtfsClassByFileName(self, filename):
if filename not in self._file_mapping:
return None
mapping = self._file_mapping[filename]
class_list = mapping['classes']
if len(class_list) > 1:
raise problems.NonStandardMapping(filename)
else:
return self._class_mapping[class_list[0]] | [
"def",
"GetGtfsClassByFileName",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"return",
"None",
"mapping",
"=",
"self",
".",
"_file_mapping",
"[",
"filename",
"]",
"class_list",
"=",
"mapping",
"["... | Returns the transitfeed class corresponding to a GTFS file.
Args:
filename: The filename whose class is to be returned
Raises:
NonStandardMapping if the specified filename has more than one
corresponding class | [
"Returns",
"the",
"transitfeed",
"class",
"corresponding",
"to",
"a",
"GTFS",
"file",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L108-L125 |
238,939 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.GetLoadingOrder | def GetLoadingOrder(self):
"""Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load"""
result = {}
for filename, mapping in self._file_mapping.iteritems():
loading_order = mapping['loading_order']
if loading_order is not None:
result[loading_order] = filename
return list(result[key] for key in sorted(result)) | python | def GetLoadingOrder(self):
result = {}
for filename, mapping in self._file_mapping.iteritems():
loading_order = mapping['loading_order']
if loading_order is not None:
result[loading_order] = filename
return list(result[key] for key in sorted(result)) | [
"def",
"GetLoadingOrder",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"filename",
",",
"mapping",
"in",
"self",
".",
"_file_mapping",
".",
"iteritems",
"(",
")",
":",
"loading_order",
"=",
"mapping",
"[",
"'loading_order'",
"]",
"if",
"loading_o... | Returns a list of filenames sorted by loading order.
Only includes files that Loader's standardized loading knows how to load | [
"Returns",
"a",
"list",
"of",
"filenames",
"sorted",
"by",
"loading",
"order",
".",
"Only",
"includes",
"files",
"that",
"Loader",
"s",
"standardized",
"loading",
"knows",
"how",
"to",
"load"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L127-L135 |
238,940 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.IsFileRequired | def IsFileRequired(self, filename):
"""Returns true if a file is required by GTFS, false otherwise.
Unknown files are, by definition, not required"""
if filename not in self._file_mapping:
return False
mapping = self._file_mapping[filename]
return mapping['required'] | python | def IsFileRequired(self, filename):
if filename not in self._file_mapping:
return False
mapping = self._file_mapping[filename]
return mapping['required'] | [
"def",
"IsFileRequired",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"return",
"False",
"mapping",
"=",
"self",
".",
"_file_mapping",
"[",
"filename",
"]",
"return",
"mapping",
"[",
"'required'",
... | Returns true if a file is required by GTFS, false otherwise.
Unknown files are, by definition, not required | [
"Returns",
"true",
"if",
"a",
"file",
"is",
"required",
"by",
"GTFS",
"false",
"otherwise",
".",
"Unknown",
"files",
"are",
"by",
"definition",
"not",
"required"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L137-L143 |
238,941 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.AddMapping | def AddMapping(self, filename, new_mapping):
"""Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the mapping
InvalidMapping if not all required fields are present
"""
for field in self._REQUIRED_MAPPING_FIELDS:
if field not in new_mapping:
raise problems.InvalidMapping(field)
if filename in self.GetKnownFilenames():
raise problems.DuplicateMapping(filename)
self._file_mapping[filename] = new_mapping | python | def AddMapping(self, filename, new_mapping):
for field in self._REQUIRED_MAPPING_FIELDS:
if field not in new_mapping:
raise problems.InvalidMapping(field)
if filename in self.GetKnownFilenames():
raise problems.DuplicateMapping(filename)
self._file_mapping[filename] = new_mapping | [
"def",
"AddMapping",
"(",
"self",
",",
"filename",
",",
"new_mapping",
")",
":",
"for",
"field",
"in",
"self",
".",
"_REQUIRED_MAPPING_FIELDS",
":",
"if",
"field",
"not",
"in",
"new_mapping",
":",
"raise",
"problems",
".",
"InvalidMapping",
"(",
"field",
")"... | Adds an entry to the list of known filenames.
Args:
filename: The filename whose mapping is being added.
new_mapping: A dictionary with the mapping to add. Must contain all
fields in _REQUIRED_MAPPING_FIELDS.
Raises:
DuplicateMapping if the filename already exists in the mapping
InvalidMapping if not all required fields are present | [
"Adds",
"an",
"entry",
"to",
"the",
"list",
"of",
"known",
"filenames",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L158-L174 |
238,942 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.UpdateMapping | def UpdateMapping(self, filename, mapping_update):
"""Updates an entry in the list of known filenames.
An entry is identified by its filename.
Args:
filename: The filename whose mapping is to be updated
mapping_update: A dictionary containing the fields to update and their
new values.
Raises:
InexistentMapping if the filename does not exist in the mapping
"""
if filename not in self._file_mapping:
raise problems.NonexistentMapping(filename)
mapping = self._file_mapping[filename]
mapping.update(mapping_update) | python | def UpdateMapping(self, filename, mapping_update):
if filename not in self._file_mapping:
raise problems.NonexistentMapping(filename)
mapping = self._file_mapping[filename]
mapping.update(mapping_update) | [
"def",
"UpdateMapping",
"(",
"self",
",",
"filename",
",",
"mapping_update",
")",
":",
"if",
"filename",
"not",
"in",
"self",
".",
"_file_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"filename",
")",
"mapping",
"=",
"self",
".",
"_file... | Updates an entry in the list of known filenames.
An entry is identified by its filename.
Args:
filename: The filename whose mapping is to be updated
mapping_update: A dictionary containing the fields to update and their
new values.
Raises:
InexistentMapping if the filename does not exist in the mapping | [
"Updates",
"an",
"entry",
"in",
"the",
"list",
"of",
"known",
"filenames",
".",
"An",
"entry",
"is",
"identified",
"by",
"its",
"filename",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L176-L190 |
238,943 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.AddClass | def AddClass(self, class_name, gtfs_class):
"""Adds an entry to the list of known classes.
Args:
class_name: A string with name through which gtfs_class is to be made
accessible.
gtfs_class: The class to be added.
Raises:
DuplicateMapping if class_name is already present in the class mapping.
"""
if class_name in self._class_mapping:
raise problems.DuplicateMapping(class_name)
self._class_mapping[class_name] = gtfs_class | python | def AddClass(self, class_name, gtfs_class):
if class_name in self._class_mapping:
raise problems.DuplicateMapping(class_name)
self._class_mapping[class_name] = gtfs_class | [
"def",
"AddClass",
"(",
"self",
",",
"class_name",
",",
"gtfs_class",
")",
":",
"if",
"class_name",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"DuplicateMapping",
"(",
"class_name",
")",
"self",
".",
"_class_mapping",
"[",
"class_name"... | Adds an entry to the list of known classes.
Args:
class_name: A string with name through which gtfs_class is to be made
accessible.
gtfs_class: The class to be added.
Raises:
DuplicateMapping if class_name is already present in the class mapping. | [
"Adds",
"an",
"entry",
"to",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L192-L204 |
238,944 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.UpdateClass | def UpdateClass(self, class_name, gtfs_class):
"""Updates an entry in the list of known classes.
Args:
class_name: A string with the class name that is to be updated.
gtfs_class: The new class
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
self._class_mapping[class_name] = gtfs_class | python | def UpdateClass(self, class_name, gtfs_class):
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
self._class_mapping[class_name] = gtfs_class | [
"def",
"UpdateClass",
"(",
"self",
",",
"class_name",
",",
"gtfs_class",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"class_name",
")",
"self",
".",
"_class_mapping",
"[",
... | Updates an entry in the list of known classes.
Args:
class_name: A string with the class name that is to be updated.
gtfs_class: The new class
Raises:
NonexistentMapping if there is no class with the specified class_name. | [
"Updates",
"an",
"entry",
"in",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L206-L217 |
238,945 | google/transitfeed | transitfeed/gtfsfactory.py | GtfsFactory.RemoveClass | def RemoveClass(self, class_name):
"""Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name.
"""
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
del self._class_mapping[class_name] | python | def RemoveClass(self, class_name):
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
del self._class_mapping[class_name] | [
"def",
"RemoveClass",
"(",
"self",
",",
"class_name",
")",
":",
"if",
"class_name",
"not",
"in",
"self",
".",
"_class_mapping",
":",
"raise",
"problems",
".",
"NonexistentMapping",
"(",
"class_name",
")",
"del",
"self",
".",
"_class_mapping",
"[",
"class_name"... | Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name. | [
"Removes",
"an",
"entry",
"from",
"the",
"list",
"of",
"known",
"classes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/gtfsfactory.py#L219-L229 |
238,946 | google/transitfeed | kmlparser.py | KmlParser.Parse | def Parse(self, filename, feed):
"""
Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.
Args:
filename - kml file name
feed - an instance of Schedule class to be updated
"""
dom = minidom.parse(filename)
self.ParseDom(dom, feed) | python | def Parse(self, filename, feed):
dom = minidom.parse(filename)
self.ParseDom(dom, feed) | [
"def",
"Parse",
"(",
"self",
",",
"filename",
",",
"feed",
")",
":",
"dom",
"=",
"minidom",
".",
"parse",
"(",
"filename",
")",
"self",
".",
"ParseDom",
"(",
"dom",
",",
"feed",
")"
] | Reads the kml file, parses it and updated the Google transit feed
object with the extracted information.
Args:
filename - kml file name
feed - an instance of Schedule class to be updated | [
"Reads",
"the",
"kml",
"file",
"parses",
"it",
"and",
"updated",
"the",
"Google",
"transit",
"feed",
"object",
"with",
"the",
"extracted",
"information",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlparser.py#L61-L71 |
238,947 | google/transitfeed | kmlparser.py | KmlParser.ParseDom | def ParseDom(self, dom, feed):
"""
Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated
"""
shape_num = 0
for node in dom.getElementsByTagName('Placemark'):
p = self.ParsePlacemark(node)
if p.IsPoint():
(lon, lat) = p.coordinates[0]
m = self.stopNameRe.search(p.name)
feed.AddStop(lat, lon, m.group(1))
elif p.IsLine():
self.ConvertPlacemarkToShape(p, feed) | python | def ParseDom(self, dom, feed):
shape_num = 0
for node in dom.getElementsByTagName('Placemark'):
p = self.ParsePlacemark(node)
if p.IsPoint():
(lon, lat) = p.coordinates[0]
m = self.stopNameRe.search(p.name)
feed.AddStop(lat, lon, m.group(1))
elif p.IsLine():
self.ConvertPlacemarkToShape(p, feed) | [
"def",
"ParseDom",
"(",
"self",
",",
"dom",
",",
"feed",
")",
":",
"shape_num",
"=",
"0",
"for",
"node",
"in",
"dom",
".",
"getElementsByTagName",
"(",
"'Placemark'",
")",
":",
"p",
"=",
"self",
".",
"ParsePlacemark",
"(",
"node",
")",
"if",
"p",
"."... | Parses the given kml dom tree and updates the Google transit feed object.
Args:
dom - kml dom tree
feed - an instance of Schedule class to be updated | [
"Parses",
"the",
"given",
"kml",
"dom",
"tree",
"and",
"updates",
"the",
"Google",
"transit",
"feed",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlparser.py#L73-L89 |
238,948 | google/transitfeed | examples/google_random_queries.py | Distance | def Distance(lat0, lng0, lat1, lng1):
"""
Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Approximate geodesic distance function (Haversine Formula) assuming
a perfect sphere of radius 6367 km (see "What are some algorithms
for calculating the distance between 2 points?" in the GIS Faq at
http://www.census.gov/geo/www/faq-index.html). The approximate
radius is adequate for our needs here, but a more sophisticated
geodesic function should be used if greater accuracy is required
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq).
"""
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat*0.5)
b = math.sin(dlng*0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c | python | def Distance(lat0, lng0, lat1, lng1):
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat*0.5)
b = math.sin(dlng*0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c | [
"def",
"Distance",
"(",
"lat0",
",",
"lng0",
",",
"lat1",
",",
"lng1",
")",
":",
"deg2rad",
"=",
"math",
".",
"pi",
"/",
"180.0",
"lat0",
"=",
"lat0",
"*",
"deg2rad",
"lng0",
"=",
"lng0",
"*",
"deg2rad",
"lat1",
"=",
"lat1",
"*",
"deg2rad",
"lng1",... | Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Approximate geodesic distance function (Haversine Formula) assuming
a perfect sphere of radius 6367 km (see "What are some algorithms
for calculating the distance between 2 points?" in the GIS Faq at
http://www.census.gov/geo/www/faq-index.html). The approximate
radius is adequate for our needs here, but a more sophisticated
geodesic function should be used if greater accuracy is required
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq). | [
"Compute",
"the",
"geodesic",
"distance",
"in",
"meters",
"between",
"two",
"points",
"on",
"the",
"surface",
"of",
"the",
"Earth",
".",
"The",
"latitude",
"and",
"longitude",
"angles",
"are",
"in",
"degrees",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L40-L66 |
238,949 | google/transitfeed | examples/google_random_queries.py | AddNoiseToLatLng | def AddNoiseToLatLng(lat, lng):
"""Add up to 500m of error to each coordinate of lat, lng."""
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1))) | python | def AddNoiseToLatLng(lat, lng):
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1))) | [
"def",
"AddNoiseToLatLng",
"(",
"lat",
",",
"lng",
")",
":",
"m_per_tenth_lat",
"=",
"Distance",
"(",
"lat",
",",
"lng",
",",
"lat",
"+",
"0.1",
",",
"lng",
")",
"m_per_tenth_lng",
"=",
"Distance",
"(",
"lat",
",",
"lng",
",",
"lat",
",",
"lng",
"+",... | Add up to 500m of error to each coordinate of lat, lng. | [
"Add",
"up",
"to",
"500m",
"of",
"error",
"to",
"each",
"coordinate",
"of",
"lat",
"lng",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L69-L76 |
238,950 | google/transitfeed | examples/google_random_queries.py | GetRandomDatetime | def GetRandomDatetime():
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0) | python | def GetRandomDatetime():
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0) | [
"def",
"GetRandomDatetime",
"(",
")",
":",
"seconds_offset",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
")",
"dt",
"=",
"datetime",
".",
"today",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"seconds_offse... | Return a datetime in the next week. | [
"Return",
"a",
"datetime",
"in",
"the",
"next",
"week",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L87-L91 |
238,951 | google/transitfeed | examples/google_random_queries.py | LatLngsToGoogleLink | def LatLngsToGoogleLink(source, destination):
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime()) | python | def LatLngsToGoogleLink(source, destination):
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime()) | [
"def",
"LatLngsToGoogleLink",
"(",
"source",
",",
"destination",
")",
":",
"dt",
"=",
"GetRandomDatetime",
"(",
")",
"return",
"\"<a href='%s'>from:%s to:%s on %s</a>\"",
"%",
"(",
"LatLngsToGoogleUrl",
"(",
"source",
",",
"destination",
",",
"dt",
")",
",",
"Form... | Return a string "<a ..." for a trip at a random time. | [
"Return",
"a",
"string",
"<a",
"...",
"for",
"a",
"trip",
"at",
"a",
"random",
"time",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L113-L119 |
238,952 | google/transitfeed | examples/google_random_queries.py | ParentAndBaseName | def ParentAndBaseName(path):
"""Given a path return only the parent name and file name as a string."""
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename) | python | def ParentAndBaseName(path):
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename) | [
"def",
"ParentAndBaseName",
"(",
"path",
")",
":",
"dirname",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"dirname",
"=",
"dirname",
".",
"rstrip",
"(",
"os",
".",
"path",
".",
"sep",
")",
"if",
"os",
".",
"path",
".",
... | Given a path return only the parent name and file name as a string. | [
"Given",
"a",
"path",
"return",
"only",
"the",
"parent",
"name",
"and",
"file",
"name",
"as",
"a",
"string",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L181-L188 |
238,953 | google/transitfeed | misc/sql_loop.py | LoadFile | def LoadFile(f, table_name, conn):
"""Import lines from f as new table in db with cursor c."""
reader = csv.reader(f)
header = next(reader)
columns = []
for n in header:
n = n.replace(' ', '')
n = n.replace('-', '_')
columns.append(n)
create_columns = []
column_types = {}
for n in columns:
if n in column_types:
create_columns.append("%s %s" % (n, column_types[n]))
else:
create_columns.append("%s INTEGER" % (n))
c = conn.cursor()
try:
c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
except sqlite.OperationalError:
# Likely table exists
print("table %s already exists?" % (table_name))
for create_column in create_columns:
try:
c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
except sqlite.OperationalError:
# Likely it already exists
print("column %s already exists in %s?" % (create_column, table_name))
placeholders = ",".join(["?"] * len(columns))
insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)
#c.execute("BEGIN TRANSACTION;")
for row in reader:
if row:
if len(row) < len(columns):
row.extend([None] * (len(columns) - len(row)))
c.execute(insert_values, row)
#c.execute("END TRANSACTION;")
conn.commit() | python | def LoadFile(f, table_name, conn):
reader = csv.reader(f)
header = next(reader)
columns = []
for n in header:
n = n.replace(' ', '')
n = n.replace('-', '_')
columns.append(n)
create_columns = []
column_types = {}
for n in columns:
if n in column_types:
create_columns.append("%s %s" % (n, column_types[n]))
else:
create_columns.append("%s INTEGER" % (n))
c = conn.cursor()
try:
c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns)))
except sqlite.OperationalError:
# Likely table exists
print("table %s already exists?" % (table_name))
for create_column in create_columns:
try:
c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column))
except sqlite.OperationalError:
# Likely it already exists
print("column %s already exists in %s?" % (create_column, table_name))
placeholders = ",".join(["?"] * len(columns))
insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders)
#c.execute("BEGIN TRANSACTION;")
for row in reader:
if row:
if len(row) < len(columns):
row.extend([None] * (len(columns) - len(row)))
c.execute(insert_values, row)
#c.execute("END TRANSACTION;")
conn.commit() | [
"def",
"LoadFile",
"(",
"f",
",",
"table_name",
",",
"conn",
")",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"header",
"=",
"next",
"(",
"reader",
")",
"columns",
"=",
"[",
"]",
"for",
"n",
"in",
"header",
":",
"n",
"=",
"n",
".",... | Import lines from f as new table in db with cursor c. | [
"Import",
"lines",
"from",
"f",
"as",
"new",
"table",
"in",
"db",
"with",
"cursor",
"c",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/sql_loop.py#L81-L123 |
238,954 | google/transitfeed | shape_importer.py | PrintColumns | def PrintColumns(shapefile):
"""
Print the columns of layer 0 of the shapefile to the screen.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
if len(layer) == 0:
raise ShapeImporterError("Layer 0 has no elements!")
feature = layer.GetFeature(0)
print("%d features" % feature.GetFieldCount())
for j in range(0, feature.GetFieldCount()):
print('--' + feature.GetFieldDefnRef(j).GetName() + \
': ' + feature.GetFieldAsString(j)) | python | def PrintColumns(shapefile):
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
if len(layer) == 0:
raise ShapeImporterError("Layer 0 has no elements!")
feature = layer.GetFeature(0)
print("%d features" % feature.GetFieldCount())
for j in range(0, feature.GetFieldCount()):
print('--' + feature.GetFieldDefnRef(j).GetName() + \
': ' + feature.GetFieldAsString(j)) | [
"def",
"PrintColumns",
"(",
"shapefile",
")",
":",
"ds",
"=",
"ogr",
".",
"Open",
"(",
"shapefile",
")",
"layer",
"=",
"ds",
".",
"GetLayer",
"(",
"0",
")",
"if",
"len",
"(",
"layer",
")",
"==",
"0",
":",
"raise",
"ShapeImporterError",
"(",
"\"Layer ... | Print the columns of layer 0 of the shapefile to the screen. | [
"Print",
"the",
"columns",
"of",
"layer",
"0",
"of",
"the",
"shapefile",
"to",
"the",
"screen",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L42-L55 |
238,955 | google/transitfeed | shape_importer.py | AddShapefile | def AddShapefile(shapefile, graph, key_cols):
"""
Adds shapes found in the given shape filename to the given polyline
graph object.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
for i in range(0, len(layer)):
feature = layer.GetFeature(i)
geometry = feature.GetGeometryRef()
if key_cols:
key_list = []
for col in key_cols:
key_list.append(str(feature.GetField(col)))
shape_id = '-'.join(key_list)
else:
shape_id = '%s-%d' % (shapefile, i)
poly = shapelib.Poly(name=shape_id)
for j in range(0, geometry.GetPointCount()):
(lat, lng) = (round(geometry.GetY(j), 15), round(geometry.GetX(j), 15))
poly.AddPoint(shapelib.Point.FromLatLng(lat, lng))
graph.AddPoly(poly)
return graph | python | def AddShapefile(shapefile, graph, key_cols):
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
for i in range(0, len(layer)):
feature = layer.GetFeature(i)
geometry = feature.GetGeometryRef()
if key_cols:
key_list = []
for col in key_cols:
key_list.append(str(feature.GetField(col)))
shape_id = '-'.join(key_list)
else:
shape_id = '%s-%d' % (shapefile, i)
poly = shapelib.Poly(name=shape_id)
for j in range(0, geometry.GetPointCount()):
(lat, lng) = (round(geometry.GetY(j), 15), round(geometry.GetX(j), 15))
poly.AddPoint(shapelib.Point.FromLatLng(lat, lng))
graph.AddPoly(poly)
return graph | [
"def",
"AddShapefile",
"(",
"shapefile",
",",
"graph",
",",
"key_cols",
")",
":",
"ds",
"=",
"ogr",
".",
"Open",
"(",
"shapefile",
")",
"layer",
"=",
"ds",
".",
"GetLayer",
"(",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"lay... | Adds shapes found in the given shape filename to the given polyline
graph object. | [
"Adds",
"shapes",
"found",
"in",
"the",
"given",
"shape",
"filename",
"to",
"the",
"given",
"polyline",
"graph",
"object",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L58-L85 |
238,956 | google/transitfeed | shape_importer.py | GetMatchingShape | def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):
"""
Tries to find a matching shape for the given pattern Poly object,
trip, and set of possibly matching Polys from which to choose a match.
"""
if len(matches) == 0:
print ('No matching shape found within max-distance %d for trip %s '
% (max_distance, trip.trip_id))
return None
if verbosity >= 1:
for match in matches:
print("match: size %d" % match.GetNumPoints())
scores = [(pattern_poly.GreedyPolyMatchDist(match), match)
for match in matches]
scores.sort()
if scores[0][0] > max_distance:
print ('No matching shape found within max-distance %d for trip %s '
'(min score was %f)'
% (max_distance, trip.trip_id, scores[0][0]))
return None
return scores[0][1] | python | def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):
if len(matches) == 0:
print ('No matching shape found within max-distance %d for trip %s '
% (max_distance, trip.trip_id))
return None
if verbosity >= 1:
for match in matches:
print("match: size %d" % match.GetNumPoints())
scores = [(pattern_poly.GreedyPolyMatchDist(match), match)
for match in matches]
scores.sort()
if scores[0][0] > max_distance:
print ('No matching shape found within max-distance %d for trip %s '
'(min score was %f)'
% (max_distance, trip.trip_id, scores[0][0]))
return None
return scores[0][1] | [
"def",
"GetMatchingShape",
"(",
"pattern_poly",
",",
"trip",
",",
"matches",
",",
"max_distance",
",",
"verbosity",
"=",
"0",
")",
":",
"if",
"len",
"(",
"matches",
")",
"==",
"0",
":",
"print",
"(",
"'No matching shape found within max-distance %d for trip %s '",... | Tries to find a matching shape for the given pattern Poly object,
trip, and set of possibly matching Polys from which to choose a match. | [
"Tries",
"to",
"find",
"a",
"matching",
"shape",
"for",
"the",
"given",
"pattern",
"Poly",
"object",
"trip",
"and",
"set",
"of",
"possibly",
"matching",
"Polys",
"from",
"which",
"to",
"choose",
"a",
"match",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L88-L112 |
238,957 | google/transitfeed | shape_importer.py | AddExtraShapes | def AddExtraShapes(extra_shapes_txt, graph):
"""
Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files.
"""
print("Adding extra shapes from %s" % extra_shapes_txt)
try:
tmpdir = tempfile.mkdtemp()
shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt'))
loader = transitfeed.ShapeLoader(tmpdir)
schedule = loader.Load()
for shape in schedule.GetShapeList():
print("Adding extra shape: %s" % shape.shape_id)
graph.AddPoly(ShapeToPoly(shape))
finally:
if tmpdir:
shutil.rmtree(tmpdir) | python | def AddExtraShapes(extra_shapes_txt, graph):
print("Adding extra shapes from %s" % extra_shapes_txt)
try:
tmpdir = tempfile.mkdtemp()
shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt'))
loader = transitfeed.ShapeLoader(tmpdir)
schedule = loader.Load()
for shape in schedule.GetShapeList():
print("Adding extra shape: %s" % shape.shape_id)
graph.AddPoly(ShapeToPoly(shape))
finally:
if tmpdir:
shutil.rmtree(tmpdir) | [
"def",
"AddExtraShapes",
"(",
"extra_shapes_txt",
",",
"graph",
")",
":",
"print",
"(",
"\"Adding extra shapes from %s\"",
"%",
"extra_shapes_txt",
")",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"shutil",
".",
"copy",
"(",
"extra_shapes_tx... | Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files. | [
"Add",
"extra",
"shapes",
"into",
"our",
"input",
"set",
"by",
"parsing",
"them",
"out",
"of",
"a",
"GTFS",
"-",
"formatted",
"shapes",
".",
"txt",
"file",
".",
"Useful",
"for",
"manually",
"adding",
"lines",
"to",
"a",
"shape",
"file",
"since",
"it",
... | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/shape_importer.py#L114-L132 |
238,958 | google/transitfeed | merge.py | ApproximateDistanceBetweenPoints | def ApproximateDistanceBetweenPoints(pa, pb):
"""Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the second (lat, lon) point tuple
Returns:
The distance as a float in metres.
"""
alat, alon = pa
blat, blon = pb
sa = transitfeed.Stop(lat=alat, lng=alon)
sb = transitfeed.Stop(lat=blat, lng=blon)
return transitfeed.ApproximateDistanceBetweenStops(sa, sb) | python | def ApproximateDistanceBetweenPoints(pa, pb):
alat, alon = pa
blat, blon = pb
sa = transitfeed.Stop(lat=alat, lng=alon)
sb = transitfeed.Stop(lat=blat, lng=blon)
return transitfeed.ApproximateDistanceBetweenStops(sa, sb) | [
"def",
"ApproximateDistanceBetweenPoints",
"(",
"pa",
",",
"pb",
")",
":",
"alat",
",",
"alon",
"=",
"pa",
"blat",
",",
"blon",
"=",
"pb",
"sa",
"=",
"transitfeed",
".",
"Stop",
"(",
"lat",
"=",
"alat",
",",
"lng",
"=",
"alon",
")",
"sb",
"=",
"tra... | Finds the distance between two points on the Earth's surface.
This is an approximate distance based on assuming that the Earth is a sphere.
The points are specified by their lattitude and longitude.
Args:
pa: the first (lat, lon) point tuple
pb: the second (lat, lon) point tuple
Returns:
The distance as a float in metres. | [
"Finds",
"the",
"distance",
"between",
"two",
"points",
"on",
"the",
"Earth",
"s",
"surface",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L63-L80 |
238,959 | google/transitfeed | merge.py | LoadWithoutErrors | def LoadWithoutErrors(path, memory_db):
""""Return a Schedule object loaded from path; sys.exit for any error."""
accumulator = transitfeed.ExceptionProblemAccumulator()
loading_problem_handler = MergeProblemReporter(accumulator)
try:
schedule = transitfeed.Loader(path,
memory_db=memory_db,
problems=loading_problem_handler,
extra_validation=True).Load()
except transitfeed.ExceptionWithContext as e:
print((
"\n\nFeeds to merge must load without any errors.\n"
"While loading %s the following error was found:\n%s\n%s\n" %
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
sys.exit(1)
return schedule | python | def LoadWithoutErrors(path, memory_db):
"accumulator = transitfeed.ExceptionProblemAccumulator()
loading_problem_handler = MergeProblemReporter(accumulator)
try:
schedule = transitfeed.Loader(path,
memory_db=memory_db,
problems=loading_problem_handler,
extra_validation=True).Load()
except transitfeed.ExceptionWithContext as e:
print((
"\n\nFeeds to merge must load without any errors.\n"
"While loading %s the following error was found:\n%s\n%s\n" %
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
sys.exit(1)
return schedule | [
"def",
"LoadWithoutErrors",
"(",
"path",
",",
"memory_db",
")",
":",
"accumulator",
"=",
"transitfeed",
".",
"ExceptionProblemAccumulator",
"(",
")",
"loading_problem_handler",
"=",
"MergeProblemReporter",
"(",
"accumulator",
")",
"try",
":",
"schedule",
"=",
"trans... | Return a Schedule object loaded from path; sys.exit for any error. | [
"Return",
"a",
"Schedule",
"object",
"loaded",
"from",
"path",
";",
"sys",
".",
"exit",
"for",
"any",
"error",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L353-L368 |
238,960 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateStatsTable | def _GenerateStatsTable(self, feed_merger):
"""Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string.
"""
rows = []
rows.append('<tr><th class="header"/><th class="header">Merged</th>'
'<th class="header">Copied from old feed</th>'
'<th class="header">Copied from new feed</th></tr>')
for merger in feed_merger.GetMergerList():
stats = merger.GetMergeStats()
if stats is None:
continue
merged, not_merged_a, not_merged_b = stats
rows.append('<tr><th class="header">%s</th>'
'<td class="header">%d</td>'
'<td class="header">%d</td>'
'<td class="header">%d</td></tr>' %
(merger.DATASET_NAME, merged, not_merged_a, not_merged_b))
return '<table>%s</table>' % '\n'.join(rows) | python | def _GenerateStatsTable(self, feed_merger):
rows = []
rows.append('<tr><th class="header"/><th class="header">Merged</th>'
'<th class="header">Copied from old feed</th>'
'<th class="header">Copied from new feed</th></tr>')
for merger in feed_merger.GetMergerList():
stats = merger.GetMergeStats()
if stats is None:
continue
merged, not_merged_a, not_merged_b = stats
rows.append('<tr><th class="header">%s</th>'
'<td class="header">%d</td>'
'<td class="header">%d</td>'
'<td class="header">%d</td></tr>' %
(merger.DATASET_NAME, merged, not_merged_a, not_merged_b))
return '<table>%s</table>' % '\n'.join(rows) | [
"def",
"_GenerateStatsTable",
"(",
"self",
",",
"feed_merger",
")",
":",
"rows",
"=",
"[",
"]",
"rows",
".",
"append",
"(",
"'<tr><th class=\"header\"/><th class=\"header\">Merged</th>'",
"'<th class=\"header\">Copied from old feed</th>'",
"'<th class=\"header\">Copied from new f... | Generate an HTML table of merge statistics.
Args:
feed_merger: The FeedMerger instance.
Returns:
The generated HTML as a string. | [
"Generate",
"an",
"HTML",
"table",
"of",
"merge",
"statistics",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L193-L216 |
238,961 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateSection | def _GenerateSection(self, problem_type):
"""Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string.
"""
if problem_type == transitfeed.TYPE_WARNING:
dataset_problems = self._dataset_warnings
heading = 'Warnings'
else:
dataset_problems = self._dataset_errors
heading = 'Errors'
if not dataset_problems:
return ''
prefix = '<h2 class="issueHeader">%s:</h2>' % heading
dataset_sections = []
for dataset_merger, problems in dataset_problems.items():
dataset_sections.append('<h3>%s</h3><ol>%s</ol>' % (
dataset_merger.FILE_NAME, '\n'.join(problems)))
body = '\n'.join(dataset_sections)
return prefix + body | python | def _GenerateSection(self, problem_type):
if problem_type == transitfeed.TYPE_WARNING:
dataset_problems = self._dataset_warnings
heading = 'Warnings'
else:
dataset_problems = self._dataset_errors
heading = 'Errors'
if not dataset_problems:
return ''
prefix = '<h2 class="issueHeader">%s:</h2>' % heading
dataset_sections = []
for dataset_merger, problems in dataset_problems.items():
dataset_sections.append('<h3>%s</h3><ol>%s</ol>' % (
dataset_merger.FILE_NAME, '\n'.join(problems)))
body = '\n'.join(dataset_sections)
return prefix + body | [
"def",
"_GenerateSection",
"(",
"self",
",",
"problem_type",
")",
":",
"if",
"problem_type",
"==",
"transitfeed",
".",
"TYPE_WARNING",
":",
"dataset_problems",
"=",
"self",
".",
"_dataset_warnings",
"heading",
"=",
"'Warnings'",
"else",
":",
"dataset_problems",
"=... | Generate a listing of the given type of problems.
Args:
problem_type: The type of problem. This is one of the problem type
constants from transitfeed.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"listing",
"of",
"the",
"given",
"type",
"of",
"problems",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L218-L244 |
238,962 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateSummary | def _GenerateSummary(self):
"""Generate a summary of the warnings and errors.
Returns:
The generated HTML as a string.
"""
items = []
if self._notices:
items.append('notices: %d' % self._notice_count)
if self._dataset_errors:
items.append('errors: %d' % self._error_count)
if self._dataset_warnings:
items.append('warnings: %d' % self._warning_count)
if items:
return '<p><span class="fail">%s</span></p>' % '<br>'.join(items)
else:
return '<p><span class="pass">feeds merged successfully</span></p>' | python | def _GenerateSummary(self):
items = []
if self._notices:
items.append('notices: %d' % self._notice_count)
if self._dataset_errors:
items.append('errors: %d' % self._error_count)
if self._dataset_warnings:
items.append('warnings: %d' % self._warning_count)
if items:
return '<p><span class="fail">%s</span></p>' % '<br>'.join(items)
else:
return '<p><span class="pass">feeds merged successfully</span></p>' | [
"def",
"_GenerateSummary",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"if",
"self",
".",
"_notices",
":",
"items",
".",
"append",
"(",
"'notices: %d'",
"%",
"self",
".",
"_notice_count",
")",
"if",
"self",
".",
"_dataset_errors",
":",
"items",
".",
... | Generate a summary of the warnings and errors.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"summary",
"of",
"the",
"warnings",
"and",
"errors",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L246-L263 |
238,963 | google/transitfeed | merge.py | HTMLProblemAccumulator._GenerateNotices | def _GenerateNotices(self):
"""Generate a summary of any notices.
Returns:
The generated HTML as a string.
"""
items = []
for e in self._notices:
d = e.GetDictToFormat()
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
items.append('<li class="notice">%s</li>' %
e.FormatProblem(d).replace('\n', '<br>'))
if items:
return '<h2>Notices:</h2>\n<ul>%s</ul>\n' % '\n'.join(items)
else:
return '' | python | def _GenerateNotices(self):
items = []
for e in self._notices:
d = e.GetDictToFormat()
if 'url' in d.keys():
d['url'] = '<a href="%(url)s">%(url)s</a>' % d
items.append('<li class="notice">%s</li>' %
e.FormatProblem(d).replace('\n', '<br>'))
if items:
return '<h2>Notices:</h2>\n<ul>%s</ul>\n' % '\n'.join(items)
else:
return '' | [
"def",
"_GenerateNotices",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"_notices",
":",
"d",
"=",
"e",
".",
"GetDictToFormat",
"(",
")",
"if",
"'url'",
"in",
"d",
".",
"keys",
"(",
")",
":",
"d",
"[",
"'url'",
... | Generate a summary of any notices.
Returns:
The generated HTML as a string. | [
"Generate",
"a",
"summary",
"of",
"any",
"notices",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L265-L281 |
238,964 | google/transitfeed | merge.py | DataSetMerger._MergeIdentical | def _MergeIdentical(self, a, b):
"""Tries to merge two values. The values are required to be identical.
Args:
a: The first value.
b: The second value.
Returns:
The trivially merged value.
Raises:
MergeError: The values were not identical.
"""
if a != b:
raise MergeError("values must be identical ('%s' vs '%s')" %
(transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | python | def _MergeIdentical(self, a, b):
if a != b:
raise MergeError("values must be identical ('%s' vs '%s')" %
(transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | [
"def",
"_MergeIdentical",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
"!=",
"b",
":",
"raise",
"MergeError",
"(",
"\"values must be identical ('%s' vs '%s')\"",
"%",
"(",
"transitfeed",
".",
"EncodeUnicode",
"(",
"a",
")",
",",
"transitfeed",
".",
... | Tries to merge two values. The values are required to be identical.
Args:
a: The first value.
b: The second value.
Returns:
The trivially merged value.
Raises:
MergeError: The values were not identical. | [
"Tries",
"to",
"merge",
"two",
"values",
".",
"The",
"values",
"are",
"required",
"to",
"be",
"identical",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L394-L411 |
238,965 | google/transitfeed | merge.py | DataSetMerger._MergeIdenticalCaseInsensitive | def _MergeIdenticalCaseInsensitive(self, a, b):
"""Tries to merge two strings.
The string are required to be the same ignoring case. The second string is
always used as the merged value.
Args:
a: The first string.
b: The second string.
Returns:
The merged string. This is equal to the second string.
Raises:
MergeError: The strings were not the same ignoring case.
"""
if a.lower() != b.lower():
raise MergeError("values must be the same (case insensitive) "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | python | def _MergeIdenticalCaseInsensitive(self, a, b):
if a.lower() != b.lower():
raise MergeError("values must be the same (case insensitive) "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return b | [
"def",
"_MergeIdenticalCaseInsensitive",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"lower",
"(",
")",
"!=",
"b",
".",
"lower",
"(",
")",
":",
"raise",
"MergeError",
"(",
"\"values must be the same (case insensitive) \"",
"\"('%s' vs '%s')\"",
... | Tries to merge two strings.
The string are required to be the same ignoring case. The second string is
always used as the merged value.
Args:
a: The first string.
b: The second string.
Returns:
The merged string. This is equal to the second string.
Raises:
MergeError: The strings were not the same ignoring case. | [
"Tries",
"to",
"merge",
"two",
"strings",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L413-L433 |
238,966 | google/transitfeed | merge.py | DataSetMerger._MergeOptional | def _MergeOptional(self, a, b):
"""Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same.
"""
if a and b:
if a != b:
raise MergeError("values must be identical if both specified "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return a or b | python | def _MergeOptional(self, a, b):
if a and b:
if a != b:
raise MergeError("values must be identical if both specified "
"('%s' vs '%s')" % (transitfeed.EncodeUnicode(a),
transitfeed.EncodeUnicode(b)))
return a or b | [
"def",
"_MergeOptional",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
"and",
"b",
":",
"if",
"a",
"!=",
"b",
":",
"raise",
"MergeError",
"(",
"\"values must be identical if both specified \"",
"\"('%s' vs '%s')\"",
"%",
"(",
"transitfeed",
".",
"Enc... | Tries to merge two values which may be None.
If both values are not None, they are required to be the same and the
merge is trivial. If one of the values is None and the other is not None,
the merge results in the one which is not None. If both are None, the merge
results in None.
Args:
a: The first value.
b: The second value.
Returns:
The merged value.
Raises:
MergeError: If both values are not None and are not the same. | [
"Tries",
"to",
"merge",
"two",
"values",
"which",
"may",
"be",
"None",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L435-L458 |
238,967 | google/transitfeed | merge.py | DataSetMerger._MergeSameAgency | def _MergeSameAgency(self, a_agency_id, b_agency_id):
"""Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
merged agency.
KeyError: Either aaid or baid is not a valid agency id.
"""
a_agency_id = (a_agency_id or
self.feed_merger.a_schedule.GetDefaultAgency().agency_id)
b_agency_id = (b_agency_id or
self.feed_merger.b_schedule.GetDefaultAgency().agency_id)
a_agency = self.feed_merger.a_schedule.GetAgency(
a_agency_id)._migrated_entity
b_agency = self.feed_merger.b_schedule.GetAgency(
b_agency_id)._migrated_entity
if a_agency != b_agency:
raise MergeError('agency must be the same')
return a_agency.agency_id | python | def _MergeSameAgency(self, a_agency_id, b_agency_id):
a_agency_id = (a_agency_id or
self.feed_merger.a_schedule.GetDefaultAgency().agency_id)
b_agency_id = (b_agency_id or
self.feed_merger.b_schedule.GetDefaultAgency().agency_id)
a_agency = self.feed_merger.a_schedule.GetAgency(
a_agency_id)._migrated_entity
b_agency = self.feed_merger.b_schedule.GetAgency(
b_agency_id)._migrated_entity
if a_agency != b_agency:
raise MergeError('agency must be the same')
return a_agency.agency_id | [
"def",
"_MergeSameAgency",
"(",
"self",
",",
"a_agency_id",
",",
"b_agency_id",
")",
":",
"a_agency_id",
"=",
"(",
"a_agency_id",
"or",
"self",
".",
"feed_merger",
".",
"a_schedule",
".",
"GetDefaultAgency",
"(",
")",
".",
"agency_id",
")",
"b_agency_id",
"=",... | Merge agency ids to the corresponding agency id in the merged schedule.
Args:
a_agency_id: an agency id from the old schedule
b_agency_id: an agency id from the new schedule
Returns:
The agency id of the corresponding merged agency.
Raises:
MergeError: If a_agency_id and b_agency_id do not correspond to the same
merged agency.
KeyError: Either aaid or baid is not a valid agency id. | [
"Merge",
"agency",
"ids",
"to",
"the",
"corresponding",
"agency",
"id",
"in",
"the",
"merged",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L460-L485 |
238,968 | google/transitfeed | merge.py | DataSetMerger._SchemedMerge | def _SchemedMerge(self, scheme, a, b):
"""Tries to merge two entities according to a merge scheme.
A scheme is specified by a map where the keys are entity attributes and the
values are merge functions like Merger._MergeIdentical or
Merger._MergeOptional. The entity is first migrated to the merged schedule.
Then the attributes are individually merged as specified by the scheme.
Args:
scheme: The merge scheme, a map from entity attributes to merge
functions.
a: The entity from the old schedule.
b: The entity from the new schedule.
Returns:
The migrated and merged entity.
Raises:
MergeError: One of the attributes was not able to be merged.
"""
migrated = self._Migrate(b, self.feed_merger.b_schedule, False)
for attr, merger in scheme.items():
a_attr = getattr(a, attr, None)
b_attr = getattr(b, attr, None)
try:
merged_attr = merger(a_attr, b_attr)
except MergeError as merge_error:
raise MergeError("Attribute '%s' could not be merged: %s." % (
attr, merge_error))
setattr(migrated, attr, merged_attr)
return migrated | python | def _SchemedMerge(self, scheme, a, b):
migrated = self._Migrate(b, self.feed_merger.b_schedule, False)
for attr, merger in scheme.items():
a_attr = getattr(a, attr, None)
b_attr = getattr(b, attr, None)
try:
merged_attr = merger(a_attr, b_attr)
except MergeError as merge_error:
raise MergeError("Attribute '%s' could not be merged: %s." % (
attr, merge_error))
setattr(migrated, attr, merged_attr)
return migrated | [
"def",
"_SchemedMerge",
"(",
"self",
",",
"scheme",
",",
"a",
",",
"b",
")",
":",
"migrated",
"=",
"self",
".",
"_Migrate",
"(",
"b",
",",
"self",
".",
"feed_merger",
".",
"b_schedule",
",",
"False",
")",
"for",
"attr",
",",
"merger",
"in",
"scheme",... | Tries to merge two entities according to a merge scheme.
A scheme is specified by a map where the keys are entity attributes and the
values are merge functions like Merger._MergeIdentical or
Merger._MergeOptional. The entity is first migrated to the merged schedule.
Then the attributes are individually merged as specified by the scheme.
Args:
scheme: The merge scheme, a map from entity attributes to merge
functions.
a: The entity from the old schedule.
b: The entity from the new schedule.
Returns:
The migrated and merged entity.
Raises:
MergeError: One of the attributes was not able to be merged. | [
"Tries",
"to",
"merge",
"two",
"entities",
"according",
"to",
"a",
"merge",
"scheme",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L487-L517 |
238,969 | google/transitfeed | merge.py | DataSetMerger._MergeSameId | def _MergeSameId(self):
"""Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedule are simply migrated into the merged schedule.
This method is less flexible than _MergeDifferentId since it only tries
to merge entities which have the same id while _MergeDifferentId tries to
merge everything. However, it is faster and so should be used whenever
possible.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
a_not_merged = []
b_not_merged = []
for a in self._GetIter(self.feed_merger.a_schedule):
try:
b = self._GetById(self.feed_merger.b_schedule, self._GetId(a))
except KeyError:
# there was no entity in B with the same id as a
a_not_merged.append(a)
continue
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError as merge_error:
a_not_merged.append(a)
b_not_merged.append(b)
self._ReportSameIdButNotMerged(self._GetId(a), merge_error)
for b in self._GetIter(self.feed_merger.b_schedule):
try:
a = self._GetById(self.feed_merger.a_schedule, self._GetId(b))
except KeyError:
# there was no entity in A with the same id as b
b_not_merged.append(b)
# migrate the remaining entities
for a in a_not_merged:
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None, self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in b_not_merged:
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b, self._Migrate(b, self.feed_merger.b_schedule, newid))
self._num_not_merged_a = len(a_not_merged)
self._num_not_merged_b = len(b_not_merged)
return self._num_merged | python | def _MergeSameId(self):
a_not_merged = []
b_not_merged = []
for a in self._GetIter(self.feed_merger.a_schedule):
try:
b = self._GetById(self.feed_merger.b_schedule, self._GetId(a))
except KeyError:
# there was no entity in B with the same id as a
a_not_merged.append(a)
continue
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError as merge_error:
a_not_merged.append(a)
b_not_merged.append(b)
self._ReportSameIdButNotMerged(self._GetId(a), merge_error)
for b in self._GetIter(self.feed_merger.b_schedule):
try:
a = self._GetById(self.feed_merger.a_schedule, self._GetId(b))
except KeyError:
# there was no entity in A with the same id as b
b_not_merged.append(b)
# migrate the remaining entities
for a in a_not_merged:
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None, self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in b_not_merged:
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b, self._Migrate(b, self.feed_merger.b_schedule, newid))
self._num_not_merged_a = len(a_not_merged)
self._num_not_merged_b = len(b_not_merged)
return self._num_merged | [
"def",
"_MergeSameId",
"(",
"self",
")",
":",
"a_not_merged",
"=",
"[",
"]",
"b_not_merged",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"_GetIter",
"(",
"self",
".",
"feed_merger",
".",
"a_schedule",
")",
":",
"try",
":",
"b",
"=",
"self",
".",
... | Tries to merge entities based on their ids.
This tries to merge only the entities from the old and new schedules which
have the same id. These are added into the merged schedule. Entities which
do not merge or do not have the same id as another entity in the other
schedule are simply migrated into the merged schedule.
This method is less flexible than _MergeDifferentId since it only tries
to merge entities which have the same id while _MergeDifferentId tries to
merge everything. However, it is faster and so should be used whenever
possible.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities. | [
"Tries",
"to",
"merge",
"entities",
"based",
"on",
"their",
"ids",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L519-L575 |
238,970 | google/transitfeed | merge.py | DataSetMerger._MergeDifferentId | def _MergeDifferentId(self):
"""Tries to merge all possible combinations of entities.
This tries to merge every entity in the old schedule with every entity in
the new schedule. Unlike _MergeSameId, the ids do not need to match.
However, _MergeDifferentId is much slower than _MergeSameId.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities.
"""
# TODO: The same entity from A could merge with multiple from B.
# This should either generate an error or should be prevented from
# happening.
for a in self._GetIter(self.feed_merger.a_schedule):
for b in self._GetIter(self.feed_merger.b_schedule):
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError:
continue
for a in self._GetIter(self.feed_merger.a_schedule):
if a not in self.feed_merger.a_merge_map:
self._num_not_merged_a += 1
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None,
self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in self._GetIter(self.feed_merger.b_schedule):
if b not in self.feed_merger.b_merge_map:
self._num_not_merged_b += 1
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b,
self._Migrate(b, self.feed_merger.b_schedule, newid))
return self._num_merged | python | def _MergeDifferentId(self):
# TODO: The same entity from A could merge with multiple from B.
# This should either generate an error or should be prevented from
# happening.
for a in self._GetIter(self.feed_merger.a_schedule):
for b in self._GetIter(self.feed_merger.b_schedule):
try:
self._Add(a, b, self._MergeEntities(a, b))
self._num_merged += 1
except MergeError:
continue
for a in self._GetIter(self.feed_merger.a_schedule):
if a not in self.feed_merger.a_merge_map:
self._num_not_merged_a += 1
newid = self._HasId(self.feed_merger.b_schedule, self._GetId(a))
self._Add(a, None,
self._Migrate(a, self.feed_merger.a_schedule, newid))
for b in self._GetIter(self.feed_merger.b_schedule):
if b not in self.feed_merger.b_merge_map:
self._num_not_merged_b += 1
newid = self._HasId(self.feed_merger.a_schedule, self._GetId(b))
self._Add(None, b,
self._Migrate(b, self.feed_merger.b_schedule, newid))
return self._num_merged | [
"def",
"_MergeDifferentId",
"(",
"self",
")",
":",
"# TODO: The same entity from A could merge with multiple from B.",
"# This should either generate an error or should be prevented from",
"# happening.",
"for",
"a",
"in",
"self",
".",
"_GetIter",
"(",
"self",
".",
"feed_merger",... | Tries to merge all possible combinations of entities.
This tries to merge every entity in the old schedule with every entity in
the new schedule. Unlike _MergeSameId, the ids do not need to match.
However, _MergeDifferentId is much slower than _MergeSameId.
This method makes use of various methods like _Merge and _Migrate which
are not implemented in the abstract DataSetMerger class. These method
should be overwritten in a subclass to allow _MergeSameId to work with
different entity types.
Returns:
The number of merged entities. | [
"Tries",
"to",
"merge",
"all",
"possible",
"combinations",
"of",
"entities",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L618-L657 |
238,971 | google/transitfeed | merge.py | DataSetMerger._ReportSameIdButNotMerged | def _ReportSameIdButNotMerged(self, entity_id, reason):
"""Report that two entities have the same id but could not be merged.
Args:
entity_id: The id of the entities.
reason: A string giving a reason why they could not be merged.
"""
self.feed_merger.problem_reporter.SameIdButNotMerged(self,
entity_id,
reason) | python | def _ReportSameIdButNotMerged(self, entity_id, reason):
self.feed_merger.problem_reporter.SameIdButNotMerged(self,
entity_id,
reason) | [
"def",
"_ReportSameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")",
":",
"self",
".",
"feed_merger",
".",
"problem_reporter",
".",
"SameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")"
] | Report that two entities have the same id but could not be merged.
Args:
entity_id: The id of the entities.
reason: A string giving a reason why they could not be merged. | [
"Report",
"that",
"two",
"entities",
"have",
"the",
"same",
"id",
"but",
"could",
"not",
"be",
"merged",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L659-L668 |
238,972 | google/transitfeed | merge.py | DataSetMerger._HasId | def _HasId(self, schedule, entity_id):
"""Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not.
"""
try:
self._GetById(schedule, entity_id)
has = True
except KeyError:
has = False
return has | python | def _HasId(self, schedule, entity_id):
try:
self._GetById(schedule, entity_id)
has = True
except KeyError:
has = False
return has | [
"def",
"_HasId",
"(",
"self",
",",
"schedule",
",",
"entity_id",
")",
":",
"try",
":",
"self",
".",
"_GetById",
"(",
"schedule",
",",
"entity_id",
")",
"has",
"=",
"True",
"except",
"KeyError",
":",
"has",
"=",
"False",
"return",
"has"
] | Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not. | [
"Check",
"if",
"the",
"schedule",
"has",
"an",
"entity",
"with",
"the",
"given",
"id",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L708-L723 |
238,973 | google/transitfeed | merge.py | AgencyMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges two agencies.
To be merged, they are required to have the same id, name, url and
timezone. The remaining language attribute is taken from the new agency.
Args:
a: The first agency.
b: The second agency.
Returns:
The merged agency.
Raises:
MergeError: The agencies could not be merged.
"""
def _MergeAgencyId(a_agency_id, b_agency_id):
"""Merge two agency ids.
The only difference between this and _MergeIdentical() is that the values
None and '' are regarded as being the same.
Args:
a_agency_id: The first agency id.
b_agency_id: The second agency id.
Returns:
The merged agency id.
Raises:
MergeError: The agency ids could not be merged.
"""
a_agency_id = a_agency_id or None
b_agency_id = b_agency_id or None
return self._MergeIdentical(a_agency_id, b_agency_id)
scheme = {'agency_id': _MergeAgencyId,
'agency_name': self._MergeIdentical,
'agency_url': self._MergeIdentical,
'agency_timezone': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
def _MergeAgencyId(a_agency_id, b_agency_id):
"""Merge two agency ids.
The only difference between this and _MergeIdentical() is that the values
None and '' are regarded as being the same.
Args:
a_agency_id: The first agency id.
b_agency_id: The second agency id.
Returns:
The merged agency id.
Raises:
MergeError: The agency ids could not be merged.
"""
a_agency_id = a_agency_id or None
b_agency_id = b_agency_id or None
return self._MergeIdentical(a_agency_id, b_agency_id)
scheme = {'agency_id': _MergeAgencyId,
'agency_name': self._MergeIdentical,
'agency_url': self._MergeIdentical,
'agency_timezone': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"def",
"_MergeAgencyId",
"(",
"a_agency_id",
",",
"b_agency_id",
")",
":",
"\"\"\"Merge two agency ids.\n\n The only difference between this and _MergeIdentical() is that the values\n None and '' are re... | Merges two agencies.
To be merged, they are required to have the same id, name, url and
timezone. The remaining language attribute is taken from the new agency.
Args:
a: The first agency.
b: The second agency.
Returns:
The merged agency.
Raises:
MergeError: The agencies could not be merged. | [
"Merges",
"two",
"agencies",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L841-L882 |
238,974 | google/transitfeed | merge.py | StopMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new stop.
Args:
a: The first stop.
b: The second stop.
Returns:
The merged stop.
Raises:
MergeError: The stops could not be merged.
"""
distance = transitfeed.ApproximateDistanceBetweenStops(a, b)
if distance > self.largest_stop_distance:
raise MergeError("Stops are too far apart: %.1fm "
"(largest_stop_distance is %.1fm)." %
(distance, self.largest_stop_distance))
scheme = {'stop_id': self._MergeIdentical,
'stop_name': self._MergeIdenticalCaseInsensitive,
'zone_id': self._MergeIdentical,
'location_type': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
distance = transitfeed.ApproximateDistanceBetweenStops(a, b)
if distance > self.largest_stop_distance:
raise MergeError("Stops are too far apart: %.1fm "
"(largest_stop_distance is %.1fm)." %
(distance, self.largest_stop_distance))
scheme = {'stop_id': self._MergeIdentical,
'stop_name': self._MergeIdenticalCaseInsensitive,
'zone_id': self._MergeIdentical,
'location_type': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"distance",
"=",
"transitfeed",
".",
"ApproximateDistanceBetweenStops",
"(",
"a",
",",
"b",
")",
"if",
"distance",
">",
"self",
".",
"largest_stop_distance",
":",
"raise",
"MergeError",
"(",... | Merges two stops.
For the stops to be merged, they must have:
- the same stop_id
- the same stop_name (case insensitive)
- the same zone_id
- locations less than largest_stop_distance apart
The other attributes can have arbitary changes. The merged attributes are
taken from the new stop.
Args:
a: The first stop.
b: The second stop.
Returns:
The merged stop.
Raises:
MergeError: The stops could not be merged. | [
"Merges",
"two",
"stops",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L932-L962 |
238,975 | google/transitfeed | merge.py | StopMerger._UpdateAndMigrateUnmerged | def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map,
schedule):
"""Correct references in migrated unmerged stops and add to merged_schedule.
For stops migrated from one of the input feeds to the output feed update the
parent_station and zone_id references to point to objects in the output
feed. Then add the migrated stop to the new schedule.
Args:
not_merged_stops: list of stops from one input feed that have not been
merged
zone_map: map from zone_id in the input feed to zone_id in the output feed
merge_map: map from Stop objects in the input feed to Stop objects in
the output feed
schedule: the input Schedule object
"""
# for the unmerged stops, we use an already mapped zone_id if possible
# if not, we generate a new one and add it to the map
for stop, migrated_stop in not_merged_stops:
if stop.zone_id in zone_map:
migrated_stop.zone_id = zone_map[stop.zone_id]
else:
migrated_stop.zone_id = self.feed_merger.GenerateId(stop.zone_id)
zone_map[stop.zone_id] = migrated_stop.zone_id
if stop.parent_station:
parent_original = schedule.GetStop(stop.parent_station)
migrated_stop.parent_station = merge_map[parent_original].stop_id
self.feed_merger.merged_schedule.AddStopObject(migrated_stop) | python | def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map,
schedule):
# for the unmerged stops, we use an already mapped zone_id if possible
# if not, we generate a new one and add it to the map
for stop, migrated_stop in not_merged_stops:
if stop.zone_id in zone_map:
migrated_stop.zone_id = zone_map[stop.zone_id]
else:
migrated_stop.zone_id = self.feed_merger.GenerateId(stop.zone_id)
zone_map[stop.zone_id] = migrated_stop.zone_id
if stop.parent_station:
parent_original = schedule.GetStop(stop.parent_station)
migrated_stop.parent_station = merge_map[parent_original].stop_id
self.feed_merger.merged_schedule.AddStopObject(migrated_stop) | [
"def",
"_UpdateAndMigrateUnmerged",
"(",
"self",
",",
"not_merged_stops",
",",
"zone_map",
",",
"merge_map",
",",
"schedule",
")",
":",
"# for the unmerged stops, we use an already mapped zone_id if possible",
"# if not, we generate a new one and add it to the map",
"for",
"stop",
... | Correct references in migrated unmerged stops and add to merged_schedule.
For stops migrated from one of the input feeds to the output feed update the
parent_station and zone_id references to point to objects in the output
feed. Then add the migrated stop to the new schedule.
Args:
not_merged_stops: list of stops from one input feed that have not been
merged
zone_map: map from zone_id in the input feed to zone_id in the output feed
merge_map: map from Stop objects in the input feed to Stop objects in
the output feed
schedule: the input Schedule object | [
"Correct",
"references",
"in",
"migrated",
"unmerged",
"stops",
"and",
"add",
"to",
"merged_schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1014-L1041 |
238,976 | google/transitfeed | merge.py | ServicePeriodMerger.DisjoinCalendars | def DisjoinCalendars(self, cutoff):
"""Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD format. The timezone
is the same as used in the calendar.txt file.
"""
def TruncatePeriod(service_period, start, end):
"""Truncate the service period to into the range [start, end].
Args:
service_period: The service period to truncate.
start: The start date as a string in YYYYMMDD format.
end: The end date as a string in YYYYMMDD format.
"""
service_period.start_date = max(service_period.start_date, start)
service_period.end_date = min(service_period.end_date, end)
dates_to_delete = []
for k in service_period.date_exceptions:
if (k < start) or (k > end):
dates_to_delete.append(k)
for k in dates_to_delete:
del service_period.date_exceptions[k]
# find the date one day before cutoff
year = int(cutoff[:4])
month = int(cutoff[4:6])
day = int(cutoff[6:8])
cutoff_date = datetime.date(year, month, day)
one_day_delta = datetime.timedelta(days=1)
before = (cutoff_date - one_day_delta).strftime('%Y%m%d')
for a in self.feed_merger.a_schedule.GetServicePeriodList():
TruncatePeriod(a, 0, before)
for b in self.feed_merger.b_schedule.GetServicePeriodList():
TruncatePeriod(b, cutoff, '9'*8) | python | def DisjoinCalendars(self, cutoff):
def TruncatePeriod(service_period, start, end):
"""Truncate the service period to into the range [start, end].
Args:
service_period: The service period to truncate.
start: The start date as a string in YYYYMMDD format.
end: The end date as a string in YYYYMMDD format.
"""
service_period.start_date = max(service_period.start_date, start)
service_period.end_date = min(service_period.end_date, end)
dates_to_delete = []
for k in service_period.date_exceptions:
if (k < start) or (k > end):
dates_to_delete.append(k)
for k in dates_to_delete:
del service_period.date_exceptions[k]
# find the date one day before cutoff
year = int(cutoff[:4])
month = int(cutoff[4:6])
day = int(cutoff[6:8])
cutoff_date = datetime.date(year, month, day)
one_day_delta = datetime.timedelta(days=1)
before = (cutoff_date - one_day_delta).strftime('%Y%m%d')
for a in self.feed_merger.a_schedule.GetServicePeriodList():
TruncatePeriod(a, 0, before)
for b in self.feed_merger.b_schedule.GetServicePeriodList():
TruncatePeriod(b, cutoff, '9'*8) | [
"def",
"DisjoinCalendars",
"(",
"self",
",",
"cutoff",
")",
":",
"def",
"TruncatePeriod",
"(",
"service_period",
",",
"start",
",",
"end",
")",
":",
"\"\"\"Truncate the service period to into the range [start, end].\n\n Args:\n service_period: The service period to tr... | Forces the old and new calendars to be disjoint about a cutoff date.
This truncates the service periods of the old schedule so that service
stops one day before the given cutoff date and truncates the new schedule
so that service only begins on the cutoff date.
Args:
cutoff: The cutoff date as a string in YYYYMMDD format. The timezone
is the same as used in the calendar.txt file. | [
"Forces",
"the",
"old",
"and",
"new",
"calendars",
"to",
"be",
"disjoint",
"about",
"a",
"cutoff",
"date",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1166-L1206 |
238,977 | google/transitfeed | merge.py | ServicePeriodMerger.CheckDisjointCalendars | def CheckDisjointCalendars(self):
"""Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not.
"""
# TODO: Do an exact check here.
a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()
b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()
for a_service_period in a_service_periods:
a_start, a_end = a_service_period.GetDateRange()
for b_service_period in b_service_periods:
b_start, b_end = b_service_period.GetDateRange()
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_end >= overlap_start:
return False
return True | python | def CheckDisjointCalendars(self):
# TODO: Do an exact check here.
a_service_periods = self.feed_merger.a_schedule.GetServicePeriodList()
b_service_periods = self.feed_merger.b_schedule.GetServicePeriodList()
for a_service_period in a_service_periods:
a_start, a_end = a_service_period.GetDateRange()
for b_service_period in b_service_periods:
b_start, b_end = b_service_period.GetDateRange()
overlap_start = max(a_start, b_start)
overlap_end = min(a_end, b_end)
if overlap_end >= overlap_start:
return False
return True | [
"def",
"CheckDisjointCalendars",
"(",
"self",
")",
":",
"# TODO: Do an exact check here.",
"a_service_periods",
"=",
"self",
".",
"feed_merger",
".",
"a_schedule",
".",
"GetServicePeriodList",
"(",
")",
"b_service_periods",
"=",
"self",
".",
"feed_merger",
".",
"b_sch... | Check whether any old service periods intersect with any new ones.
This is a rather coarse check based on
transitfeed.SevicePeriod.GetDateRange.
Returns:
True if the calendars are disjoint or False if not. | [
"Check",
"whether",
"any",
"old",
"service",
"periods",
"intersect",
"with",
"any",
"new",
"ones",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1208-L1230 |
238,978 | google/transitfeed | merge.py | FareMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges the fares if all the attributes are the same."""
scheme = {'price': self._MergeIdentical,
'currency_type': self._MergeIdentical,
'payment_method': self._MergeIdentical,
'transfers': self._MergeIdentical,
'transfer_duration': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | python | def _MergeEntities(self, a, b):
scheme = {'price': self._MergeIdentical,
'currency_type': self._MergeIdentical,
'payment_method': self._MergeIdentical,
'transfers': self._MergeIdentical,
'transfer_duration': self._MergeIdentical}
return self._SchemedMerge(scheme, a, b) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"scheme",
"=",
"{",
"'price'",
":",
"self",
".",
"_MergeIdentical",
",",
"'currency_type'",
":",
"self",
".",
"_MergeIdentical",
",",
"'payment_method'",
":",
"self",
".",
"_MergeIdentical",... | Merges the fares if all the attributes are the same. | [
"Merges",
"the",
"fares",
"if",
"all",
"the",
"attributes",
"are",
"the",
"same",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1249-L1256 |
238,979 | google/transitfeed | merge.py | ShapeMerger._MergeEntities | def _MergeEntities(self, a, b):
"""Merges the shapes by taking the new shape.
Args:
a: The first transitfeed.Shape instance.
b: The second transitfeed.Shape instance.
Returns:
The merged shape.
Raises:
MergeError: If the ids are different or if the endpoints are further
than largest_shape_distance apart.
"""
if a.shape_id != b.shape_id:
raise MergeError('shape_id must be the same')
distance = max(ApproximateDistanceBetweenPoints(a.points[0][:2],
b.points[0][:2]),
ApproximateDistanceBetweenPoints(a.points[-1][:2],
b.points[-1][:2]))
if distance > self.largest_shape_distance:
raise MergeError('The shape endpoints are too far away: %.1fm '
'(largest_shape_distance is %.1fm)' %
(distance, self.largest_shape_distance))
return self._Migrate(b, self.feed_merger.b_schedule, False) | python | def _MergeEntities(self, a, b):
if a.shape_id != b.shape_id:
raise MergeError('shape_id must be the same')
distance = max(ApproximateDistanceBetweenPoints(a.points[0][:2],
b.points[0][:2]),
ApproximateDistanceBetweenPoints(a.points[-1][:2],
b.points[-1][:2]))
if distance > self.largest_shape_distance:
raise MergeError('The shape endpoints are too far away: %.1fm '
'(largest_shape_distance is %.1fm)' %
(distance, self.largest_shape_distance))
return self._Migrate(b, self.feed_merger.b_schedule, False) | [
"def",
"_MergeEntities",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"a",
".",
"shape_id",
"!=",
"b",
".",
"shape_id",
":",
"raise",
"MergeError",
"(",
"'shape_id must be the same'",
")",
"distance",
"=",
"max",
"(",
"ApproximateDistanceBetweenPoints",
... | Merges the shapes by taking the new shape.
Args:
a: The first transitfeed.Shape instance.
b: The second transitfeed.Shape instance.
Returns:
The merged shape.
Raises:
MergeError: If the ids are different or if the endpoints are further
than largest_shape_distance apart. | [
"Merges",
"the",
"shapes",
"by",
"taking",
"the",
"new",
"shape",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1361-L1387 |
238,980 | google/transitfeed | merge.py | FareRuleMerger.MergeDataSets | def MergeDataSets(self):
"""Merge the fare rule datasets.
The fare rules are first migrated. Merging is done by removing any
duplicate rules.
Returns:
True since fare rules can always be merged.
"""
rules = set()
for (schedule, merge_map, zone_map) in ([self.feed_merger.a_schedule,
self.feed_merger.a_merge_map,
self.feed_merger.a_zone_map],
[self.feed_merger.b_schedule,
self.feed_merger.b_merge_map,
self.feed_merger.b_zone_map]):
for fare in schedule.GetFareAttributeList():
for fare_rule in fare.GetFareRuleList():
fare_id = merge_map[
schedule.GetFareAttribute(fare_rule.fare_id)].fare_id
route_id = (fare_rule.route_id and
merge_map[schedule.GetRoute(fare_rule.route_id)].route_id)
origin_id = (fare_rule.origin_id and
zone_map[fare_rule.origin_id])
destination_id = (fare_rule.destination_id and
zone_map[fare_rule.destination_id])
contains_id = (fare_rule.contains_id and
zone_map[fare_rule.contains_id])
rules.add((fare_id, route_id, origin_id, destination_id,
contains_id))
for fare_rule_tuple in rules:
migrated_fare_rule = transitfeed.FareRule(*fare_rule_tuple)
self.feed_merger.merged_schedule.AddFareRuleObject(migrated_fare_rule)
if rules:
self.feed_merger.problem_reporter.FareRulesBroken(self)
print('Fare Rules: union has %d fare rules' % len(rules))
return True | python | def MergeDataSets(self):
rules = set()
for (schedule, merge_map, zone_map) in ([self.feed_merger.a_schedule,
self.feed_merger.a_merge_map,
self.feed_merger.a_zone_map],
[self.feed_merger.b_schedule,
self.feed_merger.b_merge_map,
self.feed_merger.b_zone_map]):
for fare in schedule.GetFareAttributeList():
for fare_rule in fare.GetFareRuleList():
fare_id = merge_map[
schedule.GetFareAttribute(fare_rule.fare_id)].fare_id
route_id = (fare_rule.route_id and
merge_map[schedule.GetRoute(fare_rule.route_id)].route_id)
origin_id = (fare_rule.origin_id and
zone_map[fare_rule.origin_id])
destination_id = (fare_rule.destination_id and
zone_map[fare_rule.destination_id])
contains_id = (fare_rule.contains_id and
zone_map[fare_rule.contains_id])
rules.add((fare_id, route_id, origin_id, destination_id,
contains_id))
for fare_rule_tuple in rules:
migrated_fare_rule = transitfeed.FareRule(*fare_rule_tuple)
self.feed_merger.merged_schedule.AddFareRuleObject(migrated_fare_rule)
if rules:
self.feed_merger.problem_reporter.FareRulesBroken(self)
print('Fare Rules: union has %d fare rules' % len(rules))
return True | [
"def",
"MergeDataSets",
"(",
"self",
")",
":",
"rules",
"=",
"set",
"(",
")",
"for",
"(",
"schedule",
",",
"merge_map",
",",
"zone_map",
")",
"in",
"(",
"[",
"self",
".",
"feed_merger",
".",
"a_schedule",
",",
"self",
".",
"feed_merger",
".",
"a_merge_... | Merge the fare rule datasets.
The fare rules are first migrated. Merging is done by removing any
duplicate rules.
Returns:
True since fare rules can always be merged. | [
"Merge",
"the",
"fare",
"rule",
"datasets",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1510-L1547 |
238,981 | google/transitfeed | merge.py | FeedMerger._FindLargestIdPostfixNumber | def _FindLargestIdPostfixNumber(self, schedule):
"""Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id.
"""
postfix_number_re = re.compile('(\d+)$')
def ExtractPostfixNumber(entity_id):
"""Try to extract an integer from the end of entity_id.
If entity_id is None or if there is no integer ending the id, zero is
returned.
Args:
entity_id: An id string or None.
Returns:
An integer ending the entity_id or zero.
"""
if entity_id is None:
return 0
match = postfix_number_re.search(entity_id)
if match is not None:
return int(match.group(1))
else:
return 0
id_data_sets = {'agency_id': schedule.GetAgencyList(),
'stop_id': schedule.GetStopList(),
'route_id': schedule.GetRouteList(),
'trip_id': schedule.GetTripList(),
'service_id': schedule.GetServicePeriodList(),
'fare_id': schedule.GetFareAttributeList(),
'shape_id': schedule.GetShapeList()}
max_postfix_number = 0
for id_name, entity_list in id_data_sets.items():
for entity in entity_list:
entity_id = getattr(entity, id_name)
postfix_number = ExtractPostfixNumber(entity_id)
max_postfix_number = max(max_postfix_number, postfix_number)
return max_postfix_number | python | def _FindLargestIdPostfixNumber(self, schedule):
postfix_number_re = re.compile('(\d+)$')
def ExtractPostfixNumber(entity_id):
"""Try to extract an integer from the end of entity_id.
If entity_id is None or if there is no integer ending the id, zero is
returned.
Args:
entity_id: An id string or None.
Returns:
An integer ending the entity_id or zero.
"""
if entity_id is None:
return 0
match = postfix_number_re.search(entity_id)
if match is not None:
return int(match.group(1))
else:
return 0
id_data_sets = {'agency_id': schedule.GetAgencyList(),
'stop_id': schedule.GetStopList(),
'route_id': schedule.GetRouteList(),
'trip_id': schedule.GetTripList(),
'service_id': schedule.GetServicePeriodList(),
'fare_id': schedule.GetFareAttributeList(),
'shape_id': schedule.GetShapeList()}
max_postfix_number = 0
for id_name, entity_list in id_data_sets.items():
for entity in entity_list:
entity_id = getattr(entity, id_name)
postfix_number = ExtractPostfixNumber(entity_id)
max_postfix_number = max(max_postfix_number, postfix_number)
return max_postfix_number | [
"def",
"_FindLargestIdPostfixNumber",
"(",
"self",
",",
"schedule",
")",
":",
"postfix_number_re",
"=",
"re",
".",
"compile",
"(",
"'(\\d+)$'",
")",
"def",
"ExtractPostfixNumber",
"(",
"entity_id",
")",
":",
"\"\"\"Try to extract an integer from the end of entity_id.\n\n ... | Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id. | [
"Finds",
"the",
"largest",
"integer",
"used",
"as",
"the",
"ending",
"of",
"an",
"id",
"in",
"the",
"schedule",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1597-L1642 |
238,982 | google/transitfeed | merge.py | FeedMerger.GenerateId | def GenerateId(self, entity_id=None):
"""Generate a unique id based on the given id.
This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.
Args:
entity_id: The base id string. This is allowed to be None.
Returns:
The generated id.
"""
self._idnum += 1
if entity_id:
return '%s_merged_%d' % (entity_id, self._idnum)
else:
return 'merged_%d' % self._idnum | python | def GenerateId(self, entity_id=None):
self._idnum += 1
if entity_id:
return '%s_merged_%d' % (entity_id, self._idnum)
else:
return 'merged_%d' % self._idnum | [
"def",
"GenerateId",
"(",
"self",
",",
"entity_id",
"=",
"None",
")",
":",
"self",
".",
"_idnum",
"+=",
"1",
"if",
"entity_id",
":",
"return",
"'%s_merged_%d'",
"%",
"(",
"entity_id",
",",
"self",
".",
"_idnum",
")",
"else",
":",
"return",
"'merged_%d'",... | Generate a unique id based on the given id.
This is done by appending a counter which is then incremented. The
counter is initialised at the maximum number used as an ending for
any id in the old and new schedules.
Args:
entity_id: The base id string. This is allowed to be None.
Returns:
The generated id. | [
"Generate",
"a",
"unique",
"id",
"based",
"on",
"the",
"given",
"id",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1661-L1678 |
238,983 | google/transitfeed | merge.py | FeedMerger.Register | def Register(self, a, b, migrated_entity):
"""Registers a merge mapping.
If a and b are both not None, this means that entities a and b were merged
to produce migrated_entity. If one of a or b are not None, then it means
it was not merged but simply migrated.
The effect of a call to register is to update a_merge_map and b_merge_map
according to the merge. Also the private attributes _migrated_entity of a
and b are set to migrated_entity.
Args:
a: The entity from the old feed or None.
b: The entity from the new feed or None.
migrated_entity: The migrated entity.
"""
# There are a few places where code needs to find the corresponding
# migrated entity of an object without knowing in which original schedule
# the entity started. With a_merge_map and b_merge_map both have to be
# checked. Use of the _migrated_entity attribute allows the migrated entity
# to be directly found without the schedule. The merge maps also require
# that all objects be hashable. GenericGTFSObject is at the moment, but
# this is a bug. See comment in transitfeed.GenericGTFSObject.
if a is not None:
self.a_merge_map[a] = migrated_entity
a._migrated_entity = migrated_entity
if b is not None:
self.b_merge_map[b] = migrated_entity
b._migrated_entity = migrated_entity | python | def Register(self, a, b, migrated_entity):
# There are a few places where code needs to find the corresponding
# migrated entity of an object without knowing in which original schedule
# the entity started. With a_merge_map and b_merge_map both have to be
# checked. Use of the _migrated_entity attribute allows the migrated entity
# to be directly found without the schedule. The merge maps also require
# that all objects be hashable. GenericGTFSObject is at the moment, but
# this is a bug. See comment in transitfeed.GenericGTFSObject.
if a is not None:
self.a_merge_map[a] = migrated_entity
a._migrated_entity = migrated_entity
if b is not None:
self.b_merge_map[b] = migrated_entity
b._migrated_entity = migrated_entity | [
"def",
"Register",
"(",
"self",
",",
"a",
",",
"b",
",",
"migrated_entity",
")",
":",
"# There are a few places where code needs to find the corresponding",
"# migrated entity of an object without knowing in which original schedule",
"# the entity started. With a_merge_map and b_merge_ma... | Registers a merge mapping.
If a and b are both not None, this means that entities a and b were merged
to produce migrated_entity. If one of a or b are not None, then it means
it was not merged but simply migrated.
The effect of a call to register is to update a_merge_map and b_merge_map
according to the merge. Also the private attributes _migrated_entity of a
and b are set to migrated_entity.
Args:
a: The entity from the old feed or None.
b: The entity from the new feed or None.
migrated_entity: The migrated entity. | [
"Registers",
"a",
"merge",
"mapping",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1680-L1708 |
238,984 | google/transitfeed | merge.py | FeedMerger.AddDefaultMergers | def AddDefaultMergers(self):
"""Adds the default DataSetMergers defined in this module."""
self.AddMerger(AgencyMerger(self))
self.AddMerger(StopMerger(self))
self.AddMerger(RouteMerger(self))
self.AddMerger(ServicePeriodMerger(self))
self.AddMerger(FareMerger(self))
self.AddMerger(ShapeMerger(self))
self.AddMerger(TripMerger(self))
self.AddMerger(FareRuleMerger(self)) | python | def AddDefaultMergers(self):
self.AddMerger(AgencyMerger(self))
self.AddMerger(StopMerger(self))
self.AddMerger(RouteMerger(self))
self.AddMerger(ServicePeriodMerger(self))
self.AddMerger(FareMerger(self))
self.AddMerger(ShapeMerger(self))
self.AddMerger(TripMerger(self))
self.AddMerger(FareRuleMerger(self)) | [
"def",
"AddDefaultMergers",
"(",
"self",
")",
":",
"self",
".",
"AddMerger",
"(",
"AgencyMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"StopMerger",
"(",
"self",
")",
")",
"self",
".",
"AddMerger",
"(",
"RouteMerger",
"(",
"self",
")",
... | Adds the default DataSetMergers defined in this module. | [
"Adds",
"the",
"default",
"DataSetMergers",
"defined",
"in",
"this",
"module",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1718-L1727 |
238,985 | google/transitfeed | merge.py | FeedMerger.GetMerger | def GetMerger(self, cls):
"""Looks for an added DataSetMerger derived from the given class.
Args:
cls: A class derived from DataSetMerger.
Returns:
The matching DataSetMerger instance.
Raises:
LookupError: No matching DataSetMerger has been added.
"""
for merger in self._mergers:
if isinstance(merger, cls):
return merger
raise LookupError('No matching DataSetMerger found') | python | def GetMerger(self, cls):
for merger in self._mergers:
if isinstance(merger, cls):
return merger
raise LookupError('No matching DataSetMerger found') | [
"def",
"GetMerger",
"(",
"self",
",",
"cls",
")",
":",
"for",
"merger",
"in",
"self",
".",
"_mergers",
":",
"if",
"isinstance",
"(",
"merger",
",",
"cls",
")",
":",
"return",
"merger",
"raise",
"LookupError",
"(",
"'No matching DataSetMerger found'",
")"
] | Looks for an added DataSetMerger derived from the given class.
Args:
cls: A class derived from DataSetMerger.
Returns:
The matching DataSetMerger instance.
Raises:
LookupError: No matching DataSetMerger has been added. | [
"Looks",
"for",
"an",
"added",
"DataSetMerger",
"derived",
"from",
"the",
"given",
"class",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L1729-L1744 |
238,986 | google/transitfeed | unusual_trip_filter.py | UnusualTripFilter.filter_line | def filter_line(self, route):
"""Mark unusual trips for the given route."""
if self._route_type is not None and self._route_type != route.route_type:
self.info('Skipping route %s due to different route_type value (%s)' %
(route['route_id'], route['route_type']))
return
self.info('Filtering infrequent trips for route %s.' % route.route_id)
trip_count = len(route.trips)
for pattern_id, pattern in route.GetPatternIdTripDict().items():
ratio = float(1.0 * len(pattern) / trip_count)
if not self._force:
if (ratio < self._threshold):
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as unusual (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
ratio))
for trip in pattern:
trip.trip_type = 1 # special
self.info("\t\tsetting trip_type of trip %s as special" %
trip.trip_id)
else:
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as %s (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
('regular', 'unusual')[ratio < self._threshold],
ratio))
for trip in pattern:
trip.trip_type = ('0','1')[ratio < self._threshold]
self.info("\t\tsetting trip_type of trip %s as %s" %
(trip.trip_id,
('regular', 'unusual')[ratio < self._threshold])) | python | def filter_line(self, route):
if self._route_type is not None and self._route_type != route.route_type:
self.info('Skipping route %s due to different route_type value (%s)' %
(route['route_id'], route['route_type']))
return
self.info('Filtering infrequent trips for route %s.' % route.route_id)
trip_count = len(route.trips)
for pattern_id, pattern in route.GetPatternIdTripDict().items():
ratio = float(1.0 * len(pattern) / trip_count)
if not self._force:
if (ratio < self._threshold):
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as unusual (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
ratio))
for trip in pattern:
trip.trip_type = 1 # special
self.info("\t\tsetting trip_type of trip %s as special" %
trip.trip_id)
else:
self.info("\t%d trips on route %s with headsign '%s' recognized "
"as %s (ratio %f)" %
(len(pattern),
route['route_short_name'],
pattern[0]['trip_headsign'],
('regular', 'unusual')[ratio < self._threshold],
ratio))
for trip in pattern:
trip.trip_type = ('0','1')[ratio < self._threshold]
self.info("\t\tsetting trip_type of trip %s as %s" %
(trip.trip_id,
('regular', 'unusual')[ratio < self._threshold])) | [
"def",
"filter_line",
"(",
"self",
",",
"route",
")",
":",
"if",
"self",
".",
"_route_type",
"is",
"not",
"None",
"and",
"self",
".",
"_route_type",
"!=",
"route",
".",
"route_type",
":",
"self",
".",
"info",
"(",
"'Skipping route %s due to different route_typ... | Mark unusual trips for the given route. | [
"Mark",
"unusual",
"trips",
"for",
"the",
"given",
"route",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/unusual_trip_filter.py#L56-L90 |
238,987 | google/transitfeed | unusual_trip_filter.py | UnusualTripFilter.filter | def filter(self, dataset):
"""Mark unusual trips for all the routes in the dataset."""
self.info('Going to filter infrequent routes in the dataset')
for route in dataset.routes.values():
self.filter_line(route) | python | def filter(self, dataset):
self.info('Going to filter infrequent routes in the dataset')
for route in dataset.routes.values():
self.filter_line(route) | [
"def",
"filter",
"(",
"self",
",",
"dataset",
")",
":",
"self",
".",
"info",
"(",
"'Going to filter infrequent routes in the dataset'",
")",
"for",
"route",
"in",
"dataset",
".",
"routes",
".",
"values",
"(",
")",
":",
"self",
".",
"filter_line",
"(",
"route... | Mark unusual trips for all the routes in the dataset. | [
"Mark",
"unusual",
"trips",
"for",
"all",
"the",
"routes",
"in",
"the",
"dataset",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/unusual_trip_filter.py#L92-L96 |
238,988 | google/transitfeed | schedule_viewer.py | StopToTuple | def StopToTuple(stop):
"""Return tuple as expected by javascript function addStopMarkerFromList"""
return (stop.stop_id, stop.stop_name, float(stop.stop_lat),
float(stop.stop_lon), stop.location_type) | python | def StopToTuple(stop):
return (stop.stop_id, stop.stop_name, float(stop.stop_lat),
float(stop.stop_lon), stop.location_type) | [
"def",
"StopToTuple",
"(",
"stop",
")",
":",
"return",
"(",
"stop",
".",
"stop_id",
",",
"stop",
".",
"stop_name",
",",
"float",
"(",
"stop",
".",
"stop_lat",
")",
",",
"float",
"(",
"stop",
".",
"stop_lon",
")",
",",
"stop",
".",
"location_type",
")... | Return tuple as expected by javascript function addStopMarkerFromList | [
"Return",
"tuple",
"as",
"expected",
"by",
"javascript",
"function",
"addStopMarkerFromList"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L89-L92 |
238,989 | google/transitfeed | schedule_viewer.py | FindDefaultFileDir | def FindDefaultFileDir():
"""Return the path of the directory containing the static files. By default
the directory is called 'files'. The location depends on where setup.py put
it."""
base = FindPy2ExeBase()
if base:
return os.path.join(base, 'schedule_viewer_files')
else:
# For all other distributions 'files' is in the gtfsscheduleviewer
# directory.
base = os.path.dirname(gtfsscheduleviewer.__file__) # Strip __init__.py
return os.path.join(base, 'files') | python | def FindDefaultFileDir():
base = FindPy2ExeBase()
if base:
return os.path.join(base, 'schedule_viewer_files')
else:
# For all other distributions 'files' is in the gtfsscheduleviewer
# directory.
base = os.path.dirname(gtfsscheduleviewer.__file__) # Strip __init__.py
return os.path.join(base, 'files') | [
"def",
"FindDefaultFileDir",
"(",
")",
":",
"base",
"=",
"FindPy2ExeBase",
"(",
")",
"if",
"base",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"'schedule_viewer_files'",
")",
"else",
":",
"# For all other distributions 'files' is in the gtfssc... | Return the path of the directory containing the static files. By default
the directory is called 'files'. The location depends on where setup.py put
it. | [
"Return",
"the",
"path",
"of",
"the",
"directory",
"containing",
"the",
"static",
"files",
".",
"By",
"default",
"the",
"directory",
"is",
"called",
"files",
".",
"The",
"location",
"depends",
"on",
"where",
"setup",
".",
"py",
"put",
"it",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L461-L472 |
238,990 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_routepatterns | def handle_json_GET_routepatterns(self, params):
"""Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips."""
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send_error(404)
return
time = int(params.get('time', 0))
date = params.get('date', "")
sample_size = 3 # For each pattern return the start time for this many trips
pattern_id_trip_dict = route.GetPatternIdTripDict()
patterns = []
for pattern_id, trips in pattern_id_trip_dict.items():
time_stops = trips[0].GetTimeStops()
if not time_stops:
continue
has_non_zero_trip_type = False;
# Iterating over a copy so we can remove from trips inside the loop
trips_with_service = []
for trip in trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
trips_with_service.append(trip)
if trip['trip_type'] and trip['trip_type'] != '0':
has_non_zero_trip_type = True
# We're only interested in the trips that do run on the specified date
trips = trips_with_service
name = u'%s to %s, %d stops' % (time_stops[0][2].stop_name, time_stops[-1][2].stop_name, len(time_stops))
transitfeed.SortListOfTripByTime(trips)
num_trips = len(trips)
if num_trips <= sample_size:
start_sample_index = 0
num_after_sample = 0
else:
# Will return sample_size trips that start after the 'time' param.
# Linear search because I couldn't find a built-in way to do a binary
# search with a custom key.
start_sample_index = len(trips)
for i, trip in enumerate(trips):
if trip.GetStartTime() >= time:
start_sample_index = i
break
num_after_sample = num_trips - (start_sample_index + sample_size)
if num_after_sample < 0:
# Less than sample_size trips start after 'time' so return all the
# last sample_size trips.
num_after_sample = 0
start_sample_index = num_trips - sample_size
sample = []
for t in trips[start_sample_index:start_sample_index + sample_size]:
sample.append( (t.GetStartTime(), t.trip_id) )
patterns.append((name, pattern_id, start_sample_index, sample,
num_after_sample, (0,1)[has_non_zero_trip_type]))
patterns.sort()
return patterns | python | def handle_json_GET_routepatterns(self, params):
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send_error(404)
return
time = int(params.get('time', 0))
date = params.get('date', "")
sample_size = 3 # For each pattern return the start time for this many trips
pattern_id_trip_dict = route.GetPatternIdTripDict()
patterns = []
for pattern_id, trips in pattern_id_trip_dict.items():
time_stops = trips[0].GetTimeStops()
if not time_stops:
continue
has_non_zero_trip_type = False;
# Iterating over a copy so we can remove from trips inside the loop
trips_with_service = []
for trip in trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
trips_with_service.append(trip)
if trip['trip_type'] and trip['trip_type'] != '0':
has_non_zero_trip_type = True
# We're only interested in the trips that do run on the specified date
trips = trips_with_service
name = u'%s to %s, %d stops' % (time_stops[0][2].stop_name, time_stops[-1][2].stop_name, len(time_stops))
transitfeed.SortListOfTripByTime(trips)
num_trips = len(trips)
if num_trips <= sample_size:
start_sample_index = 0
num_after_sample = 0
else:
# Will return sample_size trips that start after the 'time' param.
# Linear search because I couldn't find a built-in way to do a binary
# search with a custom key.
start_sample_index = len(trips)
for i, trip in enumerate(trips):
if trip.GetStartTime() >= time:
start_sample_index = i
break
num_after_sample = num_trips - (start_sample_index + sample_size)
if num_after_sample < 0:
# Less than sample_size trips start after 'time' so return all the
# last sample_size trips.
num_after_sample = 0
start_sample_index = num_trips - sample_size
sample = []
for t in trips[start_sample_index:start_sample_index + sample_size]:
sample.append( (t.GetStartTime(), t.trip_id) )
patterns.append((name, pattern_id, start_sample_index, sample,
num_after_sample, (0,1)[has_non_zero_trip_type]))
patterns.sort()
return patterns | [
"def",
"handle_json_GET_routepatterns",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"route",
"=",
"schedule",
".",
"GetRoute",
"(",
"params",
".",
"get",
"(",
"'route'",
",",
"None",
")",
")",
"if",
"not... | Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips. | [
"Given",
"a",
"route_id",
"generate",
"a",
"list",
"of",
"patterns",
"of",
"the",
"route",
".",
"For",
"each",
"pattern",
"include",
"some",
"basic",
"information",
"and",
"a",
"few",
"sample",
"trips",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L187-L257 |
238,991 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_wrapper_GET | def handle_json_wrapper_GET(self, handler, parsed_params):
"""Call handler and output the return value in JSON."""
schedule = self.server.schedule
result = handler(parsed_params)
content = ResultEncoder().encode(result)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content) | python | def handle_json_wrapper_GET(self, handler, parsed_params):
schedule = self.server.schedule
result = handler(parsed_params)
content = ResultEncoder().encode(result)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content) | [
"def",
"handle_json_wrapper_GET",
"(",
"self",
",",
"handler",
",",
"parsed_params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"result",
"=",
"handler",
"(",
"parsed_params",
")",
"content",
"=",
"ResultEncoder",
"(",
")",
".",
"enco... | Call handler and output the return value in JSON. | [
"Call",
"handler",
"and",
"output",
"the",
"return",
"value",
"in",
"JSON",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L259-L268 |
238,992 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_routes | def handle_json_GET_routes(self, params):
"""Return a list of all routes."""
schedule = self.server.schedule
result = []
for r in schedule.GetRouteList():
result.append( (r.route_id, r.route_short_name, r.route_long_name) )
result.sort(key = lambda x: x[1:3])
return result | python | def handle_json_GET_routes(self, params):
schedule = self.server.schedule
result = []
for r in schedule.GetRouteList():
result.append( (r.route_id, r.route_short_name, r.route_long_name) )
result.sort(key = lambda x: x[1:3])
return result | [
"def",
"handle_json_GET_routes",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"result",
"=",
"[",
"]",
"for",
"r",
"in",
"schedule",
".",
"GetRouteList",
"(",
")",
":",
"result",
".",
"append",
"(",
"("... | Return a list of all routes. | [
"Return",
"a",
"list",
"of",
"all",
"routes",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L270-L277 |
238,993 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_triprows | def handle_json_GET_triprows(self, params):
"""Return a list of rows from the feed file that are related to this
trip."""
schedule = self.server.schedule
try:
trip = schedule.GetTrip(params.get('trip', None))
except KeyError:
# if a non-existent trip is searched for, the return nothing
return
route = schedule.GetRoute(trip.route_id)
trip_row = dict(trip.iteritems())
route_row = dict(route.iteritems())
return [['trips.txt', trip_row], ['routes.txt', route_row]] | python | def handle_json_GET_triprows(self, params):
schedule = self.server.schedule
try:
trip = schedule.GetTrip(params.get('trip', None))
except KeyError:
# if a non-existent trip is searched for, the return nothing
return
route = schedule.GetRoute(trip.route_id)
trip_row = dict(trip.iteritems())
route_row = dict(route.iteritems())
return [['trips.txt', trip_row], ['routes.txt', route_row]] | [
"def",
"handle_json_GET_triprows",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"try",
":",
"trip",
"=",
"schedule",
".",
"GetTrip",
"(",
"params",
".",
"get",
"(",
"'trip'",
",",
"None",
")",
")",
"exc... | Return a list of rows from the feed file that are related to this
trip. | [
"Return",
"a",
"list",
"of",
"rows",
"from",
"the",
"feed",
"file",
"that",
"are",
"related",
"to",
"this",
"trip",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L284-L296 |
238,994 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_neareststops | def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
limit = int(params.get('limit'))
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
return [StopToTuple(s) for s in stops] | python | def handle_json_GET_neareststops(self, params):
"""Return a list of the nearest 'limit' stops to 'lat', 'lon'"""
schedule = self.server.schedule
lat = float(params.get('lat'))
lon = float(params.get('lon'))
limit = int(params.get('limit'))
stops = schedule.GetNearestStops(lat=lat, lon=lon, n=limit)
return [StopToTuple(s) for s in stops] | [
"def",
"handle_json_GET_neareststops",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"lat",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'lat'",
")",
")",
"lon",
"=",
"float",
"(",
"params",
".",
"get"... | Return a list of the nearest 'limit' stops to 'lat', 'lon | [
"Return",
"a",
"list",
"of",
"the",
"nearest",
"limit",
"stops",
"to",
"lat",
"lon"
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L337-L344 |
238,995 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_boundboxstops | def handle_json_GET_boundboxstops(self, params):
"""Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180."""
schedule = self.server.schedule
n = float(params.get('n'))
e = float(params.get('e'))
s = float(params.get('s'))
w = float(params.get('w'))
limit = int(params.get('limit'))
stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)
return [StopToTuple(s) for s in stops] | python | def handle_json_GET_boundboxstops(self, params):
schedule = self.server.schedule
n = float(params.get('n'))
e = float(params.get('e'))
s = float(params.get('s'))
w = float(params.get('w'))
limit = int(params.get('limit'))
stops = schedule.GetStopsInBoundingBox(north=n, east=e, south=s, west=w, n=limit)
return [StopToTuple(s) for s in stops] | [
"def",
"handle_json_GET_boundboxstops",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"n",
"=",
"float",
"(",
"params",
".",
"get",
"(",
"'n'",
")",
")",
"e",
"=",
"float",
"(",
"params",
".",
"get",
"... | Return a list of up to 'limit' stops within bounding box with 'n','e'
and 's','w' in the NE and SW corners. Does not handle boxes crossing
longitude line 180. | [
"Return",
"a",
"list",
"of",
"up",
"to",
"limit",
"stops",
"within",
"bounding",
"box",
"with",
"n",
"e",
"and",
"s",
"w",
"in",
"the",
"NE",
"and",
"SW",
"corners",
".",
"Does",
"not",
"handle",
"boxes",
"crossing",
"longitude",
"line",
"180",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L346-L357 |
238,996 | google/transitfeed | schedule_viewer.py | ScheduleRequestHandler.handle_json_GET_stoptrips | def handle_json_GET_stoptrips(self, params):
"""Given a stop_id and time in seconds since midnight return the next
trips to visit the stop."""
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', "")
time_trips = stop.GetStopTimeTrips(schedule)
time_trips.sort() # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
# Keep the first 5 after param 'time'.
# Need make a tuple to find correct bisect point
time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
time_trips = time_trips[:5]
# TODO: combine times for a route to show next 2 departure times
result = []
for time, (trip, index), tp in time_trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
headsign = None
# Find the most recent headsign from the StopTime objects
for stoptime in trip.GetStopTimes()[index::-1]:
if stoptime.stop_headsign:
headsign = stoptime.stop_headsign
break
# If stop_headsign isn't found, look for a trip_headsign
if not headsign:
headsign = trip.trip_headsign
route = schedule.GetRoute(trip.route_id)
trip_name = ''
if route.route_short_name:
trip_name += route.route_short_name
if route.route_long_name:
if len(trip_name):
trip_name += " - "
trip_name += route.route_long_name
if headsign:
trip_name += " (Direction: %s)" % headsign
result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
return result | python | def handle_json_GET_stoptrips(self, params):
schedule = self.server.schedule
stop = schedule.GetStop(params.get('stop', None))
time = int(params.get('time', 0))
date = params.get('date', "")
time_trips = stop.GetStopTimeTrips(schedule)
time_trips.sort() # OPT: use bisect.insort to make this O(N*ln(N)) -> O(N)
# Keep the first 5 after param 'time'.
# Need make a tuple to find correct bisect point
time_trips = time_trips[bisect.bisect_left(time_trips, (time, 0)):]
time_trips = time_trips[:5]
# TODO: combine times for a route to show next 2 departure times
result = []
for time, (trip, index), tp in time_trips:
service_id = trip.service_id
service_period = schedule.GetServicePeriod(service_id)
if date and not service_period.IsActiveOn(date):
continue
headsign = None
# Find the most recent headsign from the StopTime objects
for stoptime in trip.GetStopTimes()[index::-1]:
if stoptime.stop_headsign:
headsign = stoptime.stop_headsign
break
# If stop_headsign isn't found, look for a trip_headsign
if not headsign:
headsign = trip.trip_headsign
route = schedule.GetRoute(trip.route_id)
trip_name = ''
if route.route_short_name:
trip_name += route.route_short_name
if route.route_long_name:
if len(trip_name):
trip_name += " - "
trip_name += route.route_long_name
if headsign:
trip_name += " (Direction: %s)" % headsign
result.append((time, (trip.trip_id, trip_name, trip.service_id), tp))
return result | [
"def",
"handle_json_GET_stoptrips",
"(",
"self",
",",
"params",
")",
":",
"schedule",
"=",
"self",
".",
"server",
".",
"schedule",
"stop",
"=",
"schedule",
".",
"GetStop",
"(",
"params",
".",
"get",
"(",
"'stop'",
",",
"None",
")",
")",
"time",
"=",
"i... | Given a stop_id and time in seconds since midnight return the next
trips to visit the stop. | [
"Given",
"a",
"stop_id",
"and",
"time",
"in",
"seconds",
"since",
"midnight",
"return",
"the",
"next",
"trips",
"to",
"visit",
"the",
"stop",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/schedule_viewer.py#L368-L410 |
238,997 | google/transitfeed | misc/traceplus.py | MakeExpandedTrace | def MakeExpandedTrace(frame_records):
"""Return a list of text lines for the given list of frame records."""
dump = []
for (frame_obj, filename, line_num, fun_name, context_lines,
context_index) in frame_records:
dump.append('File "%s", line %d, in %s\n' % (filename, line_num,
fun_name))
if context_lines:
for (i, line) in enumerate(context_lines):
if i == context_index:
dump.append(' --> %s' % line)
else:
dump.append(' %s' % line)
for local_name, local_val in frame_obj.f_locals.items():
try:
local_type_name = type(local_val).__name__
except Exception as e:
local_type_name = ' Exception in type({}).__name__: {}'.format(local_name, e)
try:
truncated_val = repr(local_val)[0:500]
except Exception as e:
dump.append(' Exception in repr({}): {}\n'.format(local_name, e))
else:
if len(truncated_val) >= 500:
truncated_val = '%s...' % truncated_val[0:499]
dump.append(' {} = {} ({})\n'.format(local_name, truncated_val, local_type_name))
dump.append('\n')
return dump | python | def MakeExpandedTrace(frame_records):
dump = []
for (frame_obj, filename, line_num, fun_name, context_lines,
context_index) in frame_records:
dump.append('File "%s", line %d, in %s\n' % (filename, line_num,
fun_name))
if context_lines:
for (i, line) in enumerate(context_lines):
if i == context_index:
dump.append(' --> %s' % line)
else:
dump.append(' %s' % line)
for local_name, local_val in frame_obj.f_locals.items():
try:
local_type_name = type(local_val).__name__
except Exception as e:
local_type_name = ' Exception in type({}).__name__: {}'.format(local_name, e)
try:
truncated_val = repr(local_val)[0:500]
except Exception as e:
dump.append(' Exception in repr({}): {}\n'.format(local_name, e))
else:
if len(truncated_val) >= 500:
truncated_val = '%s...' % truncated_val[0:499]
dump.append(' {} = {} ({})\n'.format(local_name, truncated_val, local_type_name))
dump.append('\n')
return dump | [
"def",
"MakeExpandedTrace",
"(",
"frame_records",
")",
":",
"dump",
"=",
"[",
"]",
"for",
"(",
"frame_obj",
",",
"filename",
",",
"line_num",
",",
"fun_name",
",",
"context_lines",
",",
"context_index",
")",
"in",
"frame_records",
":",
"dump",
".",
"append",... | Return a list of text lines for the given list of frame records. | [
"Return",
"a",
"list",
"of",
"text",
"lines",
"for",
"the",
"given",
"list",
"of",
"frame",
"records",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/misc/traceplus.py#L24-L51 |
238,998 | google/transitfeed | transitfeed/shapepoint.py | ShapePoint.ParseAttributes | def ParseAttributes(self, problems):
"""Parse all attributes, calling problems as needed.
Return True if all of the values are valid.
"""
if util.IsEmpty(self.shape_id):
problems.MissingValue('shape_id')
return
try:
if not isinstance(self.shape_pt_sequence, int):
self.shape_pt_sequence = \
util.NonNegIntStringToInt(self.shape_pt_sequence, problems)
elif self.shape_pt_sequence < 0:
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
return
try:
if not isinstance(self.shape_pt_lat, (int, float)):
self.shape_pt_lat = util.FloatStringToFloat(self.shape_pt_lat, problems)
if abs(self.shape_pt_lat) > 90.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
try:
if not isinstance(self.shape_pt_lon, (int, float)):
self.shape_pt_lon = util.FloatStringToFloat(self.shape_pt_lon, problems)
if abs(self.shape_pt_lon) > 180.0:
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
if abs(self.shape_pt_lat) < 1.0 and abs(self.shape_pt_lon) < 1.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat,
'Point location too close to 0, 0, which means '
'that it\'s probably an incorrect location.',
type=problems_module.TYPE_WARNING)
return
if self.shape_dist_traveled == '':
self.shape_dist_traveled = None
if (self.shape_dist_traveled is not None and
not isinstance(self.shape_dist_traveled, (int, float))):
try:
self.shape_dist_traveled = \
util.FloatStringToFloat(self.shape_dist_traveled, problems)
except (TypeError, ValueError):
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
if self.shape_dist_traveled is not None and self.shape_dist_traveled < 0:
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
return True | python | def ParseAttributes(self, problems):
if util.IsEmpty(self.shape_id):
problems.MissingValue('shape_id')
return
try:
if not isinstance(self.shape_pt_sequence, int):
self.shape_pt_sequence = \
util.NonNegIntStringToInt(self.shape_pt_sequence, problems)
elif self.shape_pt_sequence < 0:
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_sequence', self.shape_pt_sequence,
'Value should be a number (0 or higher)')
return
try:
if not isinstance(self.shape_pt_lat, (int, float)):
self.shape_pt_lat = util.FloatStringToFloat(self.shape_pt_lat, problems)
if abs(self.shape_pt_lat) > 90.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat)
return
try:
if not isinstance(self.shape_pt_lon, (int, float)):
self.shape_pt_lon = util.FloatStringToFloat(self.shape_pt_lon, problems)
if abs(self.shape_pt_lon) > 180.0:
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
except (TypeError, ValueError):
problems.InvalidValue('shape_pt_lon', self.shape_pt_lon)
return
if abs(self.shape_pt_lat) < 1.0 and abs(self.shape_pt_lon) < 1.0:
problems.InvalidValue('shape_pt_lat', self.shape_pt_lat,
'Point location too close to 0, 0, which means '
'that it\'s probably an incorrect location.',
type=problems_module.TYPE_WARNING)
return
if self.shape_dist_traveled == '':
self.shape_dist_traveled = None
if (self.shape_dist_traveled is not None and
not isinstance(self.shape_dist_traveled, (int, float))):
try:
self.shape_dist_traveled = \
util.FloatStringToFloat(self.shape_dist_traveled, problems)
except (TypeError, ValueError):
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
if self.shape_dist_traveled is not None and self.shape_dist_traveled < 0:
problems.InvalidValue('shape_dist_traveled', self.shape_dist_traveled,
'This value should be a positive number.')
return
return True | [
"def",
"ParseAttributes",
"(",
"self",
",",
"problems",
")",
":",
"if",
"util",
".",
"IsEmpty",
"(",
"self",
".",
"shape_id",
")",
":",
"problems",
".",
"MissingValue",
"(",
"'shape_id'",
")",
"return",
"try",
":",
"if",
"not",
"isinstance",
"(",
"self",... | Parse all attributes, calling problems as needed.
Return True if all of the values are valid. | [
"Parse",
"all",
"attributes",
"calling",
"problems",
"as",
"needed",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/shapepoint.py#L59-L125 |
238,999 | google/transitfeed | transitfeed/problems.py | ProblemReporter.SetFileContext | def SetFileContext(self, file_name, row_num, row, headers):
"""Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's
"""
self._context = (file_name, row_num, row, headers) | python | def SetFileContext(self, file_name, row_num, row, headers):
self._context = (file_name, row_num, row, headers) | [
"def",
"SetFileContext",
"(",
"self",
",",
"file_name",
",",
"row_num",
",",
"row",
",",
"headers",
")",
":",
"self",
".",
"_context",
"=",
"(",
"file_name",
",",
"row_num",
",",
"row",
",",
"headers",
")"
] | Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's | [
"Save",
"the",
"current",
"context",
"to",
"be",
"output",
"with",
"any",
"errors",
"."
] | eb2991a3747ba541b2cb66502b305b6304a1f85f | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/problems.py#L53-L62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.