Friday, March 21, 2025

How to maintain a positive and happy environment

 The Bhagavad Gita, an ancient Indian scripture, offers valuable insights on how to maintain a positive and happy environment. Here are some tips inspired by the Bhagavad Gita:


1. *Cultivate detachment (Vairagya)*: The Gita teaches us to remain detached from worldly possessions and desires. This detachment helps us stay calm and composed, even in challenging situations, contributing to a more peaceful environment.


2. *Practice self-control (Atma-samyama)*: The Gita emphasizes the importance of self-control and self-awareness. By regulating our thoughts, emotions, and actions, we can create a more harmonious atmosphere.


3. *Perform duties selflessly (Nishkam Karma)*: The Gita encourages us to perform our duties without attachment to the outcomes. This selfless approach helps us stay focused on the present moment and contributes to a more positive environment.


4. *Cultivate compassion and empathy (Daya)*: The Gita teaches us to treat all living beings with kindness and compassion. By doing so, we create a more supportive and loving environment.


5. *Practice mindfulness and meditation (Dhyana)*: The Gita recommends regular mindfulness and meditation practice to cultivate inner peace and calmness. This, in turn, contributes to a more peaceful and happy environment.


6. *Let go of ego and pride (Ahamkara)*: The Gita advises us to let go of our ego and pride, which can create conflict and negativity. By doing so, we create a more humble and harmonious environment.


7. *Seek knowledge and wisdom (Jnana)*: The Gita encourages us to seek knowledge and wisdom, which helps us make informed decisions and create a more positive environment.


8. *Cultivate gratitude and contentment (Santosha)*: The Gita teaches us to cultivate gratitude and contentment, which helps us appreciate what we have and creates a more positive atmosphere.


9. *Practice forgiveness and letting go (Kshama)*: The Gita advises us to practice forgiveness and letting go of past hurts and resentments. This helps create a more peaceful and harmonious environment.


10. *Connect with the divine (Bhakti)*: The Gita encourages us to connect with the divine and cultivate a sense of devotion and love. This helps us create a more positive and loving environment.


By incorporating these principles from the Bhagavad Gita into our daily lives, we can create a more positive, happy, and harmonious environment.



Here are some more insights and practical tips on how to apply the principles of the Bhagavad Gita to create a happy and harmonious environment:


*1. Cultivate a positive mindset (Chitta Shuddhi)*:


- Practice gratitude by focusing on the good things in your life.

- Reframe negative thoughts and focus on solutions rather than problems.

- Cultivate a sense of wonder and curiosity to stay positive and engaged.


*2. Let go of attachment and aversion (Vairagya)*:


- Practice detachment from outcomes and focus on the process.

- Let go of attachment to material possessions and focus on what truly brings you joy.

- Cultivate a sense of acceptance and equanimity in the face of challenges.


*3. Cultivate self-awareness and self-acceptance (Atma-Sakshatkara)*:


- Practice self-reflection and journaling to gain insights into your thoughts and emotions.

- Cultivate self-acceptance and self-compassion by treating yourself with kindness and understanding.

- Focus on your strengths and positive qualities rather than your weaknesses.


*4. Practice mindfulness and meditation (Dhyana)*:


- Start with short periods of meditation and gradually increase the duration.

- Focus on your breath or a mantra to calm your mind and cultivate inner peace.

- Practice mindfulness by being present in the moment and focusing on your thoughts and emotions.


*5. Cultivate compassion and empathy (Daya)*:


- Practice active listening and try to understand others' perspectives.

- Cultivate compassion by putting yourself in others' shoes and trying to understand their struggles.

- Focus on building positive relationships and cultivating a sense of community.


*6. Let go of ego and pride (Ahamkara)*:


- Practice humility by recognizing your limitations and weaknesses.

- Cultivate a sense of gratitude and appreciation for others' contributions.

- Focus on building others up rather than trying to elevate yourself.


*7. Cultivate forgiveness and letting go (Kshama)*:


- Practice forgiveness by letting go of grudges and negative emotions.

- Cultivate a sense of understanding and compassion for those who have wronged you.

- Focus on moving forward and creating a positive future rather than dwelling on past hurts.


By applying these principles, you can create a more positive, happy, and harmonious environment that supports your well-being and the well-being of those around you.

Program for a basic outline of how you can create a video sharing platform using Python and the Flask web framework:

 Write a program to make a platform to upload watch and share video and write comments



Here's a basic outline of how you can create a video sharing platform using Python and the Flask web framework:


