コード例 #1
0
def test_compare():
    test_data_a = trip.build_master_dict(json_chunk_a)
    test_data_b = trip.build_master_dict(json_chunk_b)
    trip_a = trip.Trip(test_data_a, test_data_a['Hotspot Names'])
    trip_b = trip.Trip(test_data_b, test_data_b['Hotspot Names'])
    assert trip_a.compare(trip_b) == {
        'Snow Goose': 0.0,
        'Canada Goose': -0.19037,
        'Black-bellied Whistling-Duck': 0.08276,
        'Brant': -0.09112,
        'Wood Duck': -0.55455,
        'Mute Swan': -0.74535
    }
コード例 #2
0
 def get(self):
     my_trip = trip.Trip()
     my_trip.t_date = self.request.get('date')
     my_trip.w_email = self.request.get('w_email')
     my_trip.dogID = self.request.get('dogID')
     my_trip.insertToDb()
     user = users.get_current_user()
     if user:
         parameters_for_template = {"user": user}
         template = jinja_environment.get_template('/owner_home.html')
         self.response.write(template.render(parameters_for_template))
コード例 #3
0
ファイル: trip_app.py プロジェクト: gzt0605/unit9
def main():
    '''
    main function
    :return:
    '''
    import trip

    # fetch data
    my_trip = trip.Trip('Sandy Spring, MD', 'New York, NY')

    # print the results
    print('Distance: ' + my_trip.distance('driving') + 'm ')
    print('Duration: ' + my_trip.duration())
    print(my_trip)
コード例 #4
0
class TripParser:
    actions = {
        "TRIP": [
            lambda _, n: trip.Trip(comment1=n[4],
                                   comment2=n[5],
                                   line1=n[8],
                                   line2=n[9],
                                   line3=n[10],
                                   station=n[16],
                                   lines=n[22])
        ],
        "NONEMPTY_LINE": [lambda _, n: n[0]],
        "STATION_TYP2_GROUP": [lambda _, n: int(n[1])],
        "STATION_TYP2_GROUP_LIST":
        [lambda _, n: [n[0]], lambda _, n: n[0] + [n[1]]],
        "STATION_GROUP": [
            lambda _, n: trip.Station(id=n[1],
                                      interval=n[2],
                                      name=n[3],
                                      tile_index=n[4],
                                      line5=n[5],
                                      line6=n[6],
                                      line7=n[7],
                                      line8=n[8])
        ],
        "STATION_GROUP_LIST":
        [lambda _, n: [n[0]], lambda _, n: n[0] + [n[1]]],
        "STATIONS": [lambda _, n: n[0], lambda _, n: n[0]],
        "OPTIONAL_LINE": [lambda _, n: "", lambda _, n: n[0]],
        "LINES": [lambda _, n: [n[0]], lambda _, n: n[0] + [n[1]]],
    }

    def __init__(self):
        self.grammar = parglare.Grammar.from_file(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "trip_grammar.pg"))
        self.parser = parglare.Parser(self.grammar,
                                      actions=self.actions,
                                      ws="\r")

    def parse(self, file_name):
        with open(file_name, encoding="iso-8859-1") as f:
            content = f.read()
        return self.parser.parse(content)
コード例 #5
0
    def getAllTrips(self, email):
        self.t_DbHandler.connectToDb()
        cursor = self.t_DbHandler.getCursor()
        sql = '''select trip.dogID, t_date, dog.d_name, dog.d_breed, dog.d_age, trip.w_from_home
        from_home from trip join dog on dog.dogID = trip.dogID  
        where trip.w_email = '%s'; ''' % (email, )
        logging.error(sql)
        cursor.execute(sql)
        trip_records = cursor.fetchall()
        for trip_record in trip_records:
            current_trip = trip.Trip()
            current_trip.d_name = trip_record[2]
            current_trip.t_date = trip_record[1]
            current_trip.t_fromHome = 'Yes' if trip_record[
                5] == 1 else 'No'  #if the value is 1, the user wants a trip from home

            current_trip.dogID = trip_record[0]
            current_trip.d_age = trip_record[4]
            current_trip.d_breed = trip_record[3]

            self.t_RetrievedTripsList.append(current_trip)
        self.t_DbHandler.disconnectFromDb()
        return self.t_RetrievedTripsList
