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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph._CalculateYLines
def _CalculateYLines(self, dists): """Builds a list with y-coordinates for the horizontal lines in the graph. Args: # One integer for each pair of stations # indicating the approximate distance dists: [0,33,140, ... ,X] Returns: # One integer y-coordinate for each station normalized between # 0 and X, where X is the height of the graph in pixels [0, 33, 140, ... , X] """ tot_dist = sum(dists) if tot_dist > 0: pixel_dist = [float(d * (self._gheight-20))/tot_dist for d in dists] pixel_grid = [0]+[int(pd + sum(pixel_dist[0:i])) for i,pd in enumerate(pixel_dist)] else: pixel_grid = [] return pixel_grid
python
def _CalculateYLines(self, dists): """Builds a list with y-coordinates for the horizontal lines in the graph. Args: # One integer for each pair of stations # indicating the approximate distance dists: [0,33,140, ... ,X] Returns: # One integer y-coordinate for each station normalized between # 0 and X, where X is the height of the graph in pixels [0, 33, 140, ... , X] """ tot_dist = sum(dists) if tot_dist > 0: pixel_dist = [float(d * (self._gheight-20))/tot_dist for d in dists] pixel_grid = [0]+[int(pd + sum(pixel_dist[0:i])) for i,pd in enumerate(pixel_dist)] else: pixel_grid = [] return pixel_grid
[ "def", "_CalculateYLines", "(", "self", ",", "dists", ")", ":", "tot_dist", "=", "sum", "(", "dists", ")", "if", "tot_dist", ">", "0", ":", "pixel_dist", "=", "[", "float", "(", "d", "*", "(", "self", ".", "_gheight", "-", "20", ")", ")", "/", "t...
Builds a list with y-coordinates for the horizontal lines in the graph. Args: # One integer for each pair of stations # indicating the approximate distance dists: [0,33,140, ... ,X] Returns: # One integer y-coordinate for each station normalized between # 0 and X, where X is the height of the graph in pixels [0, 33, 140, ... , X]
[ "Builds", "a", "list", "with", "y", "-", "coordinates", "for", "the", "horizontal", "lines", "in", "the", "graph", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L236-L257
train
219,900
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph._TravelTimes
def _TravelTimes(self,triplist,index=0): """ Calculate distances and plot stops. Uses a timetable to approximate distances between stations Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # (Optional) Index of Triplist prefered for timetable Calculation index: 3 Returns: # One integer for each pair of stations # indicating the approximate distance [0,33,140, ... ,X] """ def DistanceInTravelTime(dep_secs, arr_secs): t_dist = arr_secs-dep_secs if t_dist<0: t_dist = self._DUMMY_SEPARATOR # min separation return t_dist if not triplist: return [] if 0 < index < len(triplist): trip = triplist[index] else: trip = triplist[0] t_dists2 = [DistanceInTravelTime(stop[3],tail[2]) for (stop,tail) in itertools.izip(trip.GetTimeStops(),trip.GetTimeStops()[1:])] return t_dists2
python
def _TravelTimes(self,triplist,index=0): """ Calculate distances and plot stops. Uses a timetable to approximate distances between stations Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # (Optional) Index of Triplist prefered for timetable Calculation index: 3 Returns: # One integer for each pair of stations # indicating the approximate distance [0,33,140, ... ,X] """ def DistanceInTravelTime(dep_secs, arr_secs): t_dist = arr_secs-dep_secs if t_dist<0: t_dist = self._DUMMY_SEPARATOR # min separation return t_dist if not triplist: return [] if 0 < index < len(triplist): trip = triplist[index] else: trip = triplist[0] t_dists2 = [DistanceInTravelTime(stop[3],tail[2]) for (stop,tail) in itertools.izip(trip.GetTimeStops(),trip.GetTimeStops()[1:])] return t_dists2
[ "def", "_TravelTimes", "(", "self", ",", "triplist", ",", "index", "=", "0", ")", ":", "def", "DistanceInTravelTime", "(", "dep_secs", ",", "arr_secs", ")", ":", "t_dist", "=", "arr_secs", "-", "dep_secs", "if", "t_dist", "<", "0", ":", "t_dist", "=", ...
Calculate distances and plot stops. Uses a timetable to approximate distances between stations Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # (Optional) Index of Triplist prefered for timetable Calculation index: 3 Returns: # One integer for each pair of stations # indicating the approximate distance [0,33,140, ... ,X]
[ "Calculate", "distances", "and", "plot", "stops", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L259-L293
train
219,901
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph._DrawTrips
def _DrawTrips(self,triplist,colpar=""): """Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" points="433,0 ...' """ stations = [] if not self._stations and triplist: self._stations = self._CalculateYLines(self._TravelTimes(triplist)) if not self._stations: self._AddWarning("Failed to use traveltimes for graph") self._stations = self._CalculateYLines(self._Uniform(triplist)) if not self._stations: self._AddWarning("Failed to calculate station distances") return stations = self._stations tmpstrs = [] servlist = [] for t in triplist: if not colpar: if t.service_id not in servlist: servlist.append(t.service_id) shade = int(servlist.index(t.service_id) * (200/len(servlist))+55) color = "#00%s00" % hex(shade)[2:4] else: color=colpar start_offsets = [0] first_stop = t.GetTimeStops()[0] for j,freq_offset in enumerate(start_offsets): if j>0 and not colpar: color="purple" scriptcall = 'onmouseover="LineClick(\'%s\',\'Trip %s starting %s\')"' % (t.trip_id, t.trip_id, transitfeed.FormatSecondsSinceMidnight(t.GetStartTime())) tmpstrhead = '<polyline class="T" id="%s" stroke="%s" %s points="' % \ (str(t.trip_id),color, scriptcall) tmpstrs.append(tmpstrhead) for i, s in enumerate(t.GetTimeStops()): arr_t = s[0] dep_t = s[1] if arr_t is None or dep_t is None: continue arr_x = int(arr_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset dep_x = int(dep_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset tmpstrs.append("%s,%s " % (int(arr_x+20), int(stations[i]+20))) tmpstrs.append("%s,%s " % (int(dep_x+20), int(stations[i]+20))) tmpstrs.append('" />') return "".join(tmpstrs)
python
def _DrawTrips(self,triplist,colpar=""): """Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" points="433,0 ...' """ stations = [] if not self._stations and triplist: self._stations = self._CalculateYLines(self._TravelTimes(triplist)) if not self._stations: self._AddWarning("Failed to use traveltimes for graph") self._stations = self._CalculateYLines(self._Uniform(triplist)) if not self._stations: self._AddWarning("Failed to calculate station distances") return stations = self._stations tmpstrs = [] servlist = [] for t in triplist: if not colpar: if t.service_id not in servlist: servlist.append(t.service_id) shade = int(servlist.index(t.service_id) * (200/len(servlist))+55) color = "#00%s00" % hex(shade)[2:4] else: color=colpar start_offsets = [0] first_stop = t.GetTimeStops()[0] for j,freq_offset in enumerate(start_offsets): if j>0 and not colpar: color="purple" scriptcall = 'onmouseover="LineClick(\'%s\',\'Trip %s starting %s\')"' % (t.trip_id, t.trip_id, transitfeed.FormatSecondsSinceMidnight(t.GetStartTime())) tmpstrhead = '<polyline class="T" id="%s" stroke="%s" %s points="' % \ (str(t.trip_id),color, scriptcall) tmpstrs.append(tmpstrhead) for i, s in enumerate(t.GetTimeStops()): arr_t = s[0] dep_t = s[1] if arr_t is None or dep_t is None: continue arr_x = int(arr_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset dep_x = int(dep_t/3600.0 * self._hour_grid) - self._hour_grid * self._offset tmpstrs.append("%s,%s " % (int(arr_x+20), int(stations[i]+20))) tmpstrs.append("%s,%s " % (int(dep_x+20), int(stations[i]+20))) tmpstrs.append('" />') return "".join(tmpstrs)
[ "def", "_DrawTrips", "(", "self", ",", "triplist", ",", "colpar", "=", "\"\"", ")", ":", "stations", "=", "[", "]", "if", "not", "self", ".", "_stations", "and", "triplist", ":", "self", ".", "_stations", "=", "self", ".", "_CalculateYLines", "(", "sel...
Generates svg polylines for each transit trip. Args: # Class Trip is defined in transitfeed.py [Trip, Trip, ...] Returns: # A string containing a polyline tag for each trip ' <polyline class="T" stroke="#336633" points="433,0 ...'
[ "Generates", "svg", "polylines", "for", "each", "transit", "trip", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L298-L354
train
219,902
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph._Uniform
def _Uniform(self, triplist): """Fallback to assuming uniform distance between stations""" # This should not be neseccary, but we are in fallback mode longest = max([len(t.GetTimeStops()) for t in triplist]) return [100] * longest
python
def _Uniform(self, triplist): """Fallback to assuming uniform distance between stations""" # This should not be neseccary, but we are in fallback mode longest = max([len(t.GetTimeStops()) for t in triplist]) return [100] * longest
[ "def", "_Uniform", "(", "self", ",", "triplist", ")", ":", "# This should not be neseccary, but we are in fallback mode", "longest", "=", "max", "(", "[", "len", "(", "t", ".", "GetTimeStops", "(", ")", ")", "for", "t", "in", "triplist", "]", ")", "return", ...
Fallback to assuming uniform distance between stations
[ "Fallback", "to", "assuming", "uniform", "distance", "between", "stations" ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L356-L360
train
219,903
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph._DrawHours
def _DrawHours(self): """Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..." """ tmpstrs = [] for i in range(0, self._gwidth, self._min_grid): if i % self._hour_grid == 0: tmpstrs.append('<polyline class="FullHour" points="%d,%d, %d,%d" />' \ % (i + .5 + 20, 20, i + .5 + 20, self._gheight)) tmpstrs.append('<text class="Label" x="%d" y="%d">%d</text>' % (i + 20, 20, (i / self._hour_grid + self._offset) % 24)) else: tmpstrs.append('<polyline class="SubHour" points="%d,%d,%d,%d" />' \ % (i + .5 + 20, 20, i + .5 + 20, self._gheight)) return "".join(tmpstrs)
python
def _DrawHours(self): """Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..." """ tmpstrs = [] for i in range(0, self._gwidth, self._min_grid): if i % self._hour_grid == 0: tmpstrs.append('<polyline class="FullHour" points="%d,%d, %d,%d" />' \ % (i + .5 + 20, 20, i + .5 + 20, self._gheight)) tmpstrs.append('<text class="Label" x="%d" y="%d">%d</text>' % (i + 20, 20, (i / self._hour_grid + self._offset) % 24)) else: tmpstrs.append('<polyline class="SubHour" points="%d,%d,%d,%d" />' \ % (i + .5 + 20, 20, i + .5 + 20, self._gheight)) return "".join(tmpstrs)
[ "def", "_DrawHours", "(", "self", ")", ":", "tmpstrs", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "self", ".", "_gwidth", ",", "self", ".", "_min_grid", ")", ":", "if", "i", "%", "self", ".", "_hour_grid", "==", "0", ":", "tmpstrs",...
Generates svg to show a vertical hour and sub-hour grid Returns: # A string containing a polyline tag for each grid line " <polyline class="FullHour" points="20,0 ..."
[ "Generates", "svg", "to", "show", "a", "vertical", "hour", "and", "sub", "-", "hour", "grid" ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L380-L398
train
219,904
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph.AddStationDecoration
def AddStationDecoration(self, index, color="#f00"): """Flushes existing decorations and highlights the given station-line. Args: # Integer, index of stop to be highlighted. index: 4 # An optional string with a html color code color: "#fff" """ tmpstr = str() num_stations = len(self._stations) ind = int(index) if self._stations: if 0<ind<num_stations: y = self._stations[ind] tmpstr = '<polyline class="Dec" stroke="%s" points="%s,%s,%s,%s" />' \ % (color, 20, 20+y+.5, self._gwidth+20, 20+y+.5) self._decorators.append(tmpstr)
python
def AddStationDecoration(self, index, color="#f00"): """Flushes existing decorations and highlights the given station-line. Args: # Integer, index of stop to be highlighted. index: 4 # An optional string with a html color code color: "#fff" """ tmpstr = str() num_stations = len(self._stations) ind = int(index) if self._stations: if 0<ind<num_stations: y = self._stations[ind] tmpstr = '<polyline class="Dec" stroke="%s" points="%s,%s,%s,%s" />' \ % (color, 20, 20+y+.5, self._gwidth+20, 20+y+.5) self._decorators.append(tmpstr)
[ "def", "AddStationDecoration", "(", "self", ",", "index", ",", "color", "=", "\"#f00\"", ")", ":", "tmpstr", "=", "str", "(", ")", "num_stations", "=", "len", "(", "self", ".", "_stations", ")", "ind", "=", "int", "(", "index", ")", "if", "self", "."...
Flushes existing decorations and highlights the given station-line. Args: # Integer, index of stop to be highlighted. index: 4 # An optional string with a html color code color: "#fff"
[ "Flushes", "existing", "decorations", "and", "highlights", "the", "given", "station", "-", "line", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L400-L417
train
219,905
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph.AddTripDecoration
def AddTripDecoration(self, triplist, color="#f00"): """Flushes existing decorations and highlights the given trips. Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # An optional string with a html color code color: "#fff" """ tmpstr = self._DrawTrips(triplist,color) self._decorators.append(tmpstr)
python
def AddTripDecoration(self, triplist, color="#f00"): """Flushes existing decorations and highlights the given trips. Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # An optional string with a html color code color: "#fff" """ tmpstr = self._DrawTrips(triplist,color) self._decorators.append(tmpstr)
[ "def", "AddTripDecoration", "(", "self", ",", "triplist", ",", "color", "=", "\"#f00\"", ")", ":", "tmpstr", "=", "self", ".", "_DrawTrips", "(", "triplist", ",", "color", ")", "self", ".", "_decorators", ".", "append", "(", "tmpstr", ")" ]
Flushes existing decorations and highlights the given trips. Args: # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] # An optional string with a html color code color: "#fff"
[ "Flushes", "existing", "decorations", "and", "highlights", "the", "given", "trips", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L419-L429
train
219,906
google/transitfeed
gtfsscheduleviewer/marey_graph.py
MareyGraph.ChangeScaleFactor
def ChangeScaleFactor(self, newfactor): """Changes the zoom of the graph manually. 1.0 is the original canvas size. Args: # float value between 0.0 and 5.0 newfactor: 0.7 """ if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM: self._zoomfactor = newfactor
python
def ChangeScaleFactor(self, newfactor): """Changes the zoom of the graph manually. 1.0 is the original canvas size. Args: # float value between 0.0 and 5.0 newfactor: 0.7 """ if float(newfactor) > 0 and float(newfactor) < self._MAX_ZOOM: self._zoomfactor = newfactor
[ "def", "ChangeScaleFactor", "(", "self", ",", "newfactor", ")", ":", "if", "float", "(", "newfactor", ")", ">", "0", "and", "float", "(", "newfactor", ")", "<", "self", ".", "_MAX_ZOOM", ":", "self", ".", "_zoomfactor", "=", "newfactor" ]
Changes the zoom of the graph manually. 1.0 is the original canvas size. Args: # float value between 0.0 and 5.0 newfactor: 0.7
[ "Changes", "the", "zoom", "of", "the", "graph", "manually", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/gtfsscheduleviewer/marey_graph.py#L431-L441
train
219,907
google/transitfeed
kmlwriter.py
KMLWriter._CreateFolder
def _CreateFolder(self, parent, name, visible=True, description=None): """Create a KML Folder element. Args: parent: The parent ElementTree.Element instance. name: The folder name as a string. visible: Whether the folder is initially visible or not. description: A description string or None. Returns: The folder ElementTree.Element instance. """ folder = ET.SubElement(parent, 'Folder') name_tag = ET.SubElement(folder, 'name') name_tag.text = name if description is not None: desc_tag = ET.SubElement(folder, 'description') desc_tag.text = description if not visible: visibility = ET.SubElement(folder, 'visibility') visibility.text = '0' return folder
python
def _CreateFolder(self, parent, name, visible=True, description=None): """Create a KML Folder element. Args: parent: The parent ElementTree.Element instance. name: The folder name as a string. visible: Whether the folder is initially visible or not. description: A description string or None. Returns: The folder ElementTree.Element instance. """ folder = ET.SubElement(parent, 'Folder') name_tag = ET.SubElement(folder, 'name') name_tag.text = name if description is not None: desc_tag = ET.SubElement(folder, 'description') desc_tag.text = description if not visible: visibility = ET.SubElement(folder, 'visibility') visibility.text = '0' return folder
[ "def", "_CreateFolder", "(", "self", ",", "parent", ",", "name", ",", "visible", "=", "True", ",", "description", "=", "None", ")", ":", "folder", "=", "ET", ".", "SubElement", "(", "parent", ",", "'Folder'", ")", "name_tag", "=", "ET", ".", "SubElemen...
Create a KML Folder element. Args: parent: The parent ElementTree.Element instance. name: The folder name as a string. visible: Whether the folder is initially visible or not. description: A description string or None. Returns: The folder ElementTree.Element instance.
[ "Create", "a", "KML", "Folder", "element", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L132-L153
train
219,908
google/transitfeed
kmlwriter.py
KMLWriter._CreateStyleForRoute
def _CreateStyleForRoute(self, doc, route): """Create a KML Style element for the route. The style sets the line colour if the route colour is specified. The line thickness is set depending on the vehicle type. Args: doc: The KML Document ElementTree.Element instance. route: The transitfeed.Route to create the style for. Returns: The id of the style as a string. """ style_id = 'route_%s' % route.route_id style = ET.SubElement(doc, 'Style', {'id': style_id}) linestyle = ET.SubElement(style, 'LineStyle') width = ET.SubElement(linestyle, 'width') type_to_width = {0: '3', # Tram 1: '3', # Subway 2: '5', # Rail 3: '1'} # Bus width.text = type_to_width.get(route.route_type, '1') if route.route_color: color = ET.SubElement(linestyle, 'color') red = route.route_color[0:2].lower() green = route.route_color[2:4].lower() blue = route.route_color[4:6].lower() color.text = 'ff%s%s%s' % (blue, green, red) return style_id
python
def _CreateStyleForRoute(self, doc, route): """Create a KML Style element for the route. The style sets the line colour if the route colour is specified. The line thickness is set depending on the vehicle type. Args: doc: The KML Document ElementTree.Element instance. route: The transitfeed.Route to create the style for. Returns: The id of the style as a string. """ style_id = 'route_%s' % route.route_id style = ET.SubElement(doc, 'Style', {'id': style_id}) linestyle = ET.SubElement(style, 'LineStyle') width = ET.SubElement(linestyle, 'width') type_to_width = {0: '3', # Tram 1: '3', # Subway 2: '5', # Rail 3: '1'} # Bus width.text = type_to_width.get(route.route_type, '1') if route.route_color: color = ET.SubElement(linestyle, 'color') red = route.route_color[0:2].lower() green = route.route_color[2:4].lower() blue = route.route_color[4:6].lower() color.text = 'ff%s%s%s' % (blue, green, red) return style_id
[ "def", "_CreateStyleForRoute", "(", "self", ",", "doc", ",", "route", ")", ":", "style_id", "=", "'route_%s'", "%", "route", ".", "route_id", "style", "=", "ET", ".", "SubElement", "(", "doc", ",", "'Style'", ",", "{", "'id'", ":", "style_id", "}", ")"...
Create a KML Style element for the route. The style sets the line colour if the route colour is specified. The line thickness is set depending on the vehicle type. Args: doc: The KML Document ElementTree.Element instance. route: The transitfeed.Route to create the style for. Returns: The id of the style as a string.
[ "Create", "a", "KML", "Style", "element", "for", "the", "route", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L155-L183
train
219,909
google/transitfeed
kmlwriter.py
KMLWriter._CreatePlacemark
def _CreatePlacemark(self, parent, name, style_id=None, visible=True, description=None): """Create a KML Placemark element. Args: parent: The parent ElementTree.Element instance. name: The placemark name as a string. style_id: If not None, the id of a style to use for the placemark. visible: Whether the placemark is initially visible or not. description: A description string or None. Returns: The placemark ElementTree.Element instance. """ placemark = ET.SubElement(parent, 'Placemark') placemark_name = ET.SubElement(placemark, 'name') placemark_name.text = name if description is not None: desc_tag = ET.SubElement(placemark, 'description') desc_tag.text = description if style_id is not None: styleurl = ET.SubElement(placemark, 'styleUrl') styleurl.text = '#%s' % style_id if not visible: visibility = ET.SubElement(placemark, 'visibility') visibility.text = '0' return placemark
python
def _CreatePlacemark(self, parent, name, style_id=None, visible=True, description=None): """Create a KML Placemark element. Args: parent: The parent ElementTree.Element instance. name: The placemark name as a string. style_id: If not None, the id of a style to use for the placemark. visible: Whether the placemark is initially visible or not. description: A description string or None. Returns: The placemark ElementTree.Element instance. """ placemark = ET.SubElement(parent, 'Placemark') placemark_name = ET.SubElement(placemark, 'name') placemark_name.text = name if description is not None: desc_tag = ET.SubElement(placemark, 'description') desc_tag.text = description if style_id is not None: styleurl = ET.SubElement(placemark, 'styleUrl') styleurl.text = '#%s' % style_id if not visible: visibility = ET.SubElement(placemark, 'visibility') visibility.text = '0' return placemark
[ "def", "_CreatePlacemark", "(", "self", ",", "parent", ",", "name", ",", "style_id", "=", "None", ",", "visible", "=", "True", ",", "description", "=", "None", ")", ":", "placemark", "=", "ET", ".", "SubElement", "(", "parent", ",", "'Placemark'", ")", ...
Create a KML Placemark element. Args: parent: The parent ElementTree.Element instance. name: The placemark name as a string. style_id: If not None, the id of a style to use for the placemark. visible: Whether the placemark is initially visible or not. description: A description string or None. Returns: The placemark ElementTree.Element instance.
[ "Create", "a", "KML", "Placemark", "element", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L185-L211
train
219,910
google/transitfeed
kmlwriter.py
KMLWriter._CreateLineString
def _CreateLineString(self, parent, coordinate_list): """Create a KML LineString element. The points of the string are given in coordinate_list. Every element of coordinate_list should be one of a tuple (longitude, latitude) or a tuple (longitude, latitude, altitude). Args: parent: The parent ElementTree.Element instance. coordinate_list: The list of coordinates. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty. """ if not coordinate_list: return None linestring = ET.SubElement(parent, 'LineString') tessellate = ET.SubElement(linestring, 'tessellate') tessellate.text = '1' if len(coordinate_list[0]) == 3: altitude_mode = ET.SubElement(linestring, 'altitudeMode') altitude_mode.text = 'absolute' coordinates = ET.SubElement(linestring, 'coordinates') if len(coordinate_list[0]) == 3: coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list] else: coordinate_str_list = ['%f,%f' % t for t in coordinate_list] coordinates.text = ' '.join(coordinate_str_list) return linestring
python
def _CreateLineString(self, parent, coordinate_list): """Create a KML LineString element. The points of the string are given in coordinate_list. Every element of coordinate_list should be one of a tuple (longitude, latitude) or a tuple (longitude, latitude, altitude). Args: parent: The parent ElementTree.Element instance. coordinate_list: The list of coordinates. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty. """ if not coordinate_list: return None linestring = ET.SubElement(parent, 'LineString') tessellate = ET.SubElement(linestring, 'tessellate') tessellate.text = '1' if len(coordinate_list[0]) == 3: altitude_mode = ET.SubElement(linestring, 'altitudeMode') altitude_mode.text = 'absolute' coordinates = ET.SubElement(linestring, 'coordinates') if len(coordinate_list[0]) == 3: coordinate_str_list = ['%f,%f,%f' % t for t in coordinate_list] else: coordinate_str_list = ['%f,%f' % t for t in coordinate_list] coordinates.text = ' '.join(coordinate_str_list) return linestring
[ "def", "_CreateLineString", "(", "self", ",", "parent", ",", "coordinate_list", ")", ":", "if", "not", "coordinate_list", ":", "return", "None", "linestring", "=", "ET", ".", "SubElement", "(", "parent", ",", "'LineString'", ")", "tessellate", "=", "ET", "."...
Create a KML LineString element. The points of the string are given in coordinate_list. Every element of coordinate_list should be one of a tuple (longitude, latitude) or a tuple (longitude, latitude, altitude). Args: parent: The parent ElementTree.Element instance. coordinate_list: The list of coordinates. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty.
[ "Create", "a", "KML", "LineString", "element", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L213-L242
train
219,911
google/transitfeed
kmlwriter.py
KMLWriter._CreateLineStringForShape
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty. """ coordinate_list = [(longitude, latitude) for (latitude, longitude, distance) in shape.points] return self._CreateLineString(parent, coordinate_list)
python
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty. """ coordinate_list = [(longitude, latitude) for (latitude, longitude, distance) in shape.points] return self._CreateLineString(parent, coordinate_list)
[ "def", "_CreateLineStringForShape", "(", "self", ",", "parent", ",", "shape", ")", ":", "coordinate_list", "=", "[", "(", "longitude", ",", "latitude", ")", "for", "(", "latitude", ",", "longitude", ",", "distance", ")", "in", "shape", ".", "points", "]", ...
Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is empty.
[ "Create", "a", "KML", "LineString", "using", "coordinates", "from", "a", "shape", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L244-L257
train
219,912
google/transitfeed
kmlwriter.py
KMLWriter._CreateStopsFolder
def _CreateStopsFolder(self, schedule, doc): """Create a KML Folder containing placemarks for each stop in the schedule. If there are no stops in the schedule then no folder is created. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None if there are no stops. """ if not schedule.GetStopList(): return None stop_folder = self._CreateFolder(doc, 'Stops') stop_folder_selection = self._StopFolderSelectionMethod(stop_folder) stop_style_selection = self._StopStyleSelectionMethod(doc) stops = list(schedule.GetStopList()) stops.sort(key=lambda x: x.stop_name) for stop in stops: (folder, pathway_folder) = stop_folder_selection(stop) (style_id, pathway_style_id) = stop_style_selection(stop) self._CreateStopPlacemark(folder, stop, style_id) if (self.show_stop_hierarchy and stop.location_type != transitfeed.Stop.LOCATION_TYPE_STATION and stop.parent_station and stop.parent_station in schedule.stops): placemark = self._CreatePlacemark( pathway_folder, stop.stop_name, pathway_style_id) parent_station = schedule.stops[stop.parent_station] coordinates = [(stop.stop_lon, stop.stop_lat), (parent_station.stop_lon, parent_station.stop_lat)] self._CreateLineString(placemark, coordinates) return stop_folder
python
def _CreateStopsFolder(self, schedule, doc): """Create a KML Folder containing placemarks for each stop in the schedule. If there are no stops in the schedule then no folder is created. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None if there are no stops. """ if not schedule.GetStopList(): return None stop_folder = self._CreateFolder(doc, 'Stops') stop_folder_selection = self._StopFolderSelectionMethod(stop_folder) stop_style_selection = self._StopStyleSelectionMethod(doc) stops = list(schedule.GetStopList()) stops.sort(key=lambda x: x.stop_name) for stop in stops: (folder, pathway_folder) = stop_folder_selection(stop) (style_id, pathway_style_id) = stop_style_selection(stop) self._CreateStopPlacemark(folder, stop, style_id) if (self.show_stop_hierarchy and stop.location_type != transitfeed.Stop.LOCATION_TYPE_STATION and stop.parent_station and stop.parent_station in schedule.stops): placemark = self._CreatePlacemark( pathway_folder, stop.stop_name, pathway_style_id) parent_station = schedule.stops[stop.parent_station] coordinates = [(stop.stop_lon, stop.stop_lat), (parent_station.stop_lon, parent_station.stop_lat)] self._CreateLineString(placemark, coordinates) return stop_folder
[ "def", "_CreateStopsFolder", "(", "self", ",", "schedule", ",", "doc", ")", ":", "if", "not", "schedule", ".", "GetStopList", "(", ")", ":", "return", "None", "stop_folder", "=", "self", ".", "_CreateFolder", "(", "doc", ",", "'Stops'", ")", "stop_folder_s...
Create a KML Folder containing placemarks for each stop in the schedule. If there are no stops in the schedule then no folder is created. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None if there are no stops.
[ "Create", "a", "KML", "Folder", "containing", "placemarks", "for", "each", "stop", "in", "the", "schedule", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L259-L291
train
219,913
google/transitfeed
kmlwriter.py
KMLWriter._StopFolderSelectionMethod
def _StopFolderSelectionMethod(self, stop_folder): """Create a method to determine which KML folder a stop should go in. Args: stop_folder: the parent folder element for all stops. Returns: A function that should accept a Stop argument and return a tuple of (stop KML folder, pathways KML folder). Given a Stop, we need to determine which folder the stop should go in. In the most basic case, that's the root Stops folder. However, if show_stop_hierarchy is enabled, we put a stop in a separate sub-folder depending on if the stop is a station, a platform, an entrance, or just a plain-old stand-alone stop. This method returns a function that is used to pick which folder a stop stop should go in. It also optionally returns a folder where any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station) should be added. """ if not self.show_stop_hierarchy: return lambda stop: (stop_folder, None) # Create the various sub-folders for showing the stop hierarchy station_folder = self._CreateFolder(stop_folder, 'Stations') platform_folder = self._CreateFolder(stop_folder, 'Platforms') platform_connections = self._CreateFolder(platform_folder, 'Connections') entrance_folder = self._CreateFolder(stop_folder, 'Entrances') entrance_connections = self._CreateFolder(entrance_folder, 'Connections') standalone_folder = self._CreateFolder(stop_folder, 'Stand-Alone') def FolderSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return (station_folder, None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return (entrance_folder, entrance_connections) elif stop.parent_station: return (platform_folder, platform_connections) return (standalone_folder, None) return FolderSelectionMethod
python
def _StopFolderSelectionMethod(self, stop_folder): """Create a method to determine which KML folder a stop should go in. Args: stop_folder: the parent folder element for all stops. Returns: A function that should accept a Stop argument and return a tuple of (stop KML folder, pathways KML folder). Given a Stop, we need to determine which folder the stop should go in. In the most basic case, that's the root Stops folder. However, if show_stop_hierarchy is enabled, we put a stop in a separate sub-folder depending on if the stop is a station, a platform, an entrance, or just a plain-old stand-alone stop. This method returns a function that is used to pick which folder a stop stop should go in. It also optionally returns a folder where any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station) should be added. """ if not self.show_stop_hierarchy: return lambda stop: (stop_folder, None) # Create the various sub-folders for showing the stop hierarchy station_folder = self._CreateFolder(stop_folder, 'Stations') platform_folder = self._CreateFolder(stop_folder, 'Platforms') platform_connections = self._CreateFolder(platform_folder, 'Connections') entrance_folder = self._CreateFolder(stop_folder, 'Entrances') entrance_connections = self._CreateFolder(entrance_folder, 'Connections') standalone_folder = self._CreateFolder(stop_folder, 'Stand-Alone') def FolderSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return (station_folder, None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return (entrance_folder, entrance_connections) elif stop.parent_station: return (platform_folder, platform_connections) return (standalone_folder, None) return FolderSelectionMethod
[ "def", "_StopFolderSelectionMethod", "(", "self", ",", "stop_folder", ")", ":", "if", "not", "self", ".", "show_stop_hierarchy", ":", "return", "lambda", "stop", ":", "(", "stop_folder", ",", "None", ")", "# Create the various sub-folders for showing the stop hierarchy"...
Create a method to determine which KML folder a stop should go in. Args: stop_folder: the parent folder element for all stops. Returns: A function that should accept a Stop argument and return a tuple of (stop KML folder, pathways KML folder). Given a Stop, we need to determine which folder the stop should go in. In the most basic case, that's the root Stops folder. However, if show_stop_hierarchy is enabled, we put a stop in a separate sub-folder depending on if the stop is a station, a platform, an entrance, or just a plain-old stand-alone stop. This method returns a function that is used to pick which folder a stop stop should go in. It also optionally returns a folder where any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station) should be added.
[ "Create", "a", "method", "to", "determine", "which", "KML", "folder", "a", "stop", "should", "go", "in", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L293-L332
train
219,914
google/transitfeed
kmlwriter.py
KMLWriter._StopStyleSelectionMethod
def _StopStyleSelectionMethod(self, doc): """Create a method to determine which style to apply to a stop placemark. Args: doc: the KML document. Returns: A function that should accept a Stop argument and return a tuple of (stop placemark style id, pathway placemark style id). Either style id can be None, indicating no style should be set. Given a Stop, we need to determine what KML style to apply to the stops' placemark. In the most basic case, no styling is applied. However, if show_stop_hierarchy is enabled, we style each type of stop differently depending on if the stop is a station, platform, entrance, etc. This method returns a function that is used to pick which style id should be associated with a stop placemark, or None if no style should be applied. It also optionally returns a style id to associate with any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station). """ if not self.show_stop_hierarchy: return lambda stop: (None, None) # Create the various styles for showing the stop hierarchy self._CreateStyle( doc, 'stop_entrance', {'IconStyle': {'color': 'ff0000ff'}}) self._CreateStyle( doc, 'entrance_connection', {'LineStyle': {'color': 'ff0000ff', 'width': '2'}}) self._CreateStyle( doc, 'stop_platform', {'IconStyle': {'color': 'ffff0000'}}) self._CreateStyle( doc, 'platform_connection', {'LineStyle': {'color': 'ffff0000', 'width': '2'}}) self._CreateStyle( doc, 'stop_standalone', {'IconStyle': {'color': 'ff00ff00'}}) def StyleSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return ('stop_station', None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return ('stop_entrance', 'entrance_connection') elif stop.parent_station: return ('stop_platform', 'platform_connection') return ('stop_standalone', None) return StyleSelectionMethod
python
def _StopStyleSelectionMethod(self, doc): """Create a method to determine which style to apply to a stop placemark. Args: doc: the KML document. Returns: A function that should accept a Stop argument and return a tuple of (stop placemark style id, pathway placemark style id). Either style id can be None, indicating no style should be set. Given a Stop, we need to determine what KML style to apply to the stops' placemark. In the most basic case, no styling is applied. However, if show_stop_hierarchy is enabled, we style each type of stop differently depending on if the stop is a station, platform, entrance, etc. This method returns a function that is used to pick which style id should be associated with a stop placemark, or None if no style should be applied. It also optionally returns a style id to associate with any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station). """ if not self.show_stop_hierarchy: return lambda stop: (None, None) # Create the various styles for showing the stop hierarchy self._CreateStyle( doc, 'stop_entrance', {'IconStyle': {'color': 'ff0000ff'}}) self._CreateStyle( doc, 'entrance_connection', {'LineStyle': {'color': 'ff0000ff', 'width': '2'}}) self._CreateStyle( doc, 'stop_platform', {'IconStyle': {'color': 'ffff0000'}}) self._CreateStyle( doc, 'platform_connection', {'LineStyle': {'color': 'ffff0000', 'width': '2'}}) self._CreateStyle( doc, 'stop_standalone', {'IconStyle': {'color': 'ff00ff00'}}) def StyleSelectionMethod(stop): if stop.location_type == transitfeed.Stop.LOCATION_TYPE_STATION: return ('stop_station', None) elif stop.location_type == googletransit.Stop.LOCATION_TYPE_ENTRANCE: return ('stop_entrance', 'entrance_connection') elif stop.parent_station: return ('stop_platform', 'platform_connection') return ('stop_standalone', None) return StyleSelectionMethod
[ "def", "_StopStyleSelectionMethod", "(", "self", ",", "doc", ")", ":", "if", "not", "self", ".", "show_stop_hierarchy", ":", "return", "lambda", "stop", ":", "(", "None", ",", "None", ")", "# Create the various styles for showing the stop hierarchy", "self", ".", ...
Create a method to determine which style to apply to a stop placemark. Args: doc: the KML document. Returns: A function that should accept a Stop argument and return a tuple of (stop placemark style id, pathway placemark style id). Either style id can be None, indicating no style should be set. Given a Stop, we need to determine what KML style to apply to the stops' placemark. In the most basic case, no styling is applied. However, if show_stop_hierarchy is enabled, we style each type of stop differently depending on if the stop is a station, platform, entrance, etc. This method returns a function that is used to pick which style id should be associated with a stop placemark, or None if no style should be applied. It also optionally returns a style id to associate with any line-string connections associated with a stop (eg. to show the pathway between an entrance and a station).
[ "Create", "a", "method", "to", "determine", "which", "style", "to", "apply", "to", "a", "stop", "placemark", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L334-L383
train
219,915
google/transitfeed
kmlwriter.py
KMLWriter._CreateRoutePatternsFolder
def _CreateRoutePatternsFolder(self, parent, route, style_id=None, visible=True): """Create a KML Folder containing placemarks for each pattern in the route. A pattern is a sequence of stops used by one of the trips in the route. If there are not patterns for the route then no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the folder is initially visible or not. Returns: The Folder ElementTree.Element instance or None if there are no patterns. """ pattern_id_to_trips = route.GetPatternIdTripDict() if not pattern_id_to_trips: return None # sort by number of trips using the pattern pattern_trips = pattern_id_to_trips.values() pattern_trips.sort(lambda a, b: cmp(len(b), len(a))) folder = self._CreateFolder(parent, 'Patterns', visible) for n, trips in enumerate(pattern_trips): trip_ids = [trip.trip_id for trip in trips] name = 'Pattern %d (trips: %d)' % (n+1, len(trips)) description = 'Trips using this pattern (%d in total): %s' % ( len(trips), ', '.join(trip_ids)) placemark = self._CreatePlacemark(folder, name, style_id, visible, description) coordinates = [(stop.stop_lon, stop.stop_lat) for stop in trips[0].GetPattern()] self._CreateLineString(placemark, coordinates) return folder
python
def _CreateRoutePatternsFolder(self, parent, route, style_id=None, visible=True): """Create a KML Folder containing placemarks for each pattern in the route. A pattern is a sequence of stops used by one of the trips in the route. If there are not patterns for the route then no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the folder is initially visible or not. Returns: The Folder ElementTree.Element instance or None if there are no patterns. """ pattern_id_to_trips = route.GetPatternIdTripDict() if not pattern_id_to_trips: return None # sort by number of trips using the pattern pattern_trips = pattern_id_to_trips.values() pattern_trips.sort(lambda a, b: cmp(len(b), len(a))) folder = self._CreateFolder(parent, 'Patterns', visible) for n, trips in enumerate(pattern_trips): trip_ids = [trip.trip_id for trip in trips] name = 'Pattern %d (trips: %d)' % (n+1, len(trips)) description = 'Trips using this pattern (%d in total): %s' % ( len(trips), ', '.join(trip_ids)) placemark = self._CreatePlacemark(folder, name, style_id, visible, description) coordinates = [(stop.stop_lon, stop.stop_lat) for stop in trips[0].GetPattern()] self._CreateLineString(placemark, coordinates) return folder
[ "def", "_CreateRoutePatternsFolder", "(", "self", ",", "parent", ",", "route", ",", "style_id", "=", "None", ",", "visible", "=", "True", ")", ":", "pattern_id_to_trips", "=", "route", ".", "GetPatternIdTripDict", "(", ")", "if", "not", "pattern_id_to_trips", ...
Create a KML Folder containing placemarks for each pattern in the route. A pattern is a sequence of stops used by one of the trips in the route. If there are not patterns for the route then no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the folder is initially visible or not. Returns: The Folder ElementTree.Element instance or None if there are no patterns.
[ "Create", "a", "KML", "Folder", "containing", "placemarks", "for", "each", "pattern", "in", "the", "route", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L438-L475
train
219,916
google/transitfeed
kmlwriter.py
KMLWriter._CreateRouteShapesFolder
def _CreateRouteShapesFolder(self, schedule, parent, route, style_id=None, visible=True): """Create a KML Folder for the shapes of a route. The folder contains a placemark for each shape referenced by a trip in the route. If there are no such shapes, no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the placemark is initially visible or not. Returns: The Folder ElementTree.Element instance or None. """ shape_id_to_trips = {} for trip in route.trips: if trip.shape_id: shape_id_to_trips.setdefault(trip.shape_id, []).append(trip) if not shape_id_to_trips: return None # sort by the number of trips using the shape shape_id_to_trips_items = shape_id_to_trips.items() shape_id_to_trips_items.sort(lambda a, b: cmp(len(b[1]), len(a[1]))) folder = self._CreateFolder(parent, 'Shapes', visible) for shape_id, trips in shape_id_to_trips_items: trip_ids = [trip.trip_id for trip in trips] name = '%s (trips: %d)' % (shape_id, len(trips)) description = 'Trips using this shape (%d in total): %s' % ( len(trips), ', '.join(trip_ids)) placemark = self._CreatePlacemark(folder, name, style_id, visible, description) self._CreateLineStringForShape(placemark, schedule.GetShape(shape_id)) return folder
python
def _CreateRouteShapesFolder(self, schedule, parent, route, style_id=None, visible=True): """Create a KML Folder for the shapes of a route. The folder contains a placemark for each shape referenced by a trip in the route. If there are no such shapes, no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the placemark is initially visible or not. Returns: The Folder ElementTree.Element instance or None. """ shape_id_to_trips = {} for trip in route.trips: if trip.shape_id: shape_id_to_trips.setdefault(trip.shape_id, []).append(trip) if not shape_id_to_trips: return None # sort by the number of trips using the shape shape_id_to_trips_items = shape_id_to_trips.items() shape_id_to_trips_items.sort(lambda a, b: cmp(len(b[1]), len(a[1]))) folder = self._CreateFolder(parent, 'Shapes', visible) for shape_id, trips in shape_id_to_trips_items: trip_ids = [trip.trip_id for trip in trips] name = '%s (trips: %d)' % (shape_id, len(trips)) description = 'Trips using this shape (%d in total): %s' % ( len(trips), ', '.join(trip_ids)) placemark = self._CreatePlacemark(folder, name, style_id, visible, description) self._CreateLineStringForShape(placemark, schedule.GetShape(shape_id)) return folder
[ "def", "_CreateRouteShapesFolder", "(", "self", ",", "schedule", ",", "parent", ",", "route", ",", "style_id", "=", "None", ",", "visible", "=", "True", ")", ":", "shape_id_to_trips", "=", "{", "}", "for", "trip", "in", "route", ".", "trips", ":", "if", ...
Create a KML Folder for the shapes of a route. The folder contains a placemark for each shape referenced by a trip in the route. If there are no such shapes, no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: The id of a style to use if not None. visible: Whether the placemark is initially visible or not. Returns: The Folder ElementTree.Element instance or None.
[ "Create", "a", "KML", "Folder", "for", "the", "shapes", "of", "a", "route", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L477-L515
train
219,917
google/transitfeed
kmlwriter.py
KMLWriter._CreateRouteTripsFolder
def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None): """Create a KML Folder containing all the trips in the route. The folder contains a placemark for each of these trips. If there are no trips in the route, no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: A style id string for the placemarks or None. Returns: The Folder ElementTree.Element instance or None. """ if not route.trips: return None trips = list(route.trips) trips.sort(key=lambda x: x.trip_id) trips_folder = self._CreateFolder(parent, 'Trips', visible=False) for trip in trips: if (self.date_filter and not trip.service_period.IsActiveOn(self.date_filter)): continue if trip.trip_headsign: description = 'Headsign: %s' % trip.trip_headsign else: description = None coordinate_list = [] for secs, stoptime, tp in trip.GetTimeInterpolatedStops(): if self.altitude_per_sec > 0: coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat, (secs - 3600 * 4) * self.altitude_per_sec)) else: coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat)) placemark = self._CreatePlacemark(trips_folder, trip.trip_id, style_id=style_id, visible=False, description=description) self._CreateLineString(placemark, coordinate_list) return trips_folder
python
def _CreateRouteTripsFolder(self, parent, route, style_id=None, schedule=None): """Create a KML Folder containing all the trips in the route. The folder contains a placemark for each of these trips. If there are no trips in the route, no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: A style id string for the placemarks or None. Returns: The Folder ElementTree.Element instance or None. """ if not route.trips: return None trips = list(route.trips) trips.sort(key=lambda x: x.trip_id) trips_folder = self._CreateFolder(parent, 'Trips', visible=False) for trip in trips: if (self.date_filter and not trip.service_period.IsActiveOn(self.date_filter)): continue if trip.trip_headsign: description = 'Headsign: %s' % trip.trip_headsign else: description = None coordinate_list = [] for secs, stoptime, tp in trip.GetTimeInterpolatedStops(): if self.altitude_per_sec > 0: coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat, (secs - 3600 * 4) * self.altitude_per_sec)) else: coordinate_list.append((stoptime.stop.stop_lon, stoptime.stop.stop_lat)) placemark = self._CreatePlacemark(trips_folder, trip.trip_id, style_id=style_id, visible=False, description=description) self._CreateLineString(placemark, coordinate_list) return trips_folder
[ "def", "_CreateRouteTripsFolder", "(", "self", ",", "parent", ",", "route", ",", "style_id", "=", "None", ",", "schedule", "=", "None", ")", ":", "if", "not", "route", ".", "trips", ":", "return", "None", "trips", "=", "list", "(", "route", ".", "trips...
Create a KML Folder containing all the trips in the route. The folder contains a placemark for each of these trips. If there are no trips in the route, no folder is created and None is returned. Args: parent: The parent ElementTree.Element instance. route: The transitfeed.Route instance. style_id: A style id string for the placemarks or None. Returns: The Folder ElementTree.Element instance or None.
[ "Create", "a", "KML", "Folder", "containing", "all", "the", "trips", "in", "the", "route", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L517-L560
train
219,918
google/transitfeed
kmlwriter.py
KMLWriter._CreateRoutesFolder
def _CreateRoutesFolder(self, schedule, doc, route_type=None): """Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None. """ def GetRouteName(route): """Return a placemark name for the route. Args: route: The transitfeed.Route instance. Returns: The name as a string. """ name_parts = [] if route.route_short_name: name_parts.append('<b>%s</b>' % route.route_short_name) if route.route_long_name: name_parts.append(route.route_long_name) return ' - '.join(name_parts) or route.route_id def GetRouteDescription(route): """Return a placemark description for the route. Args: route: The transitfeed.Route instance. Returns: The description as a string. """ desc_items = [] if route.route_desc: desc_items.append(route.route_desc) if route.route_url: desc_items.append('Route info page: <a href="%s">%s</a>' % ( route.route_url, route.route_url)) description = '<br/>'.join(desc_items) return description or None routes = [route for route in schedule.GetRouteList() if route_type is None or route.route_type == route_type] if not routes: return None routes.sort(key=lambda x: GetRouteName(x)) if route_type is not None: route_type_names = {0: 'Tram, Streetcar or Light rail', 1: 'Subway or Metro', 2: 'Rail', 3: 'Bus', 4: 'Ferry', 5: 'Cable car', 6: 'Gondola or suspended cable car', 7: 'Funicular'} type_name = route_type_names.get(route_type, str(route_type)) folder_name = 'Routes - %s' % type_name else: folder_name = 'Routes' routes_folder = self._CreateFolder(doc, folder_name, visible=False) for route in routes: style_id = self._CreateStyleForRoute(doc, route) route_folder = self._CreateFolder(routes_folder, GetRouteName(route), description=GetRouteDescription(route)) self._CreateRouteShapesFolder(schedule, route_folder, route, style_id, False) self._CreateRoutePatternsFolder(route_folder, route, style_id, False) if self.show_trips: self._CreateRouteTripsFolder(route_folder, route, style_id, schedule) return routes_folder
python
def _CreateRoutesFolder(self, schedule, doc, route_type=None): """Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None. """ def GetRouteName(route): """Return a placemark name for the route. Args: route: The transitfeed.Route instance. Returns: The name as a string. """ name_parts = [] if route.route_short_name: name_parts.append('<b>%s</b>' % route.route_short_name) if route.route_long_name: name_parts.append(route.route_long_name) return ' - '.join(name_parts) or route.route_id def GetRouteDescription(route): """Return a placemark description for the route. Args: route: The transitfeed.Route instance. Returns: The description as a string. """ desc_items = [] if route.route_desc: desc_items.append(route.route_desc) if route.route_url: desc_items.append('Route info page: <a href="%s">%s</a>' % ( route.route_url, route.route_url)) description = '<br/>'.join(desc_items) return description or None routes = [route for route in schedule.GetRouteList() if route_type is None or route.route_type == route_type] if not routes: return None routes.sort(key=lambda x: GetRouteName(x)) if route_type is not None: route_type_names = {0: 'Tram, Streetcar or Light rail', 1: 'Subway or Metro', 2: 'Rail', 3: 'Bus', 4: 'Ferry', 5: 'Cable car', 6: 'Gondola or suspended cable car', 7: 'Funicular'} type_name = route_type_names.get(route_type, str(route_type)) folder_name = 'Routes - %s' % type_name else: folder_name = 'Routes' routes_folder = self._CreateFolder(doc, folder_name, visible=False) for route in routes: style_id = self._CreateStyleForRoute(doc, route) route_folder = self._CreateFolder(routes_folder, GetRouteName(route), description=GetRouteDescription(route)) self._CreateRouteShapesFolder(schedule, route_folder, route, style_id, False) self._CreateRoutePatternsFolder(route_folder, route, style_id, False) if self.show_trips: self._CreateRouteTripsFolder(route_folder, route, style_id, schedule) return routes_folder
[ "def", "_CreateRoutesFolder", "(", "self", ",", "schedule", ",", "doc", ",", "route_type", "=", "None", ")", ":", "def", "GetRouteName", "(", "route", ")", ":", "\"\"\"Return a placemark name for the route.\n\n Args:\n route: The transitfeed.Route instance.\n\n ...
Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None.
[ "Create", "a", "KML", "Folder", "containing", "routes", "in", "a", "schedule", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L562-L648
train
219,919
google/transitfeed
kmlwriter.py
KMLWriter._CreateShapesFolder
def _CreateShapesFolder(self, schedule, doc): """Create a KML Folder containing all the shapes in a schedule. The folder contains a placemark for each shape. If there are no shapes in the schedule then the folder is not created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None. """ if not schedule.GetShapeList(): return None shapes_folder = self._CreateFolder(doc, 'Shapes') shapes = list(schedule.GetShapeList()) shapes.sort(key=lambda x: x.shape_id) for shape in shapes: placemark = self._CreatePlacemark(shapes_folder, shape.shape_id) self._CreateLineStringForShape(placemark, shape) if self.shape_points: self._CreateShapePointFolder(shapes_folder, shape) return shapes_folder
python
def _CreateShapesFolder(self, schedule, doc): """Create a KML Folder containing all the shapes in a schedule. The folder contains a placemark for each shape. If there are no shapes in the schedule then the folder is not created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None. """ if not schedule.GetShapeList(): return None shapes_folder = self._CreateFolder(doc, 'Shapes') shapes = list(schedule.GetShapeList()) shapes.sort(key=lambda x: x.shape_id) for shape in shapes: placemark = self._CreatePlacemark(shapes_folder, shape.shape_id) self._CreateLineStringForShape(placemark, shape) if self.shape_points: self._CreateShapePointFolder(shapes_folder, shape) return shapes_folder
[ "def", "_CreateShapesFolder", "(", "self", ",", "schedule", ",", "doc", ")", ":", "if", "not", "schedule", ".", "GetShapeList", "(", ")", ":", "return", "None", "shapes_folder", "=", "self", ".", "_CreateFolder", "(", "doc", ",", "'Shapes'", ")", "shapes",...
Create a KML Folder containing all the shapes in a schedule. The folder contains a placemark for each shape. If there are no shapes in the schedule then the folder is not created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. Returns: The Folder ElementTree.Element instance or None.
[ "Create", "a", "KML", "Folder", "containing", "all", "the", "shapes", "in", "a", "schedule", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L650-L673
train
219,920
google/transitfeed
kmlwriter.py
KMLWriter._CreateShapePointFolder
def _CreateShapePointFolder(self, shapes_folder, shape): """Create a KML Folder containing all the shape points in a shape. The folder contains placemarks for each shapepoint. Args: shapes_folder: A KML Shape Folder ElementTree.Element instance shape: The shape to plot. Returns: The Folder ElementTree.Element instance or None. """ folder_name = shape.shape_id + ' Shape Points' folder = self._CreateFolder(shapes_folder, folder_name, visible=False) for (index, (lat, lon, dist)) in enumerate(shape.points): placemark = self._CreatePlacemark(folder, str(index+1)) point = ET.SubElement(placemark, 'Point') coordinates = ET.SubElement(point, 'coordinates') coordinates.text = '%.6f,%.6f' % (lon, lat) return folder
python
def _CreateShapePointFolder(self, shapes_folder, shape): """Create a KML Folder containing all the shape points in a shape. The folder contains placemarks for each shapepoint. Args: shapes_folder: A KML Shape Folder ElementTree.Element instance shape: The shape to plot. Returns: The Folder ElementTree.Element instance or None. """ folder_name = shape.shape_id + ' Shape Points' folder = self._CreateFolder(shapes_folder, folder_name, visible=False) for (index, (lat, lon, dist)) in enumerate(shape.points): placemark = self._CreatePlacemark(folder, str(index+1)) point = ET.SubElement(placemark, 'Point') coordinates = ET.SubElement(point, 'coordinates') coordinates.text = '%.6f,%.6f' % (lon, lat) return folder
[ "def", "_CreateShapePointFolder", "(", "self", ",", "shapes_folder", ",", "shape", ")", ":", "folder_name", "=", "shape", ".", "shape_id", "+", "' Shape Points'", "folder", "=", "self", ".", "_CreateFolder", "(", "shapes_folder", ",", "folder_name", ",", "visibl...
Create a KML Folder containing all the shape points in a shape. The folder contains placemarks for each shapepoint. Args: shapes_folder: A KML Shape Folder ElementTree.Element instance shape: The shape to plot. Returns: The Folder ElementTree.Element instance or None.
[ "Create", "a", "KML", "Folder", "containing", "all", "the", "shape", "points", "in", "a", "shape", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L675-L695
train
219,921
google/transitfeed
kmlwriter.py
KMLWriter.Write
def Write(self, schedule, output_file): """Writes out a feed as KML. Args: schedule: A transitfeed.Schedule object containing the feed to write. output_file: The name of the output KML file, or file object to use. """ # Generate the DOM to write root = ET.Element('kml') root.attrib['xmlns'] = 'http://earth.google.com/kml/2.1' doc = ET.SubElement(root, 'Document') open_tag = ET.SubElement(doc, 'open') open_tag.text = '1' self._CreateStopsFolder(schedule, doc) if self.split_routes: route_types = set() for route in schedule.GetRouteList(): route_types.add(route.route_type) route_types = list(route_types) route_types.sort() for route_type in route_types: self._CreateRoutesFolder(schedule, doc, route_type) else: self._CreateRoutesFolder(schedule, doc) self._CreateShapesFolder(schedule, doc) # Make sure we pretty-print self._SetIndentation(root) # Now write the output if isinstance(output_file, file): output = output_file else: output = open(output_file, 'w') output.write("""<?xml version="1.0" encoding="UTF-8"?>\n""") ET.ElementTree(root).write(output, 'utf-8')
python
def Write(self, schedule, output_file): """Writes out a feed as KML. Args: schedule: A transitfeed.Schedule object containing the feed to write. output_file: The name of the output KML file, or file object to use. """ # Generate the DOM to write root = ET.Element('kml') root.attrib['xmlns'] = 'http://earth.google.com/kml/2.1' doc = ET.SubElement(root, 'Document') open_tag = ET.SubElement(doc, 'open') open_tag.text = '1' self._CreateStopsFolder(schedule, doc) if self.split_routes: route_types = set() for route in schedule.GetRouteList(): route_types.add(route.route_type) route_types = list(route_types) route_types.sort() for route_type in route_types: self._CreateRoutesFolder(schedule, doc, route_type) else: self._CreateRoutesFolder(schedule, doc) self._CreateShapesFolder(schedule, doc) # Make sure we pretty-print self._SetIndentation(root) # Now write the output if isinstance(output_file, file): output = output_file else: output = open(output_file, 'w') output.write("""<?xml version="1.0" encoding="UTF-8"?>\n""") ET.ElementTree(root).write(output, 'utf-8')
[ "def", "Write", "(", "self", ",", "schedule", ",", "output_file", ")", ":", "# Generate the DOM to write", "root", "=", "ET", ".", "Element", "(", "'kml'", ")", "root", ".", "attrib", "[", "'xmlns'", "]", "=", "'http://earth.google.com/kml/2.1'", "doc", "=", ...
Writes out a feed as KML. Args: schedule: A transitfeed.Schedule object containing the feed to write. output_file: The name of the output KML file, or file object to use.
[ "Writes", "out", "a", "feed", "as", "KML", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/kmlwriter.py#L697-L732
train
219,922
google/transitfeed
feedvalidator.py
RunValidationOutputFromOptions
def RunValidationOutputFromOptions(feed, options): """Validate feed, output results per options and return an exit code.""" if options.output.upper() == "CONSOLE": return RunValidationOutputToConsole(feed, options) else: return RunValidationOutputToFilename(feed, options, options.output)
python
def RunValidationOutputFromOptions(feed, options): """Validate feed, output results per options and return an exit code.""" if options.output.upper() == "CONSOLE": return RunValidationOutputToConsole(feed, options) else: return RunValidationOutputToFilename(feed, options, options.output)
[ "def", "RunValidationOutputFromOptions", "(", "feed", ",", "options", ")", ":", "if", "options", ".", "output", ".", "upper", "(", ")", "==", "\"CONSOLE\"", ":", "return", "RunValidationOutputToConsole", "(", "feed", ",", "options", ")", "else", ":", "return",...
Validate feed, output results per options and return an exit code.
[ "Validate", "feed", "output", "results", "per", "options", "and", "return", "an", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L503-L508
train
219,923
google/transitfeed
feedvalidator.py
RunValidationOutputToFilename
def RunValidationOutputToFilename(feed, options, output_filename): """Validate feed, save HTML at output_filename and return an exit code.""" try: output_file = open(output_filename, 'w') exit_code = RunValidationOutputToFile(feed, options, output_file) output_file.close() except IOError as e: print('Error while writing %s: %s' % (output_filename, e)) output_filename = None exit_code = 2 if options.manual_entry and output_filename: webbrowser.open('file://%s' % os.path.abspath(output_filename)) return exit_code
python
def RunValidationOutputToFilename(feed, options, output_filename): """Validate feed, save HTML at output_filename and return an exit code.""" try: output_file = open(output_filename, 'w') exit_code = RunValidationOutputToFile(feed, options, output_file) output_file.close() except IOError as e: print('Error while writing %s: %s' % (output_filename, e)) output_filename = None exit_code = 2 if options.manual_entry and output_filename: webbrowser.open('file://%s' % os.path.abspath(output_filename)) return exit_code
[ "def", "RunValidationOutputToFilename", "(", "feed", ",", "options", ",", "output_filename", ")", ":", "try", ":", "output_file", "=", "open", "(", "output_filename", ",", "'w'", ")", "exit_code", "=", "RunValidationOutputToFile", "(", "feed", ",", "options", ",...
Validate feed, save HTML at output_filename and return an exit code.
[ "Validate", "feed", "save", "HTML", "at", "output_filename", "and", "return", "an", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L511-L525
train
219,924
google/transitfeed
feedvalidator.py
RunValidationOutputToFile
def RunValidationOutputToFile(feed, options, output_file): """Validate feed, write HTML to output_file and return an exit code.""" accumulator = HTMLCountingProblemAccumulator(options.limit_per_type, options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) schedule, exit_code = RunValidation(feed, options, problems) if isinstance(feed, basestring): feed_location = feed else: feed_location = getattr(feed, 'name', repr(feed)) accumulator.WriteOutput(feed_location, output_file, schedule, options.extension) return exit_code
python
def RunValidationOutputToFile(feed, options, output_file): """Validate feed, write HTML to output_file and return an exit code.""" accumulator = HTMLCountingProblemAccumulator(options.limit_per_type, options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) schedule, exit_code = RunValidation(feed, options, problems) if isinstance(feed, basestring): feed_location = feed else: feed_location = getattr(feed, 'name', repr(feed)) accumulator.WriteOutput(feed_location, output_file, schedule, options.extension) return exit_code
[ "def", "RunValidationOutputToFile", "(", "feed", ",", "options", ",", "output_file", ")", ":", "accumulator", "=", "HTMLCountingProblemAccumulator", "(", "options", ".", "limit_per_type", ",", "options", ".", "error_types_ignore_list", ")", "problems", "=", "transitfe...
Validate feed, write HTML to output_file and return an exit code.
[ "Validate", "feed", "write", "HTML", "to", "output_file", "and", "return", "an", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L528-L539
train
219,925
google/transitfeed
feedvalidator.py
RunValidationOutputToConsole
def RunValidationOutputToConsole(feed, options): """Validate feed, print reports and return an exit code.""" accumulator = CountingConsoleProblemAccumulator( options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) _, exit_code = RunValidation(feed, options, problems) return exit_code
python
def RunValidationOutputToConsole(feed, options): """Validate feed, print reports and return an exit code.""" accumulator = CountingConsoleProblemAccumulator( options.error_types_ignore_list) problems = transitfeed.ProblemReporter(accumulator) _, exit_code = RunValidation(feed, options, problems) return exit_code
[ "def", "RunValidationOutputToConsole", "(", "feed", ",", "options", ")", ":", "accumulator", "=", "CountingConsoleProblemAccumulator", "(", "options", ".", "error_types_ignore_list", ")", "problems", "=", "transitfeed", ".", "ProblemReporter", "(", "accumulator", ")", ...
Validate feed, print reports and return an exit code.
[ "Validate", "feed", "print", "reports", "and", "return", "an", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L542-L548
train
219,926
google/transitfeed
feedvalidator.py
RunValidation
def RunValidation(feed, options, problems): """Validate feed, returning the loaded Schedule and exit code. Args: feed: GTFS file, either path of the file as a string or a file object options: options object returned by optparse problems: transitfeed.ProblemReporter instance Returns: a transitfeed.Schedule object, exit code and plain text string of other problems Exit code is 2 if an extension is provided but can't be loaded, 1 if problems are found and 0 if the Schedule is problem free. plain text string is '' if no other problems are found. """ util.CheckVersion(problems, options.latest_version) # TODO: Add tests for this flag in testfeedvalidator.py if options.extension: try: __import__(options.extension) extension_module = sys.modules[options.extension] except ImportError: # TODO: Document extensions in a wiki page, place link here print("Could not import extension %s! Please ensure it is a proper " "Python module." % options.extension) exit(2) else: extension_module = transitfeed gtfs_factory = extension_module.GetGtfsFactory() print('validating %s' % feed) print('FeedValidator extension used: %s' % options.extension) loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False, memory_db=options.memory_db, check_duplicate_trips=\ options.check_duplicate_trips, gtfs_factory=gtfs_factory) schedule = loader.Load() # Start validation: children are already validated by the loader. schedule.Validate(service_gap_interval=options.service_gap_interval, validate_children=False) if feed == 'IWantMyvalidation-crash.txt': # See tests/testfeedvalidator.py raise Exception('For testing the feed validator crash handler.') accumulator = problems.GetAccumulator() if accumulator.HasIssues(): print('ERROR: %s found' % accumulator.FormatCount()) return schedule, 1 else: print('feed validated successfully') return schedule, 0
python
def RunValidation(feed, options, problems): """Validate feed, returning the loaded Schedule and exit code. Args: feed: GTFS file, either path of the file as a string or a file object options: options object returned by optparse problems: transitfeed.ProblemReporter instance Returns: a transitfeed.Schedule object, exit code and plain text string of other problems Exit code is 2 if an extension is provided but can't be loaded, 1 if problems are found and 0 if the Schedule is problem free. plain text string is '' if no other problems are found. """ util.CheckVersion(problems, options.latest_version) # TODO: Add tests for this flag in testfeedvalidator.py if options.extension: try: __import__(options.extension) extension_module = sys.modules[options.extension] except ImportError: # TODO: Document extensions in a wiki page, place link here print("Could not import extension %s! Please ensure it is a proper " "Python module." % options.extension) exit(2) else: extension_module = transitfeed gtfs_factory = extension_module.GetGtfsFactory() print('validating %s' % feed) print('FeedValidator extension used: %s' % options.extension) loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False, memory_db=options.memory_db, check_duplicate_trips=\ options.check_duplicate_trips, gtfs_factory=gtfs_factory) schedule = loader.Load() # Start validation: children are already validated by the loader. schedule.Validate(service_gap_interval=options.service_gap_interval, validate_children=False) if feed == 'IWantMyvalidation-crash.txt': # See tests/testfeedvalidator.py raise Exception('For testing the feed validator crash handler.') accumulator = problems.GetAccumulator() if accumulator.HasIssues(): print('ERROR: %s found' % accumulator.FormatCount()) return schedule, 1 else: print('feed validated successfully') return schedule, 0
[ "def", "RunValidation", "(", "feed", ",", "options", ",", "problems", ")", ":", "util", ".", "CheckVersion", "(", "problems", ",", "options", ".", "latest_version", ")", "# TODO: Add tests for this flag in testfeedvalidator.py", "if", "options", ".", "extension", ":...
Validate feed, returning the loaded Schedule and exit code. Args: feed: GTFS file, either path of the file as a string or a file object options: options object returned by optparse problems: transitfeed.ProblemReporter instance Returns: a transitfeed.Schedule object, exit code and plain text string of other problems Exit code is 2 if an extension is provided but can't be loaded, 1 if problems are found and 0 if the Schedule is problem free. plain text string is '' if no other problems are found.
[ "Validate", "feed", "returning", "the", "loaded", "Schedule", "and", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L551-L605
train
219,927
google/transitfeed
feedvalidator.py
RunValidationFromOptions
def RunValidationFromOptions(feed, options): """Validate feed, run in profiler if in options, and return an exit code.""" if options.performance: return ProfileRunValidationOutputFromOptions(feed, options) else: return RunValidationOutputFromOptions(feed, options)
python
def RunValidationFromOptions(feed, options): """Validate feed, run in profiler if in options, and return an exit code.""" if options.performance: return ProfileRunValidationOutputFromOptions(feed, options) else: return RunValidationOutputFromOptions(feed, options)
[ "def", "RunValidationFromOptions", "(", "feed", ",", "options", ")", ":", "if", "options", ".", "performance", ":", "return", "ProfileRunValidationOutputFromOptions", "(", "feed", ",", "options", ")", "else", ":", "return", "RunValidationOutputFromOptions", "(", "fe...
Validate feed, run in profiler if in options, and return an exit code.
[ "Validate", "feed", "run", "in", "profiler", "if", "in", "options", "and", "return", "an", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L700-L705
train
219,928
google/transitfeed
feedvalidator.py
ProfileRunValidationOutputFromOptions
def ProfileRunValidationOutputFromOptions(feed, options): """Run RunValidationOutputFromOptions, print profile and return exit code.""" import cProfile import pstats # runctx will modify a dict, but not locals(). We need a way to get rv back. locals_for_exec = locals() cProfile.runctx('rv = RunValidationOutputFromOptions(feed, options)', globals(), locals_for_exec, 'validate-stats') # Only available on Unix, http://docs.python.org/lib/module-resource.html import resource print("Time: %d seconds" % ( resource.getrusage(resource.RUSAGE_SELF).ru_utime + resource.getrusage(resource.RUSAGE_SELF).ru_stime)) # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 # http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely # available for review and use." def _VmB(VmKey): """Return size from proc status in bytes.""" _proc_status = '/proc/%d/status' % os.getpid() _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, 'KB': 1024.0, 'MB': 1024.0*1024.0} # get pseudo file /proc/<pid>/status try: t = open(_proc_status) v = t.read() t.close() except: raise Exception("no proc file %s" % _proc_status) return 0 # non-Linux? # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' try: i = v.index(VmKey) v = v[i:].split(None, 3) # whitespace except: return 0 # v is empty if len(v) < 3: raise Exception("%s" % v) return 0 # invalid format? # convert Vm value to bytes return int(float(v[1]) * _scale[v[2]]) # I ran this on over a hundred GTFS files, comparing VmSize to VmRSS # (resident set size). The difference was always under 2% or 3MB. print("Virtual Memory Size: %d bytes" % _VmB('VmSize:')) # Output report of where CPU time was spent. p = pstats.Stats('validate-stats') p.strip_dirs() p.sort_stats('cumulative').print_stats(30) p.sort_stats('cumulative').print_callers(30) return locals_for_exec['rv']
python
def ProfileRunValidationOutputFromOptions(feed, options): """Run RunValidationOutputFromOptions, print profile and return exit code.""" import cProfile import pstats # runctx will modify a dict, but not locals(). We need a way to get rv back. locals_for_exec = locals() cProfile.runctx('rv = RunValidationOutputFromOptions(feed, options)', globals(), locals_for_exec, 'validate-stats') # Only available on Unix, http://docs.python.org/lib/module-resource.html import resource print("Time: %d seconds" % ( resource.getrusage(resource.RUSAGE_SELF).ru_utime + resource.getrusage(resource.RUSAGE_SELF).ru_stime)) # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 # http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely # available for review and use." def _VmB(VmKey): """Return size from proc status in bytes.""" _proc_status = '/proc/%d/status' % os.getpid() _scale = {'kB': 1024.0, 'mB': 1024.0*1024.0, 'KB': 1024.0, 'MB': 1024.0*1024.0} # get pseudo file /proc/<pid>/status try: t = open(_proc_status) v = t.read() t.close() except: raise Exception("no proc file %s" % _proc_status) return 0 # non-Linux? # get VmKey line e.g. 'VmRSS: 9999 kB\n ...' try: i = v.index(VmKey) v = v[i:].split(None, 3) # whitespace except: return 0 # v is empty if len(v) < 3: raise Exception("%s" % v) return 0 # invalid format? # convert Vm value to bytes return int(float(v[1]) * _scale[v[2]]) # I ran this on over a hundred GTFS files, comparing VmSize to VmRSS # (resident set size). The difference was always under 2% or 3MB. print("Virtual Memory Size: %d bytes" % _VmB('VmSize:')) # Output report of where CPU time was spent. p = pstats.Stats('validate-stats') p.strip_dirs() p.sort_stats('cumulative').print_stats(30) p.sort_stats('cumulative').print_callers(30) return locals_for_exec['rv']
[ "def", "ProfileRunValidationOutputFromOptions", "(", "feed", ",", "options", ")", ":", "import", "cProfile", "import", "pstats", "# runctx will modify a dict, but not locals(). We need a way to get rv back.", "locals_for_exec", "=", "locals", "(", ")", "cProfile", ".", "runct...
Run RunValidationOutputFromOptions, print profile and return exit code.
[ "Run", "RunValidationOutputFromOptions", "print", "profile", "and", "return", "exit", "code", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L708-L762
train
219,929
google/transitfeed
feedvalidator.py
HTMLCountingProblemAccumulator.FormatType
def FormatType(self, level_name, class_problist): """Write the HTML dumping all problems of one type. Args: level_name: string such as "Error" or "Warning" class_problist: sequence of tuples (class name, BoundedProblemList object) Returns: HTML in a string """ class_problist.sort() output = [] for classname, problist in class_problist: output.append('<h4 class="issueHeader"><a name="%s%s">%s</a></h4><ul>\n' % (level_name, classname, UnCamelCase(classname))) for e in problist.problems: self.FormatException(e, output) if problist.dropped_count: output.append('<li>and %d more of this type.' % (problist.dropped_count)) output.append('</ul>\n') return ''.join(output)
python
def FormatType(self, level_name, class_problist): """Write the HTML dumping all problems of one type. Args: level_name: string such as "Error" or "Warning" class_problist: sequence of tuples (class name, BoundedProblemList object) Returns: HTML in a string """ class_problist.sort() output = [] for classname, problist in class_problist: output.append('<h4 class="issueHeader"><a name="%s%s">%s</a></h4><ul>\n' % (level_name, classname, UnCamelCase(classname))) for e in problist.problems: self.FormatException(e, output) if problist.dropped_count: output.append('<li>and %d more of this type.' % (problist.dropped_count)) output.append('</ul>\n') return ''.join(output)
[ "def", "FormatType", "(", "self", ",", "level_name", ",", "class_problist", ")", ":", "class_problist", ".", "sort", "(", ")", "output", "=", "[", "]", "for", "classname", ",", "problist", "in", "class_problist", ":", "output", ".", "append", "(", "'<h4 cl...
Write the HTML dumping all problems of one type. Args: level_name: string such as "Error" or "Warning" class_problist: sequence of tuples (class name, BoundedProblemList object) Returns: HTML in a string
[ "Write", "the", "HTML", "dumping", "all", "problems", "of", "one", "type", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L254-L276
train
219,930
google/transitfeed
feedvalidator.py
HTMLCountingProblemAccumulator.FormatTypeSummaryTable
def FormatTypeSummaryTable(self, level_name, name_to_problist): """Return an HTML table listing the number of problems by class name. Args: level_name: string such as "Error" or "Warning" name_to_problist: dict mapping class name to an BoundedProblemList object Returns: HTML in a string """ output = [] output.append('<table>') for classname in sorted(name_to_problist.keys()): problist = name_to_problist[classname] human_name = MaybePluralizeWord(problist.count, UnCamelCase(classname)) output.append('<tr><td>%d</td><td><a href="#%s%s">%s</a></td></tr>\n' % (problist.count, level_name, classname, human_name)) output.append('</table>\n') return ''.join(output)
python
def FormatTypeSummaryTable(self, level_name, name_to_problist): """Return an HTML table listing the number of problems by class name. Args: level_name: string such as "Error" or "Warning" name_to_problist: dict mapping class name to an BoundedProblemList object Returns: HTML in a string """ output = [] output.append('<table>') for classname in sorted(name_to_problist.keys()): problist = name_to_problist[classname] human_name = MaybePluralizeWord(problist.count, UnCamelCase(classname)) output.append('<tr><td>%d</td><td><a href="#%s%s">%s</a></td></tr>\n' % (problist.count, level_name, classname, human_name)) output.append('</table>\n') return ''.join(output)
[ "def", "FormatTypeSummaryTable", "(", "self", ",", "level_name", ",", "name_to_problist", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "'<table>'", ")", "for", "classname", "in", "sorted", "(", "name_to_problist", ".", "keys", "(", ")", ...
Return an HTML table listing the number of problems by class name. Args: level_name: string such as "Error" or "Warning" name_to_problist: dict mapping class name to an BoundedProblemList object Returns: HTML in a string
[ "Return", "an", "HTML", "table", "listing", "the", "number", "of", "problems", "by", "class", "name", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L278-L296
train
219,931
google/transitfeed
feedvalidator.py
HTMLCountingProblemAccumulator.FormatException
def FormatException(self, e, output): """Append HTML version of e to list output.""" d = e.GetDictToFormat() for k in ('file_name', 'feedname', 'column_name'): if k in d.keys(): d[k] = '<code>%s</code>' % d[k] if 'url' in d.keys(): d['url'] = '<a href="%(url)s">%(url)s</a>' % d problem_text = e.FormatProblem(d).replace('\n', '<br>') problem_class = 'problem' if e.IsNotice(): problem_class += ' notice' output.append('<li>') output.append('<div class="%s">%s</div>' % (problem_class, transitfeed.EncodeUnicode(problem_text))) try: if hasattr(e, 'row_num'): line_str = 'line %d of ' % e.row_num else: line_str = '' output.append('in %s<code>%s</code><br>\n' % (line_str, transitfeed.EncodeUnicode(e.file_name))) row = e.row headers = e.headers column_name = e.column_name table_header = '' # HTML table_data = '' # HTML for header, value in zip(headers, row): attributes = '' if header == column_name: attributes = ' class="problem"' table_header += '<th%s>%s</th>' % (attributes, header) table_data += '<td%s>%s</td>' % (attributes, value) # Make sure output is encoded into UTF-8 output.append('<table class="dump"><tr>%s</tr>\n' % transitfeed.EncodeUnicode(table_header)) output.append('<tr>%s</tr></table>\n' % transitfeed.EncodeUnicode(table_data)) except AttributeError as e: pass # Hope this was getting an attribute from e ;-) output.append('<br></li>\n')
python
def FormatException(self, e, output): """Append HTML version of e to list output.""" d = e.GetDictToFormat() for k in ('file_name', 'feedname', 'column_name'): if k in d.keys(): d[k] = '<code>%s</code>' % d[k] if 'url' in d.keys(): d['url'] = '<a href="%(url)s">%(url)s</a>' % d problem_text = e.FormatProblem(d).replace('\n', '<br>') problem_class = 'problem' if e.IsNotice(): problem_class += ' notice' output.append('<li>') output.append('<div class="%s">%s</div>' % (problem_class, transitfeed.EncodeUnicode(problem_text))) try: if hasattr(e, 'row_num'): line_str = 'line %d of ' % e.row_num else: line_str = '' output.append('in %s<code>%s</code><br>\n' % (line_str, transitfeed.EncodeUnicode(e.file_name))) row = e.row headers = e.headers column_name = e.column_name table_header = '' # HTML table_data = '' # HTML for header, value in zip(headers, row): attributes = '' if header == column_name: attributes = ' class="problem"' table_header += '<th%s>%s</th>' % (attributes, header) table_data += '<td%s>%s</td>' % (attributes, value) # Make sure output is encoded into UTF-8 output.append('<table class="dump"><tr>%s</tr>\n' % transitfeed.EncodeUnicode(table_header)) output.append('<tr>%s</tr></table>\n' % transitfeed.EncodeUnicode(table_data)) except AttributeError as e: pass # Hope this was getting an attribute from e ;-) output.append('<br></li>\n')
[ "def", "FormatException", "(", "self", ",", "e", ",", "output", ")", ":", "d", "=", "e", ".", "GetDictToFormat", "(", ")", "for", "k", "in", "(", "'file_name'", ",", "'feedname'", ",", "'column_name'", ")", ":", "if", "k", "in", "d", ".", "keys", "...
Append HTML version of e to list output.
[ "Append", "HTML", "version", "of", "e", "to", "list", "output", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/feedvalidator.py#L298-L339
train
219,932
google/transitfeed
transitfeed/serviceperiod.py
ServicePeriod.GetDateRange
def GetDateRange(self): """Return the range over which this ServicePeriod is valid. The range includes exception dates that add service outside of (start_date, end_date), but doesn't shrink the range if exception dates take away service at the edges of the range. Returns: A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if no dates have been given. """ start = self.start_date end = self.end_date for date, (exception_type, _) in self.date_exceptions.items(): if exception_type == self._EXCEPTION_TYPE_REMOVE: continue if not start or (date < start): start = date if not end or (date > end): end = date if start is None: start = end elif end is None: end = start # If start and end are None we did a little harmless shuffling return (start, end)
python
def GetDateRange(self): """Return the range over which this ServicePeriod is valid. The range includes exception dates that add service outside of (start_date, end_date), but doesn't shrink the range if exception dates take away service at the edges of the range. Returns: A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if no dates have been given. """ start = self.start_date end = self.end_date for date, (exception_type, _) in self.date_exceptions.items(): if exception_type == self._EXCEPTION_TYPE_REMOVE: continue if not start or (date < start): start = date if not end or (date > end): end = date if start is None: start = end elif end is None: end = start # If start and end are None we did a little harmless shuffling return (start, end)
[ "def", "GetDateRange", "(", "self", ")", ":", "start", "=", "self", ".", "start_date", "end", "=", "self", ".", "end_date", "for", "date", ",", "(", "exception_type", ",", "_", ")", "in", "self", ".", "date_exceptions", ".", "items", "(", ")", ":", "...
Return the range over which this ServicePeriod is valid. The range includes exception dates that add service outside of (start_date, end_date), but doesn't shrink the range if exception dates take away service at the edges of the range. Returns: A tuple of "YYYYMMDD" strings, (start date, end date) or (None, None) if no dates have been given.
[ "Return", "the", "range", "over", "which", "this", "ServicePeriod", "is", "valid", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L78-L104
train
219,933
google/transitfeed
transitfeed/serviceperiod.py
ServicePeriod.GetCalendarFieldValuesTuple
def GetCalendarFieldValuesTuple(self): """Return the tuple of calendar.txt values or None if this ServicePeriod should not be in calendar.txt .""" if self.start_date and self.end_date: return [getattr(self, fn) for fn in self._FIELD_NAMES]
python
def GetCalendarFieldValuesTuple(self): """Return the tuple of calendar.txt values or None if this ServicePeriod should not be in calendar.txt .""" if self.start_date and self.end_date: return [getattr(self, fn) for fn in self._FIELD_NAMES]
[ "def", "GetCalendarFieldValuesTuple", "(", "self", ")", ":", "if", "self", ".", "start_date", "and", "self", ".", "end_date", ":", "return", "[", "getattr", "(", "self", ",", "fn", ")", "for", "fn", "in", "self", ".", "_FIELD_NAMES", "]" ]
Return the tuple of calendar.txt values or None if this ServicePeriod should not be in calendar.txt .
[ "Return", "the", "tuple", "of", "calendar", ".", "txt", "values", "or", "None", "if", "this", "ServicePeriod", "should", "not", "be", "in", "calendar", ".", "txt", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L106-L110
train
219,934
google/transitfeed
transitfeed/serviceperiod.py
ServicePeriod.GenerateCalendarDatesFieldValuesTuples
def GenerateCalendarDatesFieldValuesTuples(self): """Generates tuples of calendar_dates.txt values. Yield zero tuples if this ServicePeriod should not be in calendar_dates.txt .""" for date, (exception_type, _) in self.date_exceptions.items(): yield (self.service_id, date, unicode(exception_type))
python
def GenerateCalendarDatesFieldValuesTuples(self): """Generates tuples of calendar_dates.txt values. Yield zero tuples if this ServicePeriod should not be in calendar_dates.txt .""" for date, (exception_type, _) in self.date_exceptions.items(): yield (self.service_id, date, unicode(exception_type))
[ "def", "GenerateCalendarDatesFieldValuesTuples", "(", "self", ")", ":", "for", "date", ",", "(", "exception_type", ",", "_", ")", "in", "self", ".", "date_exceptions", ".", "items", "(", ")", ":", "yield", "(", "self", ".", "service_id", ",", "date", ",", ...
Generates tuples of calendar_dates.txt values. Yield zero tuples if this ServicePeriod should not be in calendar_dates.txt .
[ "Generates", "tuples", "of", "calendar_dates", ".", "txt", "values", ".", "Yield", "zero", "tuples", "if", "this", "ServicePeriod", "should", "not", "be", "in", "calendar_dates", ".", "txt", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L112-L116
train
219,935
google/transitfeed
transitfeed/serviceperiod.py
ServicePeriod.GetCalendarDatesFieldValuesTuples
def GetCalendarDatesFieldValuesTuples(self): """Return a list of date execeptions""" result = [] for date_tuple in self.GenerateCalendarDatesFieldValuesTuples(): result.append(date_tuple) result.sort() # helps with __eq__ return result
python
def GetCalendarDatesFieldValuesTuples(self): """Return a list of date execeptions""" result = [] for date_tuple in self.GenerateCalendarDatesFieldValuesTuples(): result.append(date_tuple) result.sort() # helps with __eq__ return result
[ "def", "GetCalendarDatesFieldValuesTuples", "(", "self", ")", ":", "result", "=", "[", "]", "for", "date_tuple", "in", "self", ".", "GenerateCalendarDatesFieldValuesTuples", "(", ")", ":", "result", ".", "append", "(", "date_tuple", ")", "result", ".", "sort", ...
Return a list of date execeptions
[ "Return", "a", "list", "of", "date", "execeptions" ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L118-L124
train
219,936
google/transitfeed
transitfeed/serviceperiod.py
ServicePeriod.HasDateExceptionOn
def HasDateExceptionOn(self, date, exception_type=_EXCEPTION_TYPE_ADD): """Test if this service period has a date exception of the given type. Args: date: a string of form "YYYYMMDD" exception_type: the exception type the date should have. Defaults to _EXCEPTION_TYPE_ADD Returns: True iff this service has service exception of specified type at date. """ if date in self.date_exceptions: return exception_type == self.date_exceptions[date][0] return False
python
def HasDateExceptionOn(self, date, exception_type=_EXCEPTION_TYPE_ADD): """Test if this service period has a date exception of the given type. Args: date: a string of form "YYYYMMDD" exception_type: the exception type the date should have. Defaults to _EXCEPTION_TYPE_ADD Returns: True iff this service has service exception of specified type at date. """ if date in self.date_exceptions: return exception_type == self.date_exceptions[date][0] return False
[ "def", "HasDateExceptionOn", "(", "self", ",", "date", ",", "exception_type", "=", "_EXCEPTION_TYPE_ADD", ")", ":", "if", "date", "in", "self", ".", "date_exceptions", ":", "return", "exception_type", "==", "self", ".", "date_exceptions", "[", "date", "]", "["...
Test if this service period has a date exception of the given type. Args: date: a string of form "YYYYMMDD" exception_type: the exception type the date should have. Defaults to _EXCEPTION_TYPE_ADD Returns: True iff this service has service exception of specified type at date.
[ "Test", "if", "this", "service", "period", "has", "a", "date", "exception", "of", "the", "given", "type", "." ]
eb2991a3747ba541b2cb66502b305b6304a1f85f
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/serviceperiod.py#L177-L190
train
219,937
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): """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
[ "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
train
219,938
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): """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
[ "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
train
219,939
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): """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
[ "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
train
219,940
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
train
219,941
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
train
219,942
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
train
219,943
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
train
219,944
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
train
219,945
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
train
219,946
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
train
219,947
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
train
219,948
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
train
219,949
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
train
219,950
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
train
219,951
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): """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
[ "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
train
219,952
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): """ 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)
[ "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
train
219,953
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): """ 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
[ "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
train
219,954
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): """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
[ "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
train
219,955
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): """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
[ "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
train
219,956
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): """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
[ "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
train
219,957
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): """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
[ "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
train
219,958
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): """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
[ "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
train
219,959
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): """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))))
[ "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
train
219,960
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): """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)
[ "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
train
219,961
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): """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
[ "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
train
219,962
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): """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
[ "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
train
219,963
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): """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
[ "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
train
219,964
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): """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)
[ "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
train
219,965
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): """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)
[ "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
train
219,966
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): """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))
[ "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
train
219,967
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): """ 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)
[ "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
train
219,968
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): """ 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
[ "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
train
219,969
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): """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
[ "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
train
219,970
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): """Returns a list of file names in the feed.""" 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
train
219,971
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): """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
[ "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
train
219,972
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): """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)
[ "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
train
219,973
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): """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
[ "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
train
219,974
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): """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
[ "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
train
219,975
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): """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]]
[ "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
train
219,976
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): """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))
[ "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
train
219,977
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): """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']
[ "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
train
219,978
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): """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
[ "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
train
219,979
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): """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)
[ "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
train
219,980
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): """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
[ "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
train
219,981
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): """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
[ "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
train
219,982
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): """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]
[ "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
train
219,983
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): """ 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)
[ "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
train
219,984
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): """ 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)
[ "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
train
219,985
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): """ 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
[ "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
train
219,986
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): """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)))
[ "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
train
219,987
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(): """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)
[ "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
train
219,988
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): """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())
[ "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
train
219,989
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): """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)
[ "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
train
219,990
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): """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()
[ "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
train
219,991
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): """ 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))
[ "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
train
219,992
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): """ 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
[ "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
train
219,993
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): """ 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]
[ "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
train
219,994
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): """ 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)
[ "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
train
219,995
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): """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)
[ "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
train
219,996
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): """"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
[ "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
train
219,997
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): """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)
[ "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
train
219,998
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): """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
[ "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
train
219,999