```

from flask import Flask, render_template, request, redirect, url_for

from flask_sqlalchemy import SQLAlchemy

from werkzeug.utils import secure_filename

import os


app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///video.db"

db = SQLAlchemy(app)


class Video(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    title = db.Column(db.String(100), nullable=False)

    description = db.Column(db.Text, nullable=False)

    filename = db.Column(db.String(100), nullable=False)

    comments = db.relationship("Comment", backref="video", lazy=True)


class Comment(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    content = db.Column(db.Text, nullable=False)

    video_id = db.Column(db.Integer, db.ForeignKey("video.id"), nullable=False)


@app.route("/")

def index():

    videos = Video.query.all()

    return render_template("index.html", videos=videos)


@app.route("/upload", methods=["GET", "POST"])

def upload():

    if request.method == "POST":

        title = request.form["title"]

        description = request.form["description"]

        file = request.files["file"]

        filename = secure_filename(file.filename)

        file.save(os.path.join("static/videos", filename))

        video = Video(title=title, description=description, filename=filename)

        db.session.add(video)

        db.session.commit()

        return redirect(url_for("index"))

    return render_template("upload.html")


@app.route("/video/<int:video_id>")

def video(video_id):

    video = Video.query.get_or_404(video_id)

    comments = video.comments

    return render_template("video.html", video=video, comments=comments)


@app.route("/comment/<int:video_id>", methods=["POST"])

def comment(video_id):

    video = Video.query.get_or_404(video_id)

    content = request.form["content"]

    comment = Comment(content=content, video=video)

    db.session.add(comment)

    db.session.commit()

    return redirect(url_for("video", video_id=video_id))


if __name__ == "__main__":

    app.run(debug=True)

```


This code creates a basic video sharing platform with the following features:


- Users can upload videos with a title, description, and file.

- Videos are displayed on the homepage with their title, description, and a link to watch the video.

- Users can watch videos and leave comments.

- Comments are displayed below the video.


To run this code, you'll need to:


1. Install Flask and Flask-SQLAlchemy using pip: `pip install flask flask-sqlalchemy`

2. Create a new file called `app.py` and paste the code into it.

3. Create a new directory called `templates` and create the following HTML files inside it: `index.html`, `upload.html`, and `video.html`.

4. Create a new directory called `static` and create a new directory called `videos` inside it. This is where the uploaded videos will be stored.

5. Run the code using `python app.py` and open your web browser to `http://localhost:5000`.


Here's an example of what the HTML files might look like:


`index.html`:


```

<!DOCTYPE html>

<html>

<head>

    <title>Video Sharing Platform</title>

</head>

<body>

    <h1>Video Sharing Platform</h1>

    <ul>

    {% for video in videos %}

        <li>

            <a href="{{ url_for('video', video_id=video.id) }}">{{ video.title }}</a>

        </li>

    {% endfor %}

    </ul>

    <p><a href="{{ url_for('upload') }}">Upload a new video</a></p>

</body>

</html>

```


`upload.html`:


```

<!DOCTYPE html>

<html>

<head>

    <title>Upload a new video</title>

</head>

<body>

    <h1>Upload a new video</h1>

    <form action="" method="post" enctype="multipart/form-data">

        <label for="title">Title:</label>

        <input type="text" id="title" name="title"><br><br>

        <label for="description">Description:</label>

        <textarea id="description" name="description"></textarea><br><br>

        <label for="file">File:</label>

        <input type="file" id="file" name="file"><br><br>

        <input type="submit" value="Upload">

    </form>

</body>

</html>

```


`video.html`:


```

<!DOCTYPE html>

<html>

<head>

    <title>{{ video.title }}</title>

</head>

<body

```


Here is the rest of the `video.html` template:


```

<!DOCTYPE html>

<html>

<head>

    <title>{{ video.title }}</title>

</head>

<body>

    <h1>{{ video.title }}</h1>

    <p>{{ video.description }}</p>

    <video width="320" height="240" controls>

        <source src="{{ url_for('static', filename='videos/' + video.filename) }}" type="video/mp4">

        Your browser does not support the video tag.

    </video>

    <h2>Comments:</h2>

    <ul>

    {% for comment in comments %}

        <li>{{ comment.content }}</li>

    {% endfor %}

    </ul>

    <form action="" method="post">

        <label for="content">Leave a comment:</label>

        <textarea id="content" name="content"></textarea>

        <input type="submit" value="Comment">

    </form>

</body>

</html>

```


This template displays the video title, description, and the video itself. It also displays a list of comments and a form to leave a new comment.