コード例 #6
0
 def setUp(self):
     self.trip = trip.Trip(SEATTLE_ORIGIN, SEATTLE_DESTINATION, 'mode',
                           DISTANCE, DURATION, BASKET_CATEGORY, PAIR,
                           DEPARTURE_TIME, RANK)
コード例 #7
0
    def __init__(
        self,
        Facility_Name,
        facility_type,
        Distance_per_lift,
        Distance_to_TransferStation,
        Total_tonnes_collected,
        Number_bin_per_hhold,
        number_hhold,
        Transfer_Station,
        Processing_Facility,
        Transfer_Distance,
    ):

        self.Facility_Name = Facility_Name
        self.facility_type = facility_type
        self.Distance_per_lift = Distance_per_lift
        self.Distance_to_TransferStation = Distance_to_TransferStation
        self.Total_tonnes_collected = Total_tonnes_collected
        self.Number_bin_per_hhold = Number_bin_per_hhold
        self.number_hhold = number_hhold
        self.Transfer_Station = Transfer_Station
        self.Processing_Facility = Processing_Facility
        self.Transfer_Distance = Transfer_Distance

        ###########################################################################################################
        #processing facility

        #grab composition
        self.waste_composition_class = Co.Waste_Composition()
        #grab mat diversion per facility
        self.Material_Diversion_class = WF.Facility_Type()

        self.WP = Prcss.Processing(self.Facility_Name,
                                   self.waste_composition_class,
                                   self.Material_Diversion_class)
        self.WP.Material_Recovery(facility_type)

        self.total_landfill_in_t = self.WP.total_for_landfill
        self.total_processed = self.WP.total_processed
        print("total landfill in t = ", self.WP.total_for_landfill,
              " total processed = ", self.WP.total_processed)

        ###########################################################################################################
        #waste stream
        self.WasteCompo = self.waste_composition_class.Waste_Composition
        self.WS = wststream.WasteStream(self.WasteCompo)

        #self.WS.verification()
        for compo in self.WS.Waste_Composition:
            self.WS.landfill_emissions_per_t(compo)
            print(compo, " total emissions per t = ",
                  self.WS.total_emission_per_t)

        ###########################################################################################################
        #trip from households to transfer station
        self.Trucks = TR.trucks()
        for collection_truck in self.Trucks.collection_trucks:
            self.TRP = Trp.Trip(collection_truck, self.Distance_per_lift,
                                self.Distance_to_TransferStation,
                                self.Total_tonnes_collected,
                                self.Number_bin_per_hhold, self.number_hhold)
            self.TRP.total_emissions()
            self.TRP.costs()
            print("Collection truck = ", collection_truck,
                  " total emissions in t CO2 = ", self.TRP.tCO2,
                  " total liftcost = ", self.TRP.lift_costs)

        ###########################################################################################################
        #transfert from transfert station to processing facility
        for transfer_truck in self.Trucks.transfer_trucks:
            self.TRANS = Trf.Transfer(transfer_truck, self.Transfer_Station,
                                      self.Processing_Facility,
                                      self.Transfer_Distance,
                                      self.Total_tonnes_collected)
            self.TRANS.total_emissions()
            self.TRANS.costs()
            print("transfer truck = ", transfer_truck,
                  " total emissions in t CO2 = ", self.TRANS.tCO2,
                  " total transfercost = ", self.TRANS.transfer_costs)

        return
