Friday, March 21, 2025

A simple Python program using the OpenWeatherMap API to check the current weather of a city:

 Here is a simple Python program using the OpenWeatherMap API to check the current weather of a city:


```

import requests

import json


def get_weather(city, api_key):

    base_url = "http://api.openweathermap.org/data/2.5/weather"

    params = {

        "q": city,

        "units": "metric",

        "appid": api_key

    }

    response = requests.get(base_url, params=params)

    weather_data = response.json()

    return weather_data


def print_weather(weather_data):

    city = weather_data["name"]

    country = weather_data["sys"]["country"]

    temperature = weather_data["main"]["temp"]

    humidity = weather_data["main"]["humidity"]

    weather_description = weather_data["weather"][0]["description"]


    print(f"Weather in {city}, {country}:")

    print(f"Temperature: {temperature}°C")

    print(f"Humidity: {humidity}%")

    print(f"Weather: {weather_description}")


def main():

    api_key = "YOUR_OPENWEATHERMAP_API_KEY"

    city = input("Enter the city name: ")

    weather_data = get_weather(city, api_key)

    print_weather(weather_data)


if __name__ == "__main__":

    main()

```


To use this program, you need to:


1. Get an API key from OpenWeatherMap (https://home.openweathermap.org/users/sign_up)

2. Replace `YOUR_OPENWEATHERMAP_API_KEY` with your actual API key

3. Run the program and enter the city name when prompted


Note: This program uses the metric system for temperature. If you prefer Fahrenheit, change the `"units"` parameter in the `get_weather` function to `"imperial"`.


For mobile devices, you can create a mobile app using a framework like React Native or Flutter, and use the same API to fetch the weather data.


To get the current location of the device, you can use the Geolocation API (https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) in JavaScript or the equivalent API in your chosen mobile app framework.


Here's an example of how to use the Geolocation API to get the current location:


```

navigator.geolocation.getCurrentPosition(position => {

    const latitude = position.coords.latitude;

    const longitude = position.coords.longitude;

    // Use the latitude and longitude to fetch the weather data

});

```


Program that simulates a bus ticket booking system:

 Write a program to save the database and make a bus ticket for passengers with travel date time and seat no amount of ticket paid having information of number of adults childrens and senior citizens on the tickets



Here's a simple Java program that simulates a bus ticket booking system:



import java.time.LocalDate;

import java.time.LocalTime;

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;


class BusTicket {

    private String ticketId;

    private String travelDate;

    private String travelTime;

    private String seatNo;

    private double amountPaid;

    private int adults;

    private int children;

    private int seniorCitizens;


    public BusTicket(String ticketId, String travelDate, String travelTime, String seatNo, double amountPaid, int adults, int children, int seniorCitizens) {

        this.ticketId = ticketId;

        this.travelDate = travelDate;

        this.travelTime = travelTime;

        this.seatNo = seatNo;

        this.amountPaid = amountPaid;

        this.adults = adults;

        this.children = children;

        this.seniorCitizens = seniorCitizens;

    }


    public String getTicketId() {

        return ticketId;

    }


    public String getTravelDate() {

        return travelDate;

    }


    public String getTravelTime() {

        return travelTime;

    }


    public String getSeatNo() {

        return seatNo;

    }


    public double getAmountPaid() {

        return amountPaid;

    }


    public int getAdults() {

        return adults;

    }


    public int getChildren() {

        return children;

    }


    public int getSeniorCitizens() {

        return seniorCitizens;

    }

}


public class BusTicketBookingSystem {

    private Map<String, BusTicket> tickets;

    private Scanner scanner;


    public BusTicketBookingSystem() {

        tickets = new HashMap<>();

        scanner = new Scanner(System.in);

    }


    public void bookTicket() {

        System.out.print("Enter ticket ID: ");

        String ticketId = scanner.nextLine();

        System.out.print("Enter travel date (yyyy-MM-dd): ");

        String travelDate = scanner.nextLine();

        System.out.print("Enter travel time (HH:mm): ");

        String travelTime = scanner.nextLine();

        System.out.print("Enter seat number: ");

        String seatNo = scanner.nextLine();

        System.out.print("Enter amount paid: ");

        double amountPaid = scanner.nextDouble();

        scanner.nextLine(); // Consume newline left-over

        System.out.print("Enter number of adults: ");

        int adults = scanner.nextInt();

        scanner.nextLine(); // Consume newline left-over

        System.out.print("Enter number of children: ");

        int children = scanner.nextInt();

        scanner.nextLine(); // Consume newline left-over

        System.out.print("Enter number of senior citizens: ");

        int seniorCitizens = scanner.nextInt();

        scanner.nextLine(); // Consume newline left-over


        BusTicket ticket = new BusTicket(ticketId, travelDate, travelTime, seatNo, amountPaid, adults, children, seniorCitizens);

        tickets.put(ticketId, ticket);


        System.out.println("Ticket booked successfully!");

    }


    public void displayTicket() {

        System.out.print("Enter ticket ID: ");

        String ticketId = scanner.nextLine();


        BusTicket ticket = tickets.get(ticketId);

        if (ticket != null) {

            System.out.println("Ticket ID: " + ticket.getTicketId());

            System.out.println("Travel Date: " + ticket.getTravelDate());

            System.out.println("Travel Time: " + ticket.getTravelTime());

            System.out.println("Seat Number: " + ticket.getSeatNo());

            System.out.println("Amount Paid: " + ticket.getAmountPaid());

            System.out.println("Number of Adults: " + ticket.getAdults());

            System.out.println("Number of Children: " + ticket.getChildren());

            System.out.println("Number of Senior Citizens: " + ticket.getSeniorCitizens());

        } else {

            System.out.println("Ticket not found!");

        }

    }


    public void run() {

        while (true) {

            System.out.println("1. Book Ticket");

            System.out.println("2. Display Ticket");

            System.out.println("3. Exit");

            System.out.print("Enter your choice: ");

            int choice = scanner.nextInt();

            scanner.nextLine(); // Consume newline left-over


            switch (choice) {

                case 1:

                    bookTicket();

                    break;

                case 2:

                    displayTicket();

                    break;

                case 3:

                    System.exit(0);

                default:

                    System.out.println("Invalid choice. Please try again.");

            }

        }

    }


    public static void main(String[] args) {

        BusTicketBookingSystem system = new BusTicketBookingSystem();

        system.run();

    }

}





This program allows users to:


1. Book a ticket by entering ticket ID, travel date, travel time, seat number, amount paid, and number of adults, children, and senior citizens.

2. Display a ticket by entering the ticket ID.

3. Exit the program.




Write SQL query to save the above database with connection


Here is an example SQL query to create a database and a table to store the bus ticket information:



-- Create a database

CREATE DATABASE BusTicketBooking;


-- Use the database

USE BusTicketBooking;


-- Create a table to store bus ticket information

CREATE TABLE BusTickets (

    TicketID INT PRIMARY KEY,

    TravelDate DATE,

    TravelTime TIME,

    SeatNumber VARCHAR(10),

    AmountPaid DECIMAL(10, 2),

    Adults INT,

    Children INT,

    SeniorCitizens INT

);


-- Insert some sample data into the table

INSERT INTO BusTickets (TicketID, TravelDate, TravelTime, SeatNumber, AmountPaid, Adults, Children, SeniorCitizens)

VALUES

(1, '2022-01-01', '08:00:00', 'A1', 100.00, 2, 1, 0),

(2, '2022-01-02', '09:00:00', 'B2', 120.00, 1, 2, 1),

(3, '2022-01-03', '10:00:00', 'C3', 150.00, 3, 0, 1);


-- Create a connection to the database

-- This will vary depending on the programming language and database driver being used

-- For example, in Java using MySQL Connector/J:

-- String url = "jdbc:mysql://localhost:3306/BusTicketBooking";

-- String username = "your_username";

-- String password = "your_password";

-- Connection conn = DriverManager.getConnection(url, username, password);



To connect to the database and execute SQL queries in Java, you can use the following code:



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;


public class BusTicketBookingSystem {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/BusTicketBooking";

    private static final String USERNAME = "your_username";

    private static final String PASSWORD = "your_password";


    public static void main(String[] args) {

        try {

            Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);

            System.out.println("Connected to the database!");


            // Create a prepared statement to insert data into the BusTickets table

            String sql = "INSERT INTO BusTickets (TicketID, TravelDate, TravelTime, SeatNumber, AmountPaid, Adults, Children, SeniorCitizens) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

            PreparedStatement pstmt = conn.prepareStatement(sql);


            // Set the values for the prepared statement

            pstmt.setInt(1, 4);

            pstmt.setDate(2, java.sql.Date.valueOf("2022-01-04"));

            pstmt.setTime(3, java.sql.Time.valueOf("11:00:00"));

            pstmt.setString(4, "D4");

            pstmt.setDouble(5, 180.00);

            pstmt.setInt(6, 2);

            pstmt.setInt(7, 1);

            pstmt.setInt(8, 1);


            // Execute the prepared statement

            pstmt.executeUpdate();


            System.out.println("Data inserted successful

ly!");


            // Close the prepared statement and connection

            pstmt.close();

            conn.close();

        } catch (SQLException e) {

            System.out.println("Error: " + e.getMessage());

        }

    }

}


Featured posts

Ethiopian culture calendar language

Ethiopian culture, calendar, language  The Ethiopian language, specifically Amharic, uses a script called Ge'ez script. It consists of 3...

Popular posts