To run this code, you'll need to create a new directory called `templates` and add the `index.html`, `upload.html`, and `video.html` files to it.


You'll also need to create a new directory called `static` and add a new directory called `videos` to it. This is where the uploaded videos will be stored.


Finally, you can run the code using `python app.py` and open your web browser to `http://localhost:5000`.


Note: This is a very basic example and you should consider adding more features such as user authentication, video processing, and security measures to prevent unauthorized access.




Here is the rest of the code:


```

if __name__ == "__main__":

    app.run(debug=True)

```


This code starts the Flask development server, which will automatically reload the application if any changes are made to the code.


To run this code, save it to a file called `app.py` and run it using `python app.py`. Then, open your web browser and navigate to `http://localhost:5000`.


You should see a webpage with a form to upload a new video. Fill out the form and submit it to upload a new video.


Once you've uploaded a video, you can view it by clicking on the link to the video. You can also leave comments on the video by filling out the comment form.


Note: This is a very basic example and you should consider adding more features such as user authentication, video processing, and security measures to prevent unauthorized access.


Also, this code uses a very simple database model and you may want to consider using a more robust database model and ORM (Object Relational Mapping) tool.


You can also use a more robust framework such as Django which has built-in support for user authentication, video processing and security measures.


Please let me know if you have any questions or need further clarification.

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());

        }

    }

}

```

SQL query to create a table to store student information:

 Here is a SQL query to create a table to store student information:


```

CREATE TABLE Students (

    StudentID INT PRIMARY KEY,

    FirstName VARCHAR(50) NOT NULL,

    LastName VARCHAR(50) NOT NULL,

    DateOfBirth DATE,

    Email VARCHAR(100) UNIQUE,

    Phone VARCHAR(20),

    Address VARCHAR(200),

    City VARCHAR(50),

    State VARCHAR(50),

    Country VARCHAR(50),

    PostalCode VARCHAR(10),

    Course VARCHAR(50),

    Department VARCHAR(50)

);

```


Here's a brief explanation of each column:


- `StudentID`: Unique identifier for each student.

- `FirstName` and `LastName`: Student's name.

- `DateOfBirth`: Student's date of birth.

- `Email`: Student's email address (unique).

- `Phone`: Student's phone number.

- `Address`, `City`, `State`, `Country`, and `PostalCode`: Student's address.

- `Course` and `Department`: Student's course and department.


To insert data into the table:


```

INSERT INTO Students (

    StudentID,

    FirstName,

    LastName,

    DateOfBirth,

    Email,

    Phone,

    Address,

    City,

    State,

    Country,

    PostalCode,

    Course,

    Department

)

VALUES (

    1,

    'John',

    'Doe',

    '1990-01-01',

    'john.doe@example.com',

    '123-456-7890',

    '123 Main St',

    'Anytown',

    'CA',

    'USA',

    '12345',

    'Computer Science',

    'Engineering'

);

```


To retrieve data from the table:


```

SELECT * FROM Students;

```


To update data in the table:


```

UPDATE Students

SET FirstName = 'Jane'

WHERE StudentID = 1;

```


To

 delete data from the table:


```

DELETE FROM Students

WHERE StudentID = 1;

```

simple Java program using Swing for GUI and Google Translate API for translation:

 Here is a simple Java program using Swing for GUI and Google Translate API for translation:


```

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import org.json.JSONObject;


public class Translator extends JFrame {

    private JTextArea textArea;

    private JComboBox<String> languageComboBox;

    private JButton translateButton;