コード例 #8
0
def all_itinerary_trips(itin):
    """Get all trips conforming to a given Itinerary (object instance)"""
    # if that itinerary is just walking, return nothing
    if itin.is_walking:
        return []
    # query can take more than a second
    c = cursor()
    c.execute(
        """
		WITH RECURSIVE sub(depth,trips,departure,arrival) AS (
			SELECT 
				1 AS depth,
				ARRAY[t.trip_id] AS trips,
				orig.etime - (%(walk_times)s)[1] AS departure,
				dest.etime + (%(walk_times)s)[2] AS arrival
			FROM ttc_stop_times AS orig
				JOIN ttc_trips AS t
					ON t.trip_id = orig.trip_id
				JOIN ttc_stop_times AS dest
					ON t.trip_id = dest.trip_id 
				WHERE 
					orig.stop_uid = (%(o_stops)s)[1] AND
					dest.stop_uid = (%(d_stops)s)[1] AND
					orig.stop_sequence < dest.stop_sequence AND
					-- departure is within time window
					orig.local_time - '10 minutes'::interval BETWEEN 
						%(window_start)s::time AND 
						%(window_end)s::time + '30 minutes'::interval
						
			UNION
			
			SELECT depth, trips, departure, arrival
			FROM (
				SELECT 
					sub.depth + 1 AS depth,
					sub.trips || t.trip_id AS trips,
					sub.departure,
					dest.etime + (%(walk_times)s)[sub.depth+2] AS arrival,
					row_number() OVER (PARTITION BY sub.trips ORDER BY orig.etime, dest.etime ASC)
				FROM sub, ttc_stop_times AS orig
				JOIN ttc_trips AS t
					ON t.trip_id = orig.trip_id
				JOIN ttc_stop_times AS dest
					ON t.trip_id = dest.trip_id 
				WHERE 
					orig.stop_uid = (%(o_stops)s)[sub.depth+1] AND
					dest.stop_uid = (%(d_stops)s)[sub.depth+1] AND
					orig.etime >= sub.arrival AND
					orig.etime < sub.arrival + 3600 AND
					orig.stop_sequence < dest.stop_sequence
			) AS whatev
			WHERE row_number = 1
		)
		SELECT departure, arrival, trips FROM sub WHERE depth = %(final_depth)s;""",
        {
            'o_stops': itin.o_stops,
            'd_stops': itin.d_stops,
            'walk_times': itin.walk_times,
            'final_depth': len(itin.routes),
            'window_start': str(config.window_start_time),
            'window_end': str(config.window_end_time)
        })
    trips = []
    for depart, arrive, trip_ids in c.fetchall():
        trips.append(trip.Trip(depart, arrive, itin.otp_string, trip_ids))
    return trips
コード例 #9
0
    def __init__(self, id, user, trip):
        self.id = id
        self.user = user
        self.trip = trip
        self.amount = float(user.count) * float(trip.cost)

    def showDetails(self):
        print(self.id) 
        print("user details : ", self.user.showDetails())
        print("trip details : ")
        self.trip.showDetails()
        print("Total Amount", self.amount)



trip_1 = trip.Trip("Shatabdi", "Delhi", "Bangluru", "2 Days", "2500")

# trip_1.showDetails()

user_1 = user.User("kanishk", "debnath", 23, "male", "8130692843", 4)

print("start of program")

# print(user_1.showDetails())
# print(user_1.fullname())
# print(user_1.age)

ticket_1 = Ticket(101, user_1, trip_1)

ticket_1.showDetails()
コード例 #10
0
import ticket
import user
import trip

# defining trips available for booking
trips = []
trip_1 = trip.Trip("Shatabdi", "Delhi", "Bangluru", "2 Days 7 hours", 2500)
trip_2 = trip.Trip("Gareeb Rath", "Patna", "Lucknow", "1 Days 3 hours", 500)

# append trips to the list called trips
trips.append(trip_1)
trips.append(trip_2)


def showTrip():
    count = 1
    for t in trips:
        print("Trip number : ", count)
        t.showDetails()
        count = count + 1


