idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,100
def _find_feed_language ( self ) : self . feed_language = ( read_first_available_value ( os . path . join ( self . src_dir , 'feed_info.txt' ) , 'feed_lang' ) or read_first_available_value ( os . path . join ( self . src_dir , 'agency.txt' ) , 'agency_lang' ) ) if not self . feed_language : raise Exception ( 'Cannot fi...
Find feed language based specified feed_info . txt or agency . txt .
31,101
def _read_translations ( self ) : print ( 'Reading original translations' ) self . translations_map = { } n_translations = 0 with open ( os . path . join ( self . src_dir , 'translations.txt' ) , 'rb' ) as csvfile : reader = csv . DictReader ( csvfile ) for row in reader : self . translations_map . setdefault ( row [ '...
Read from the old translations . txt .
31,102
def _find_context_dependent_names ( self ) : n_occurences_of_original = { } for trans_id , translations in self . translations_map . items ( ) : try : original_name = translations [ self . feed_language ] except KeyError : raise Exception ( 'No translation in feed language for %s, available: %s' % ( trans_id , translat...
Finds texts whose translation depends on context .
31,103
def convert_translations ( self , dest_dir ) : if not os . path . isdir ( dest_dir ) : os . makedirs ( dest_dir ) total_translation_rows = 0 with open ( os . path . join ( dest_dir , 'translations.txt' ) , 'w+b' ) as out_file : writer = csv . DictWriter ( out_file , fieldnames = NEW_TRANSLATIONS_FIELDS ) writer . write...
Converts translations to the new format and stores at dest_dir .
31,104
def _translate_table ( self , dest_dir , table_name , translations_writer ) : in_filename = os . path . join ( self . src_dir , '%s.txt' % table_name ) if not os . path . exists ( in_filename ) : raise Exception ( 'No %s' % table_name ) out_filename = os . path . join ( dest_dir , '%s.txt' % table_name ) with open ( in...
Converts translations to the new format for a single table .
31,105
def _DetermineFormat ( self ) : if self . _zip : assert not self . _path return True if not isinstance ( self . _path , basestring ) and hasattr ( self . _path , 'read' ) : self . _zip = zipfile . ZipFile ( self . _path , mode = 'r' ) return True if not os . path . exists ( self . _path ) : self . _problems . FeedNotFo...
Determines whether the feed is in a form that we understand and if so returns True .
31,106
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 .
31,107
def _GetUtf8Contents ( self , file_name ) : contents = self . _FileContents ( file_name ) if not contents : return 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 , ) ) contents = codec...
Check for errors in file_name and return a string for csv reader .
31,108
def _HasFile ( self , file_name ) : if self . _zip : return file_name in self . _zip . namelist ( ) else : file_path = os . path . join ( self . _path , file_name ) return os . path . exists ( file_path ) and os . path . isfile ( file_path )
Returns True if there s a file in the current feed with the given file_name in the current feed .
31,109
def AddTrip ( self , schedule = None , headsign = None , service_period = None , trip_id = None ) : if schedule is None : assert self . _schedule is not None schedule = self . _schedule if trip_id is None : trip_id = util . FindUniqueId ( schedule . trips ) if service_period is None : service_period = schedule . GetDef...
Add a trip to this route .
31,110
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 .
31,111
def GetGtfsClassByFileName ( self , filename ) : if filename not in self . _file_mapping : return None mapping = self . _file_mapping [ filename ] class_list = mapping [ 'classes' ] if len ( class_list ) > 1 : raise problems . NonStandardMapping ( filename ) else : return self . _class_mapping [ class_list [ 0 ] ]
Returns the transitfeed class corresponding to a GTFS file .
31,112
def GetLoadingOrder ( self ) : result = { } for filename , mapping in self . _file_mapping . iteritems ( ) : loading_order = mapping [ 'loading_order' ] if loading_order is not None : result [ loading_order ] = filename return list ( result [ key ] for key in sorted ( result ) )
Returns a list of filenames sorted by loading order . Only includes files that Loader s standardized loading knows how to load
31,113
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
31,114
def AddMapping ( self , filename , new_mapping ) : for field in self . _REQUIRED_MAPPING_FIELDS : if field not in new_mapping : raise problems . InvalidMapping ( field ) if filename in self . GetKnownFilenames ( ) : raise problems . DuplicateMapping ( filename ) self . _file_mapping [ filename ] = new_mapping
Adds an entry to the list of known filenames .
31,115
def UpdateMapping ( self , filename , mapping_update ) : if filename not in self . _file_mapping : raise problems . NonexistentMapping ( filename ) mapping = self . _file_mapping [ filename ] mapping . update ( mapping_update )
Updates an entry in the list of known filenames . An entry is identified by its filename .
31,116
def AddClass ( self , class_name , gtfs_class ) : if class_name in self . _class_mapping : raise problems . DuplicateMapping ( class_name ) self . _class_mapping [ class_name ] = gtfs_class
Adds an entry to the list of known classes .
31,117
def UpdateClass ( self , class_name , gtfs_class ) : if class_name not in self . _class_mapping : raise problems . NonexistentMapping ( class_name ) self . _class_mapping [ class_name ] = gtfs_class
Updates an entry in the list of known classes .
31,118
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 .
31,119
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 .
31,120
def ParseDom ( self , dom , feed ) : shape_num = 0 for node in dom . getElementsByTagName ( 'Placemark' ) : p = self . ParsePlacemark ( node ) if p . IsPoint ( ) : ( lon , lat ) = p . coordinates [ 0 ] m = self . stopNameRe . search ( p . name ) feed . AddStop ( lat , lon , m . group ( 1 ) ) elif p . IsLine ( ) : self ...
Parses the given kml dom tree and updates the Google transit feed object .
31,121
def Distance ( lat0 , lng0 , lat1 , lng1 ) : deg2rad = math . pi / 180.0 lat0 = lat0 * deg2rad lng0 = lng0 * deg2rad lat1 = lat1 * deg2rad lng1 = lng1 * deg2rad dlng = lng1 - lng0 dlat = lat1 - lat0 a = math . sin ( dlat * 0.5 ) b = math . sin ( dlng * 0.5 ) a = a * a + math . cos ( lat0 ) * math . cos ( lat1 ) * b * b...
Compute the geodesic distance in meters between two points on the surface of the Earth . The latitude and longitude angles are in degrees .
31,122
def AddNoiseToLatLng ( lat , lng ) : m_per_tenth_lat = Distance ( lat , lng , lat + 0.1 , lng ) m_per_tenth_lng = Distance ( lat , lng , lat , lng + 0.1 ) lat_per_100m = 1 / m_per_tenth_lat * 10 lng_per_100m = 1 / m_per_tenth_lng * 10 return ( lat + ( lat_per_100m * 5 * ( random . random ( ) * 2 - 1 ) ) , lng + ( lng_p...
Add up to 500m of error to each coordinate of lat lng .
31,123
def GetRandomDatetime ( ) : seconds_offset = random . randint ( 0 , 60 * 60 * 24 * 7 ) dt = datetime . today ( ) + timedelta ( seconds = seconds_offset ) return dt . replace ( second = 0 , microsecond = 0 )
Return a datetime in the next week .
31,124
def LatLngsToGoogleLink ( source , destination ) : dt = GetRandomDatetime ( ) return "<a href='%s'>from:%s to:%s on %s</a>" % ( LatLngsToGoogleUrl ( source , destination , dt ) , FormatLatLng ( source ) , FormatLatLng ( destination ) , dt . ctime ( ) )
Return a string <a ... for a trip at a random time .
31,125
def ParentAndBaseName ( path ) : dirname , basename = os . path . split ( path ) dirname = dirname . rstrip ( os . path . sep ) if os . path . altsep : dirname = dirname . rstrip ( os . path . altsep ) _ , parentname = os . path . split ( dirname ) return os . path . join ( parentname , basename )
Given a path return only the parent name and file name as a string .
31,126
def LoadFile ( f , table_name , conn ) : reader = csv . reader ( f ) header = next ( reader ) columns = [ ] for n in header : n = n . replace ( ' ' , '' ) n = n . replace ( '-' , '_' ) columns . append ( n ) create_columns = [ ] column_types = { } for n in columns : if n in column_types : create_columns . append ( "%s ...
Import lines from f as new table in db with cursor c .
31,127
def PrintColumns ( shapefile ) : ds = ogr . Open ( shapefile ) layer = ds . GetLayer ( 0 ) if len ( layer ) == 0 : raise ShapeImporterError ( "Layer 0 has no elements!" ) feature = layer . GetFeature ( 0 ) print ( "%d features" % feature . GetFieldCount ( ) ) for j in range ( 0 , feature . GetFieldCount ( ) ) : print (...
Print the columns of layer 0 of the shapefile to the screen .
31,128
def AddShapefile ( shapefile , graph , key_cols ) : ds = ogr . Open ( shapefile ) layer = ds . GetLayer ( 0 ) for i in range ( 0 , len ( layer ) ) : feature = layer . GetFeature ( i ) geometry = feature . GetGeometryRef ( ) if key_cols : key_list = [ ] for col in key_cols : key_list . append ( str ( feature . GetField ...
Adds shapes found in the given shape filename to the given polyline graph object .
31,129
def GetMatchingShape ( pattern_poly , trip , matches , max_distance , verbosity = 0 ) : if len ( matches ) == 0 : print ( 'No matching shape found within max-distance %d for trip %s ' % ( max_distance , trip . trip_id ) ) return None if verbosity >= 1 : for match in matches : print ( "match: size %d" % match . GetNumPo...
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 .
31,130
def AddExtraShapes ( extra_shapes_txt , graph ) : print ( "Adding extra shapes from %s" % extra_shapes_txt ) try : tmpdir = tempfile . mkdtemp ( ) shutil . copy ( extra_shapes_txt , os . path . join ( tmpdir , 'shapes.txt' ) ) loader = transitfeed . ShapeLoader ( tmpdir ) schedule = loader . Load ( ) for shape in sched...
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 .
31,131
def ApproximateDistanceBetweenPoints ( pa , pb ) : alat , alon = pa blat , blon = pb sa = transitfeed . Stop ( lat = alat , lng = alon ) sb = transitfeed . Stop ( lat = blat , lng = blon ) return transitfeed . ApproximateDistanceBetweenStops ( sa , sb )
Finds the distance between two points on the Earth s surface .
31,132
def LoadWithoutErrors ( path , memory_db ) : accumulator = transitfeed . ExceptionProblemAccumulator ( ) loading_problem_handler = MergeProblemReporter ( accumulator ) try : schedule = transitfeed . Loader ( path , memory_db = memory_db , problems = loading_problem_handler , extra_validation = True ) . Load ( ) except ...
Return a Schedule object loaded from path ; sys . exit for any error .
31,133
def _GenerateStatsTable ( self , feed_merger ) : rows = [ ] rows . append ( '<tr><th class="header"/><th class="header">Merged</th>' '<th class="header">Copied from old feed</th>' '<th class="header">Copied from new feed</th></tr>' ) for merger in feed_merger . GetMergerList ( ) : stats = merger . GetMergeStats ( ) if ...
Generate an HTML table of merge statistics .
31,134
def _GenerateSection ( self , problem_type ) : if problem_type == transitfeed . TYPE_WARNING : dataset_problems = self . _dataset_warnings heading = 'Warnings' else : dataset_problems = self . _dataset_errors heading = 'Errors' if not dataset_problems : return '' prefix = '<h2 class="issueHeader">%s:</h2>' % heading da...
Generate a listing of the given type of problems .
31,135
def _GenerateSummary ( self ) : items = [ ] if self . _notices : items . append ( 'notices: %d' % self . _notice_count ) if self . _dataset_errors : items . append ( 'errors: %d' % self . _error_count ) if self . _dataset_warnings : items . append ( 'warnings: %d' % self . _warning_count ) if items : return '<p><span c...
Generate a summary of the warnings and errors .
31,136
def _GenerateNotices ( self ) : items = [ ] for e in self . _notices : d = e . GetDictToFormat ( ) if 'url' in d . keys ( ) : d [ 'url' ] = '<a href="%(url)s">%(url)s</a>' % d items . append ( '<li class="notice">%s</li>' % e . FormatProblem ( d ) . replace ( '\n' , '<br>' ) ) if items : return '<h2>Notices:</h2>\n<ul>...
Generate a summary of any notices .
31,137
def _MergeIdentical ( self , a , b ) : if a != b : raise MergeError ( "values must be identical ('%s' vs '%s')" % ( transitfeed . EncodeUnicode ( a ) , transitfeed . EncodeUnicode ( b ) ) ) return b
Tries to merge two values . The values are required to be identical .
31,138
def _MergeIdenticalCaseInsensitive ( self , a , b ) : if a . lower ( ) != b . lower ( ) : raise MergeError ( "values must be the same (case insensitive) " "('%s' vs '%s')" % ( transitfeed . EncodeUnicode ( a ) , transitfeed . EncodeUnicode ( b ) ) ) return b
Tries to merge two strings .
31,139
def _MergeOptional ( self , a , b ) : if a and b : if a != b : raise MergeError ( "values must be identical if both specified " "('%s' vs '%s')" % ( transitfeed . EncodeUnicode ( a ) , transitfeed . EncodeUnicode ( b ) ) ) return a or b
Tries to merge two values which may be None .
31,140
def _MergeSameAgency ( self , a_agency_id , b_agency_id ) : a_agency_id = ( a_agency_id or self . feed_merger . a_schedule . GetDefaultAgency ( ) . agency_id ) b_agency_id = ( b_agency_id or self . feed_merger . b_schedule . GetDefaultAgency ( ) . agency_id ) a_agency = self . feed_merger . a_schedule . GetAgency ( a_a...
Merge agency ids to the corresponding agency id in the merged schedule .
31,141
def _SchemedMerge ( self , scheme , a , b ) : migrated = self . _Migrate ( b , self . feed_merger . b_schedule , False ) for attr , merger in scheme . items ( ) : a_attr = getattr ( a , attr , None ) b_attr = getattr ( b , attr , None ) try : merged_attr = merger ( a_attr , b_attr ) except MergeError as merge_error : r...
Tries to merge two entities according to a merge scheme .
31,142
def _MergeSameId ( self ) : a_not_merged = [ ] b_not_merged = [ ] for a in self . _GetIter ( self . feed_merger . a_schedule ) : try : b = self . _GetById ( self . feed_merger . b_schedule , self . _GetId ( a ) ) except KeyError : a_not_merged . append ( a ) continue try : self . _Add ( a , b , self . _MergeEntities ( ...
Tries to merge entities based on their ids .
31,143
def _MergeDifferentId ( self ) : for a in self . _GetIter ( self . feed_merger . a_schedule ) : for b in self . _GetIter ( self . feed_merger . b_schedule ) : try : self . _Add ( a , b , self . _MergeEntities ( a , b ) ) self . _num_merged += 1 except MergeError : continue for a in self . _GetIter ( self . feed_merger ...
Tries to merge all possible combinations of entities .
31,144
def _ReportSameIdButNotMerged ( self , entity_id , reason ) : self . feed_merger . problem_reporter . SameIdButNotMerged ( self , entity_id , reason )
Report that two entities have the same id but could not be merged .
31,145
def _HasId ( self , schedule , entity_id ) : try : self . _GetById ( schedule , entity_id ) has = True except KeyError : has = False return has
Check if the schedule has an entity with the given id .
31,146
def _MergeEntities ( self , a , b ) : def _MergeAgencyId ( a_agency_id , b_agency_id ) : a_agency_id = a_agency_id or None b_agency_id = b_agency_id or None return self . _MergeIdentical ( a_agency_id , b_agency_id ) scheme = { 'agency_id' : _MergeAgencyId , 'agency_name' : self . _MergeIdentical , 'agency_url' : self ...
Merges two agencies .
31,147
def _MergeEntities ( self , a , b ) : distance = transitfeed . ApproximateDistanceBetweenStops ( a , b ) if distance > self . largest_stop_distance : raise MergeError ( "Stops are too far apart: %.1fm " "(largest_stop_distance is %.1fm)." % ( distance , self . largest_stop_distance ) ) scheme = { 'stop_id' : self . _Me...
Merges two stops .
31,148
def _UpdateAndMigrateUnmerged ( self , not_merged_stops , zone_map , merge_map , schedule ) : for stop , migrated_stop in not_merged_stops : if stop . zone_id in zone_map : migrated_stop . zone_id = zone_map [ stop . zone_id ] else : migrated_stop . zone_id = self . feed_merger . GenerateId ( stop . zone_id ) zone_map ...
Correct references in migrated unmerged stops and add to merged_schedule .
31,149
def DisjoinCalendars ( self , cutoff ) : def TruncatePeriod ( service_period , start , end ) : service_period . start_date = max ( service_period . start_date , start ) service_period . end_date = min ( service_period . end_date , end ) dates_to_delete = [ ] for k in service_period . date_exceptions : if ( k < start ) ...
Forces the old and new calendars to be disjoint about a cutoff date .
31,150
def CheckDisjointCalendars ( self ) : a_service_periods = self . feed_merger . a_schedule . GetServicePeriodList ( ) b_service_periods = self . feed_merger . b_schedule . GetServicePeriodList ( ) for a_service_period in a_service_periods : a_start , a_end = a_service_period . GetDateRange ( ) for b_service_period in b_...
Check whether any old service periods intersect with any new ones .
31,151
def _MergeEntities ( self , a , b ) : scheme = { 'price' : self . _MergeIdentical , 'currency_type' : self . _MergeIdentical , 'payment_method' : self . _MergeIdentical , 'transfers' : self . _MergeIdentical , 'transfer_duration' : self . _MergeIdentical } return self . _SchemedMerge ( scheme , a , b )
Merges the fares if all the attributes are the same .
31,152
def _MergeEntities ( self , a , b ) : if a . shape_id != b . shape_id : raise MergeError ( 'shape_id must be the same' ) distance = max ( ApproximateDistanceBetweenPoints ( a . points [ 0 ] [ : 2 ] , b . points [ 0 ] [ : 2 ] ) , ApproximateDistanceBetweenPoints ( a . points [ - 1 ] [ : 2 ] , b . points [ - 1 ] [ : 2 ] ...
Merges the shapes by taking the new shape .
31,153
def MergeDataSets ( self ) : rules = set ( ) for ( schedule , merge_map , zone_map ) in ( [ self . feed_merger . a_schedule , self . feed_merger . a_merge_map , self . feed_merger . a_zone_map ] , [ self . feed_merger . b_schedule , self . feed_merger . b_merge_map , self . feed_merger . b_zone_map ] ) : for fare in sc...
Merge the fare rule datasets .
31,154
def _FindLargestIdPostfixNumber ( self , schedule ) : postfix_number_re = re . compile ( '(\d+)$' ) def ExtractPostfixNumber ( entity_id ) : if entity_id is None : return 0 match = postfix_number_re . search ( entity_id ) if match is not None : return int ( match . group ( 1 ) ) else : return 0 id_data_sets = { 'agency...
Finds the largest integer used as the ending of an id in the schedule .
31,155
def GenerateId ( self , entity_id = None ) : self . _idnum += 1 if entity_id : return '%s_merged_%d' % ( entity_id , self . _idnum ) else : return 'merged_%d' % self . _idnum
Generate a unique id based on the given id .
31,156
def Register ( self , a , b , migrated_entity ) : if a is not None : self . a_merge_map [ a ] = migrated_entity a . _migrated_entity = migrated_entity if b is not None : self . b_merge_map [ b ] = migrated_entity b . _migrated_entity = migrated_entity
Registers a merge mapping .
31,157
def AddDefaultMergers ( self ) : self . AddMerger ( AgencyMerger ( self ) ) self . AddMerger ( StopMerger ( self ) ) self . AddMerger ( RouteMerger ( self ) ) self . AddMerger ( ServicePeriodMerger ( self ) ) self . AddMerger ( FareMerger ( self ) ) self . AddMerger ( ShapeMerger ( self ) ) self . AddMerger ( TripMerge...
Adds the default DataSetMergers defined in this module .
31,158
def GetMerger ( self , cls ) : for merger in self . _mergers : if isinstance ( merger , cls ) : return merger raise LookupError ( 'No matching DataSetMerger found' )
Looks for an added DataSetMerger derived from the given class .
31,159
def filter_line ( self , route ) : if self . _route_type is not None and self . _route_type != route . route_type : self . info ( 'Skipping route %s due to different route_type value (%s)' % ( route [ 'route_id' ] , route [ 'route_type' ] ) ) return self . info ( 'Filtering infrequent trips for route %s.' % route . rou...
Mark unusual trips for the given route .
31,160
def filter ( self , dataset ) : self . info ( 'Going to filter infrequent routes in the dataset' ) for route in dataset . routes . values ( ) : self . filter_line ( route )
Mark unusual trips for all the routes in the dataset .
31,161
def StopToTuple ( stop ) : return ( stop . stop_id , stop . stop_name , float ( stop . stop_lat ) , float ( stop . stop_lon ) , stop . location_type )
Return tuple as expected by javascript function addStopMarkerFromList
31,162
def FindDefaultFileDir ( ) : base = FindPy2ExeBase ( ) if base : return os . path . join ( base , 'schedule_viewer_files' ) else : base = os . path . dirname ( gtfsscheduleviewer . __file__ ) return os . path . join ( base , 'files' )
Return the path of the directory containing the static files . By default the directory is called files . The location depends on where setup . py put it .
31,163
def handle_json_GET_routepatterns ( self , params ) : schedule = self . server . schedule route = schedule . GetRoute ( params . get ( 'route' , None ) ) if not route : self . send_error ( 404 ) return time = int ( params . get ( 'time' , 0 ) ) date = params . get ( 'date' , "" ) sample_size = 3 pattern_id_trip_dict = ...
Given a route_id generate a list of patterns of the route . For each pattern include some basic information and a few sample trips .
31,164
def handle_json_wrapper_GET ( self , handler , parsed_params ) : schedule = self . server . schedule result = handler ( parsed_params ) content = ResultEncoder ( ) . encode ( result ) self . send_response ( 200 ) self . send_header ( 'Content-Type' , 'text/plain' ) self . send_header ( 'Content-Length' , str ( len ( co...
Call handler and output the return value in JSON .
31,165
def handle_json_GET_routes ( self , params ) : schedule = self . server . schedule result = [ ] for r in schedule . GetRouteList ( ) : result . append ( ( r . route_id , r . route_short_name , r . route_long_name ) ) result . sort ( key = lambda x : x [ 1 : 3 ] ) return result
Return a list of all routes .
31,166
def handle_json_GET_triprows ( self , params ) : schedule = self . server . schedule try : trip = schedule . GetTrip ( params . get ( 'trip' , None ) ) except KeyError : return route = schedule . GetRoute ( trip . route_id ) trip_row = dict ( trip . iteritems ( ) ) route_row = dict ( route . iteritems ( ) ) return [ [ ...
Return a list of rows from the feed file that are related to this trip .
31,167
def handle_json_GET_neareststops ( self , params ) : schedule = self . server . schedule lat = float ( params . get ( 'lat' ) ) lon = float ( params . get ( 'lon' ) ) limit = int ( params . get ( 'limit' ) ) stops = schedule . GetNearestStops ( lat = lat , lon = lon , n = limit ) return [ StopToTuple ( s ) for s in sto...
Return a list of the nearest limit stops to lat lon
31,168
def handle_json_GET_boundboxstops ( self , params ) : schedule = self . server . schedule n = float ( params . get ( 'n' ) ) e = float ( params . get ( 'e' ) ) s = float ( params . get ( 's' ) ) w = float ( params . get ( 'w' ) ) limit = int ( params . get ( 'limit' ) ) stops = schedule . GetStopsInBoundingBox ( north ...
Return a list of up to limit stops within bounding box with n e and s w in the NE and SW corners . Does not handle boxes crossing longitude line 180 .
31,169
def handle_json_GET_stoptrips ( self , params ) : schedule = self . server . schedule stop = schedule . GetStop ( params . get ( 'stop' , None ) ) time = int ( params . get ( 'time' , 0 ) ) date = params . get ( 'date' , "" ) time_trips = stop . GetStopTimeTrips ( schedule ) time_trips . sort ( ) time_trips = time_trip...
Given a stop_id and time in seconds since midnight return the next trips to visit the stop .
31,170
def MakeExpandedTrace ( frame_records ) : dump = [ ] for ( frame_obj , filename , line_num , fun_name , context_lines , context_index ) in frame_records : dump . append ( 'File "%s", line %d, in %s\n' % ( filename , line_num , fun_name ) ) if context_lines : for ( i , line ) in enumerate ( context_lines ) : if i == con...
Return a list of text lines for the given list of frame records .
31,171
def ParseAttributes ( self , problems ) : if util . IsEmpty ( self . shape_id ) : problems . MissingValue ( 'shape_id' ) return try : if not isinstance ( self . shape_pt_sequence , int ) : self . shape_pt_sequence = util . NonNegIntStringToInt ( self . shape_pt_sequence , problems ) elif self . shape_pt_sequence < 0 : ...
Parse all attributes calling problems as needed .
31,172
def SetFileContext ( self , file_name , row_num , row , headers ) : self . _context = ( file_name , row_num , row , headers )
Save the current context to be output with any errors .
31,173
def InvalidLineEnd ( self , bad_line_end , context = None , type = TYPE_WARNING ) : e = InvalidLineEnd ( bad_line_end = bad_line_end , context = context , context2 = self . _context , type = type ) self . AddToAccumulator ( e )
bad_line_end is a human readable string .
31,174
def GetDictToFormat ( self ) : d = { } for k , v in self . __dict__ . items ( ) : d [ k ] = util . EncodeUnicode ( v ) return d
Return a copy of self as a dict suitable for passing to FormatProblem
31,175
def FormatProblem ( self , d = None ) : if not d : d = self . GetDictToFormat ( ) output_error_text = self . __class__ . ERROR_TEXT % d if ( 'reason' in d ) and d [ 'reason' ] : return '%s\n%s' % ( output_error_text , d [ 'reason' ] ) else : return output_error_text
Return a text string describing the problem .
31,176
def FormatContext ( self ) : text = '' if hasattr ( self , 'feed_name' ) : text += "In feed '%s': " % self . feed_name if hasattr ( self , 'file_name' ) : text += self . file_name if hasattr ( self , 'row_num' ) : text += ":%i" % self . row_num if hasattr ( self , 'column_name' ) : text += " column %s" % self . column_...
Return a text string describing the context
31,177
def GetOrderKey ( self ) : context_attributes = [ '_type' ] context_attributes . extend ( ExceptionWithContext . CONTEXT_PARTS ) context_attributes . extend ( self . _GetExtraOrderAttributes ( ) ) tokens = [ ] for context_attribute in context_attributes : tokens . append ( getattr ( self , context_attribute , None ) ) ...
Return a tuple that can be used to sort problems into a consistent order .
31,178
def gtfs_to_graphviz ( gtfs , stop_ids = None ) : graph = GraphViz ( ) location_ids = choose_location_ids ( gtfs , stop_ids ) locations = [ gtfs . get_location ( i ) for i in location_ids ] for location in locations : if not location . parent_id : graph . add_cluster ( GraphCluster ( location . gtfs_id , location_label...
Reads GTFS data and returns GraphViz DOT file content as string .
31,179
def GetGtfsFactory ( self ) : if self . _gtfs_factory is None : from . import gtfsfactory self . _gtfs_factory = gtfsfactory . GetGtfsFactory ( ) return self . _gtfs_factory
Return the object s GTFS Factory .
31,180
def keys ( self ) : columns = set ( ) for name in vars ( self ) : if ( not name ) or name [ 0 ] == "_" : continue columns . add ( name ) return columns
Return iterable of columns used by this object .
31,181
def AddShapePointObjectUnsorted ( self , shapepoint , problems ) : if ( len ( self . sequence ) == 0 or shapepoint . shape_pt_sequence >= self . sequence [ - 1 ] ) : index = len ( self . sequence ) elif shapepoint . shape_pt_sequence <= self . sequence [ 0 ] : index = 0 else : index = bisect . bisect ( self . sequence ...
Insert a point into a correct position by sequence .
31,182
def GetPointWithDistanceTraveled ( self , shape_dist_traveled ) : if not self . distance : return None if shape_dist_traveled <= self . distance [ 0 ] : return self . points [ 0 ] if shape_dist_traveled >= self . distance [ - 1 ] : return self . points [ - 1 ] index = bisect . bisect ( self . distance , shape_dist_trav...
Returns a point on the shape polyline with the input shape_dist_traveled .
31,183
def AddStopTime ( self , stop , problems = None , schedule = None , ** kwargs ) : if problems is None : problems = problems_module . default_problem_reporter stoptime = self . GetGtfsFactory ( ) . StopTime ( problems = problems , stop = stop , ** kwargs ) self . AddStopTimeObject ( stoptime , schedule )
Add a stop to this trip . Stops must be added in the order visited .
31,184
def _AddStopTimeObjectUnordered ( self , stoptime , schedule ) : stop_time_class = self . GetGtfsFactory ( ) . StopTime cursor = schedule . _connection . cursor ( ) insert_query = "INSERT INTO stop_times (%s) VALUES (%s);" % ( ',' . join ( stop_time_class . _SQL_FIELD_NAMES ) , ',' . join ( [ '?' ] * len ( stop_time_cl...
Add StopTime object to this trip .
31,185
def ReplaceStopTimeObject ( self , stoptime , schedule = None ) : if schedule is None : schedule = self . _schedule new_secs = stoptime . GetTimeSecs ( ) cursor = schedule . _connection . cursor ( ) cursor . execute ( "DELETE FROM stop_times WHERE trip_id=? and " "stop_sequence=? and stop_id=?" , ( self . trip_id , sto...
Replace a StopTime object from this trip with the given one .
31,186
def AddStopTimeObject ( self , stoptime , schedule = None , problems = None ) : if schedule is None : schedule = self . _schedule if schedule is None : warnings . warn ( "No longer supported. _schedule attribute is used to get " "stop_times table" , DeprecationWarning ) if problems is None : problems = schedule . probl...
Add a StopTime object to the end of this trip .
31,187
def GetCountStopTimes ( self ) : cursor = self . _schedule . _connection . cursor ( ) cursor . execute ( 'SELECT count(*) FROM stop_times WHERE trip_id=?' , ( self . trip_id , ) ) return cursor . fetchone ( ) [ 0 ]
Return the number of stops made by this trip .
31,188
def ClearStopTimes ( self ) : cursor = self . _schedule . _connection . cursor ( ) cursor . execute ( 'DELETE FROM stop_times WHERE trip_id=?' , ( self . trip_id , ) )
Remove all stop times from this trip .
31,189
def GetStopTimes ( self , problems = None ) : cursor = self . _schedule . _connection . cursor ( ) cursor . execute ( 'SELECT arrival_secs,departure_secs,stop_headsign,pickup_type,' 'drop_off_type,shape_dist_traveled,stop_id,stop_sequence,timepoint ' 'FROM stop_times ' 'WHERE trip_id=? ' 'ORDER BY stop_sequence' , ( se...
Return a sorted list of StopTime objects for this trip .
31,190
def GetFrequencyStopTimes ( self , problems = None ) : stoptimes_list = [ ] stoptime_pattern = self . GetStopTimes ( ) first_secs = stoptime_pattern [ 0 ] . arrival_secs stoptime_class = self . GetGtfsFactory ( ) . StopTime for run_secs in self . GetFrequencyStartTimes ( ) : stoptimes = [ ] for st in stoptime_pattern :...
Return a list of StopTime objects for each headway - based run .
31,191
def GetFrequencyStartTimes ( self ) : start_times = [ ] for freq_tuple in self . GetFrequencyTuples ( ) : ( start_secs , end_secs , headway_secs ) = freq_tuple [ 0 : 3 ] run_secs = start_secs while run_secs < end_secs : start_times . append ( run_secs ) run_secs += headway_secs return start_times
Return a list of start time for each headway - based run .
31,192
def _GenerateStopTimesTuples ( self ) : stoptimes = self . GetStopTimes ( ) for i , st in enumerate ( stoptimes ) : yield st . GetFieldValuesTuple ( self . trip_id )
Generator for rows of the stop_times file
31,193
def GetPattern ( self ) : stoptimes = self . GetStopTimes ( ) return tuple ( st . stop for st in stoptimes )
Return a tuple of Stop objects in the order visited
31,194
def AddHeadwayPeriodObject ( self , headway_period , problem_reporter ) : warnings . warn ( "No longer supported. The HeadwayPeriod class was renamed to " "Frequency, and all related functions were renamed " "accordingly." , DeprecationWarning ) self . AddFrequencyObject ( frequency , problem_reporter )
Deprecated . Please use AddFrequencyObject instead .
31,195
def AddFrequencyObject ( self , frequency , problem_reporter ) : if frequency is not None : self . AddFrequency ( frequency . StartTime ( ) , frequency . EndTime ( ) , frequency . HeadwaySecs ( ) , frequency . ExactTimes ( ) , problem_reporter )
Add a Frequency object to this trip s list of Frequencies .
31,196
def AddHeadwayPeriod ( self , start_time , end_time , headway_secs , problem_reporter = problems_module . default_problem_reporter ) : warnings . warn ( "No longer supported. The HeadwayPeriod class was renamed to " "Frequency, and all related functions were renamed " "accordingly." , DeprecationWarning ) self . AddFre...
Deprecated . Please use AddFrequency instead .
31,197
def Validate ( self , problems , validate_children = True ) : self . ValidateRouteId ( problems ) self . ValidateServicePeriod ( problems ) self . ValidateDirectionId ( problems ) self . ValidateTripId ( problems ) self . ValidateShapeIdsExistInShapeList ( problems ) self . ValidateRouteIdExistsInRouteList ( problems )...
Validate attributes of this object .
31,198
def ValidateChildren ( self , problems ) : assert self . _schedule , "Trip must be in a schedule to ValidateChildren" self . ValidateNoDuplicateStopSequences ( problems ) stoptimes = self . GetStopTimes ( problems ) stoptimes . sort ( key = lambda x : x . stop_sequence ) self . ValidateTripStartAndEndTimes ( problems ,...
Validate StopTimes and headways of this trip .
31,199
def GetFieldValuesTuple ( self , trip_id ) : result = [ ] for fn in self . _FIELD_NAMES : if fn == 'trip_id' : result . append ( trip_id ) else : result . append ( getattr ( self , fn ) or '' ) return tuple ( result )
Return a tuple that outputs a row of _FIELD_NAMES to be written to a GTFS file .