    public Translator() {

        setLayout(new BorderLayout());


        // Text Area

        textArea = new JTextArea(20, 40);

        add(new JScrollPane(textArea), BorderLayout.CENTER);


        // Language Combo Box

        String[] languages = {"English", "Spanish", "French", "German", "Italian", "Portuguese", "Chinese", "Japanese", "Korean"};

        languageComboBox = new JComboBox<>(languages);

        add(languageComboBox, BorderLayout.NORTH);


        // Translate Button

        translateButton = new JButton("Translate");

        translateButton.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                translateText();

            }

        });

        add(translateButton, BorderLayout.SOUTH);


        setSize(600, 400);

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setVisible(true);

    }


    private void translateText() {

        String text = textArea.getText();

        String language = (String) languageComboBox.getSelectedItem();

        String translatedText = translate(text, language);

        textArea.setText(translatedText);

    }


    private String translate(String text, String language) {

        try {

            URL url = new URL("https://translation.googleapis.com/language/translate/v2?key=YOUR_API_KEY");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");

            connection.setRequestProperty("Content-Type", "application/json");


            JSONObject json = new JSONObject();

            json.put("q", text);

            json.put("target", getLanguageCode(language));


            connection.setDoOutput(true);

            connection.getOutputStream().write(json.toString().getBytes());


            int responseCode = connection.getResponseCode();

            if (responseCode == 200) {

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String line;

                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {

                    response.append(line);

                }

                reader.close();


                JSONObject jsonResponse = new JSONObject(response.toString());

                return jsonResponse.getJSONArray("data").getJSONObject(0).getString("translations").getJSONObject(0).getString("translatedText");

            } else {

                return "Error: " + responseCode;

            }

        } catch (Exception e) {

            return "Error: " + e.getMessage();

        }

    }


    private String getLanguageCode(String language) {

        switch (language) {

            case "English":

                return "en";

            case "Spanish":

                return "es";

            case "French":

                return "fr";

            case "German":

                return "de";

            case "Italian":

                return "it";

            case "Portuguese":

                return "pt";

            case "Chinese":

                return "zh-CN";

            case "Japanese":

                return "ja";

            case "Korean":

                return "ko";

            default:

                return "en";

        }

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override

            public void run() {

                new Translator();

            }

        });

    }

}

```


Replace `YOUR_API_KEY` with your actual Google Translate API key.


Note:


- This program uses the Google Translate API, which requires a API key.

- The program translates the text in the text area to the selected language.

- The program uses the `getLanguageCode` method to get the language

 code for the selected language.

- The program uses the `translate` method to translate the text using the Google Translate API.

Saturday, March 15, 2025

Java program for a shopping mall

 Here's a simple Java program for a shopping mall:



import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;


class Product {

    String name;

    double price;


    public Product(String name, double price) {

        this.name = name;

        this.price = price;

    }

}


public class ShoppingMall {

    static Map<String, Product> products = new HashMap<>();

    static Map<String, Integer> cart = new HashMap<>();


    public static void main(String[] args) {

        addProducts();

        Scanner scanner = new Scanner(System.in);

        while (true) {

            System.out.println("1. View Products");

            System.out.println("2. Add to Cart");

            System.out.println("3. View Cart");

            System.out.println("4. Checkout");

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

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

            int choice = scanner.nextInt();

            switch (choice) {

                case 1:

                    viewProducts();

                    break;

                case 2:

                    addToCart(scanner);

                    break;

                case 3:

                    viewCart();

                    break;

                case 4:

                    checkout();

                    break;

                case 5:

                    System.exit(0);

                default:

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

            }

        }

    }


    static void addProducts() {

        products.put("P1", new Product("Shirt", 500.0));

        products.put("P2", new Product("Pants", 700.0));

        products.put("P3", new Product("Shoes", 1000.0));

        products.put("P4", new Product("Watch", 5000.0));

        products.put("P5", new Product("Sunglasses", 2000.0));

    }


    static void viewProducts() {

        System.out.println("Available Products:");

        for (Map.Entry<String, Product> entry : products.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue().name + " - " + entry.getValue().price);

        }

    }


    static void addToCart(Scanner scanner) {

        System.out.print("Enter product code: ");

        String code = scanner.next();

        if (products.containsKey(code)) {

            System.out.print("Enter quantity: ");

            int quantity = scanner.nextInt();

            if (cart.containsKey(code)) {

                cart.put(code, cart.get(code) + quantity);

            } else {

                cart.put(code, quantity);

            }

            System.out.println("Product added to cart successfully.");

        } else {

            System.out.println("Product not found.");

        }

    }


    static void viewCart() {

        System.out.println("Your Cart:");

        double total = 0;

        for (Map.Entry<String, Integer> entry : cart.entrySet()) {

            Product product = products.get(entry.getKey());

            double price = product.price * entry.getValue();

            System.out.println(entry.getKey() + ": " + product.name + " x " + entry.getValue() + " = " + price);

            total += price;

        }

        System.out.println("Total: " + total);

    }


    static void checkout() {

        System.out.println("Checkout successful. Thank you for shopping with us!");

        cart.clear();

    }

}



This program allows users to:


1. View available products

2. Add products to their cart

3. View their cart

4. Checkout and clear their cart


Note that this is a simplified example and a real-world shopping mall program would require more features, such as user authentication, payment processing, and inventory management.

Program to develop for cost saving in hotel industry

 To develop a program for cost-saving in a hotel, you can consider the following features: Key Features 1. *Room Management*: Optimize room ...