def bookTicket():
    showTrip()
    tripNumber = int(input("Enter the trip you want to select: "))
    passengerTrip = trips[tripNumber - 1]

    print("Enter Passenger details : ")
    firstname = input("Enter your first name :")
    lastname = input("Enter your last name :")
    age = input("Enter your age :")
コード例 #11
0
def test_inequality():
    test_data_a = trip.build_master_dict(json_chunk_a)
    test_data_b = trip.build_master_dict(json_chunk_b)
    trip_a = trip.Trip(test_data_a, test_data_a['Hotspot Names'])
    trip_b = trip.Trip(test_data_b, test_data_b['Hotspot Names'])
    assert trip_a != trip_b
コード例 #12
0
def trip_fixture():
    '''Test Trip creation with fixed data.'''
    test_data = trip.build_master_dict(json_chunk_a)
    return trip.Trip(test_data, test_data['Hotspot Names'])
コード例 #13
0
        'Brant': -0.09112,
        'Wood Duck': -0.55455,
        'Mute Swan': -0.74535
    }


def test_random_trip():
    rand_trip = trip.random_trip(trip.MASTER_ROUTE, 3)
    assert rand_trip is not None


def test_specialties():
    pass


if __name__ == "__main__":
    pytest.main()
    test_data_a = trip.build_master_dict(json_chunk_a)
    test_data_b = trip.build_master_dict(json_chunk_b)
    trip_a = trip.Trip(test_data_a, test_data_a['Hotspot Names'])
    trip_b = trip.Trip(test_data_b, test_data_b['Hotspot Names'])
    for bird in trip_a.birds.items():
        print(bird)
    for bird in trip_b.birds.items():
        print(bird)
    print(trip_a.compare(trip_b))
    print(trip_b.compare(trip_a))

    rand_trip = trip.random_trip(trip.MASTER_ROUTE, 3)
    print(rand_trip.hotspots)
コード例 #14
0
ファイル: build_single_trip.py プロジェクト: fagan2888/axon
def build_single_trip(trip, CONFIG):

    # 6 preceding/following departure/arrival
    loop_through = [(6, True), (6, False), (-6, True), (-6, False)]
    # Multi-threaded API calls (returns fifo queue of responses)
    q_out = multithread_api_queries(trip, loop_through, CONFIG)

    # Initialize empty dataframe with the right column structure for easy concatenation later
    # trip_link_df, itinerary_df, legs_df, segments_df = ids.initialize_all_empty_df()
    newTrip = tr.Trip(trip, CONFIG)

    while not q_out.empty():
        # Pop one response for processing
        response = q_out.get()

        # extracts the valuable information from the API query and stores it into pandas dataframes
        #  (This runs in about 0.04 seconds per response.content, not a bottleneck anymore)
        # trip_link_df_i, itinerary_df_i, legs_df_i, segments_df_i = \
        #     build_single_itinerary(response.content, trip, itinerary_df['context_reconstruction'].values, CONFIG)
        newTrip.build_single_itinerary(sbb_response.SBBResponse(response))

        # Update the dataframe with new items
        # we can do this later now
        # trip_link_df = pd.concat([trip_link_df, trip_link_df_i], ignore_index=True)
        # itinerary_df = pd.concat([itinerary_df, itinerary_df_i])
        # legs_df = pd.concat([legs_df, legs_df_i])
        # segments_df = pd.concat([segments_df, segments_df_i])

    newTrip.concat_trip_dfs()
    newTrip.concat_legs_dfs()
    newTrip.concat_seg_dfs()
    # Only perform these on non-empty dataframes
    # if not trip_link_df.empty:
    #     # These values are shared across all rows so add them at once
    #     trip_link_df['vid'] = trip['vid']
    #     trip_link_df['mot_segment_id'] = trip['mot_segment_id']
    #
    #     # Not using vid / mot_segment_id as indexes since they're identical for all...
    #     # Hierarchical indexes need to be sorted for faster operation (uses np.searchsorted )
    #     trip_link_df.sort_values(['itinerary_id', 'leg_id', 'segment_id', ], inplace=True)
    #
    #     trip_link_df.set_index(['itinerary_id', 'leg_id', 'segment_id', ], inplace=True)
    #
    # return trip_link_df, itinerary_df, legs_df, segments_df
    if not newTrip.trip_link_df.empty:
        # These values are shared across all rows so add them at once
        newTrip.trip_link_df['vid'] = trip['vid']
        newTrip.trip_link_df['mot_segment_id'] = trip['mot_segment_id']

        # Not using vid / mot_segment_id as indexes since they're identical for all...
        # Hierarchical indexes need to be sorted for faster operation (uses np.searchsorted )
        newTrip.trip_link_df.sort_values([
            'itinerary_id',
            'leg_id',
            'segment_id',
        ],
                                         inplace=True)

        newTrip.trip_link_df.set_index([
            'itinerary_id',
            'leg_id',
            'segment_id',
        ],
                                       inplace=True)

    return newTrip.trip_link_df, newTrip.itinerary_df, newTrip.legs_df, newTrip.segments_df
コード例 #15
0
ファイル: block.py プロジェクト: songsc/google_transit
 def add_trip(self, bid, tid, direct, headsign, origin, depart, destin, arrival, shape):
     if self.bid == "null": self.bid = bid
     trip = t.Trip(bid, tid, direct, headsign, origin, depart, destin, arrival, shape)
     self.trips.insert(0, trip)
コード例 #16
0
ファイル: Triples.py プロジェクト: yashagrawal3/triples
    def run(self, restore=False):
        g.init()
        pygame.init()
        pygame.display.init()
        if not self.journal:
            utils.load()
        self.trip = trip.Trip(self.sugar, self.label, self.colors[0])
        self.trip.setup()
        load_save.retrieve()
        self.buttons_setup()
        if self.canvas is not None:
            self.canvas.grab_focus()
        ctrl = False
        pygame.key.set_repeat(600, 120)
        key_ms = pygame.time.get_ticks()
        going = True
        while going:
            if self.journal:
                # Pump GTK messages.
                while Gtk.events_pending():
                    Gtk.main_iteration()

            # Pump PyGame messages.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    # only in standalone version
                    if not self.journal:
                        utils.save()
                    going = False
                elif event.type == pygame.MOUSEMOTION:
                    g.pos = event.pos
                    self.trip.check_mouse()
                    g.redraw = True
                    if self.canvas is not None:
                        self.canvas.grab_focus()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    g.redraw = True
                    if event.button == 1:
                        bu = buttons.check()
                        if bu != '':
                            self.do_button(bu)
                        else:
                            if self.trip.check_mouse():
                                self.do_click()
                        self.flush_queue()
                elif event.type == pygame.KEYDOWN:
                    # throttle keyboard repeat
                    if pygame.time.get_ticks() - key_ms > 110:
                        key_ms = pygame.time.get_ticks()
                        if ctrl:
                            if event.key == pygame.K_q:
                                if not self.journal:
                                    utils.save()
                                going = False
                                break
                            else:
                                ctrl = False
                        if event.key in (pygame.K_LCTRL, pygame.K_RCTRL):
                            ctrl = True
                            break
                        self.do_key(event.key)
                        g.redraw = True
                        self.flush_queue()
                elif event.type == pygame.KEYUP:
                    ctrl = False
            if not going:
                break
            if g.redraw:
                self.display()
                if g.version_display:
                    utils.version_display()
                g.screen.blit(g.pointer, g.pos)
                pygame.display.flip()
                g.redraw = False
                if self.trip.delay:
                    pygame.time.delay(1000)
                    self.trip.delay = False
                    self.trip.gone()
                    g.redraw = True
                    self.trip.complete()
            g.clock.tick(40)
コード例 #17
0
def query(input_date, input_route):

    # TO DO: Implement exception handling!
    F_dates = open("data/calendar_dates.txt", 'rt')
    reader_dates = csv.reader(F_dates)
    F_trips = open("data/trips.txt", 'rt')
    reader_trips = csv.reader(F_trips)
    F_times = open("data/stop_times.txt", 'rt')
    reader_times = csv.reader(F_times)
    F_stops = open("data/stops.txt", 'rt')
    reader_stops = csv.reader(F_stops)

    # Make sure the date is in range.
    for date in reader_dates:
        if input_date == date[0]: break
    if input_date != date[0]:
        return "Error: Date out of range"

    out_date_blocks = "output/trips/" + input_date + "_trips.txt"
    F_date_blocks = open(out_date_blocks, 'w')
    writer_date_blocks = csv.writer(F_date_blocks)
    out_date_stops = "output/stops/" + input_date + "_stops.txt"
    F_date_stops = open(out_date_stops, 'w')
    writer_date_stops = csv.writer(F_date_stops)

    trip = next(reader_trips)
    times1 = next(reader_times)
    stop = next(reader_stops)
    # Write headers
    writer_date_blocks.writerow([
        trip[6], trip[2], trip[5], trip[3], "origin", times1[2], "destination",
        times1[1]
    ])  # Header
    writer_date_stops.writerow(
        [stop[0], stop[1], times1[2], times1[4], stop[2], stop[3]])
    times1 = next(reader_times)

    blocks = []  # List of blocks
    temp_block = b.Block()  # A single block element
    trip_count = 0
    for trip in reader_trips:
        # Move to the selected date
        if input_date != "" and trip[1] != input_date: continue

        trip_count += 1
        new_trip = t.Trip(trip[6], trip[2], trip[5], trip[3], "", "", "", "",
                          trip[7])
        temp_stop_list = []

        while times1[0] != trip[2]:
            times2 = times1
            try:
                times1 = next(reader_times)
            except StopIteration:
                break

        # Only interested in the stop times at the origin and destination.
        # Since stop times are listed in reverse chronological order,
        # the first line for each trip is the arrival time,
        # and the last line for each trip is the departure time.
        arrival = times1[1]
        destin_id = times1[3]
        while times1[0] == trip[2]:
            new_stop = s.Stop(times1[3], "", times1[2], times1[4], "", "")
            temp_stop_list.insert(0, new_stop)
            times2 = times1
            try:
                times1 = next(reader_times)
            except StopIteration:
                break
        depart = times2[1]
        origin_id = times2[3]

        origin = "null"
        destin = "null"

        while origin == "null" or destin == "null" or len(temp_stop_list) != 0:
            try:
                stop = next(reader_stops)
                if stop[0] == origin_id: origin = stop[1]
                if stop[0] == destin_id: destin = stop[1]
                for temp_stop in temp_stop_list:
                    if stop[0] == temp_stop.stop_id:
                        temp_stop_list.remove(temp_stop)
                        temp_stop.stop_name = stop[1]
                        temp_stop.lat = stop[2]
                        temp_stop.lon = stop[3]
                        new_trip.add_stop_ref(temp_stop)
            except StopIteration:
                F_stops.seek(0)

        new_trip.update_origin(origin, depart)
        new_trip.update_destin(destin, arrival)

        if temp_block.get_bid() == "null" or temp_block.get_bid() == trip[6]:
            temp_block.add_trip_ref(new_trip)
        else:
            blocks.insert(0, temp_block)
            temp_block = b.Block()
            temp_block.add_trip_ref(new_trip)
    # Make sure to add the last block
    blocks.insert(0, temp_block)

    for block in blocks:
        block.write_block(writer_date_blocks)
        block.write_stops(writer_date_stops)

    F_dates.close()
    F_trips.close()
    F_times.close()
    F_stops.close()
    F_date_blocks.close()
    F_date_stops.close()

    return ("Found %d trips. Check output folder." % (trip_count))