IMAP End-Sem Practice Questions – Unit-wise

Unit 1: Front End (Web, JavaScript, HTML, CSS, Git)

Theory
1. Describe the sequence of steps a browser follows from receiving the HTML response to displaying the
page on screen. Which step calculates the size and position of each element?

2. Define a Promise in JavaScript and list its three states. Convert the following code to use async and
await: fetch(url).then(r => r.json()).then(d => console.log(d))

3. Convert function square(n) { return n * n; } into an arrow function. Give two ways in which
let/const differ from var, and name one more ES6 feature with a one-line example.

Git commands
4. Write the Git command for each situation:

    1. You have a project folder and want Git to begin tracking its history.
    2. You changed several files but want only index.html to go into the next commit.
    3. You want to commit the staged changes with the message "Fix footer links".
    4. You want to create a branch called login-page and switch to it in a single step.
    5. You are on main and want to merge in the completed work from login-page.
    6. You want to check which files have been modified and which have been staged.
    7. You want to stage all the changed files in the current folder.
    8. You want to view the commit history, showing one line per commit.
    9. You want a local copy of the repository at https://github.com/ravi/portfolio.git.
    10. You want to push your commits on the dev branch to the remote called upstream.
    11. You want to see the exact changes you have made but not yet staged.
    12. You want to create a branch called update-header without switching to it.
    13. You want to add a remote called upstream that points to https://github.com/ravi/portfolio.git.
    14. You want to fetch the latest dev branch from upstream and merge it into your current branch.
    15. You staged app.js by mistake and want to unstage it while keeping your edits.

HTML fill in the blanks
A tag written as a pair, such as <______>...</______>, is one blank filled with one tag name.

5. Fill in the blanks so the page has a proper head section, a semantic header and a form that sends its
data to the server using POST.
<head>
  <meta ______="utf-8">
  <______>Ravi's Blog</______>
  <script src="app.js" ______></script>
</head>
<body>

  <______ class="site-header"><h1>Ravi's Blog</h1></______>
  <form ______="post" action="/subscribe">
    <label ______="phone">Phone</label>
    <input type="tel" id="phone" name="phone">
  </form>
</body>
6. Fill in the blanks so the page states its language, displays well on mobile, links its stylesheet, wraps its
content in a semantic main area, gives its image alternative text and opens the link in a new tab.
<!DOCTYPE html>
<html ______="en">
<head>
  <meta name="______" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" ______="theme.css">
</head>
<body>
  <______>
    <h1>Events</h1>
    <img src="banner.jpg" ______="Annual fest banner">
    <a href="https://www.example.com/register" ______="_blank">Register now</a>
  </______>
</body>
</html>
7. Fill in the blanks so the navigation link, the table header group, the merged cell, the password field
and the dropdown option are correct.
<ul>
  <li><a ______="/contact">Contact</a></li>
</ul>
<table border="1">
  <______>
     <tr><th>Subject</th><th>Grade</th></tr>
  </______>
  <tbody>
     <tr><td ______="2">Average</td></tr>
  </tbody>
</table>
<form action="/signin" method="post">
  <input type="______" name="secret" ______>
  <select name="year">
     <______ value="fy">First Year</______>
  </select>
</form>

CSS
8. Using the markup shown, write the CSS for each requirement.
<header class="topbar">
  <div class="logo">ShopEasy</div>
  <div class="menu"><a href="#">Products</a><a href="#">Cart</a></div>
</header>
      •   Make .topbar a flex container, with .logo at the left end and .menu at the right end.
      •   Align the items inside .topbar to the vertical centre.

    •    Arrange the links in .menu in a row with a 12px gap between them.
    •    Remove the underline from all links.

9. Using the markup shown, write the CSS for each requirement.
<div class="photos">
  <div class="tile wide">A</div>
  <div class="tile">B</div>
  <div class="tile">C</div>
  <div class="tile">D</div>
</div>
    •    Turn .photos into a grid container.
    •    Create four columns of equal width.
    •    Leave a 10px gap between the rows and the columns.
    •    Make the tile with class wide stretch across two columns.

10. Write the CSS for each requirement for an element with class profile.
<div class="profile">Student profile</div>
    •    Give .profile a 2px solid #999 border with 12px rounded corners.
    •    Add 24px of space inside .profile and 10px of space outside it.
    •    Change the background of .profile to #eef6ff when the mouse pointer is over it.
    •    On screens 768px wide or narrower, make .profile take up the full width.

Unit 2: Back End (Python, Django, DRF)

Python
1. List the four pillars of object-oriented programming with a one-line explanation of each. Write a short
Python program in which a class Puppy inherits from a class Dog and calls the parent's constructor
through super().

2. Using a short Python example, show how to open a text file with a with statement, read it line by line
and have it closed safely. What happens if the file is missing, and how would you handle that?

3. Using a short Python example, describe how a TCP server and a client exchange data over sockets.
Which methods does each side call to establish and use the connection?

4. Explain the role of *args and **kwargs in a Python function.

Django theory
5. Describe Django's MVT (Model–View–Template) pattern. Follow a single request for a page that
displays orders from the database, identifying the file and the MVT component involved at every step.

6. Describe how Django's built-in authentication works. Which functions create a user, verify credentials,
log a user in and log a user out? Why is create_user() preferred over calling User() directly, and what
roles do the session and the cookie play once the user has logged in?

7. Describe what a serializer, a ViewSet and a router each do in Django REST Framework. How does
token authentication secure an API endpoint?

8. Describe the Django template language. What are {{ }} and {% %} used for? Explain how template
inheritance works with {% extends %} and {% block %}.

9. Describe how a Django project is linked to a PostgreSQL database. List the settings inside DATABASES
and explain what makemigrations and migrate each do.

10. Explain the Django ORM. Write an ORM query that retrieves every Order with a price greater than
100, sorted from cheapest to most expensive.

11. Describe the role of a serializer, a ModelSerializer, a ViewSet and a router in Django REST
Framework. Which URLs does a router generate for a ViewSet?

12. Distinguish between authentication and authorization in Django. Illustrate how @login_required and
permissions are used, and give one difference between session-based and token-based authentication.

Django fill in the blanks
Write only the missing word.

13. Fill in the blanks so the model, the views and the protected page work correctly.

Choose from: CharField, redirect, ForeignKey, filter, auto_now_add, POST, DecimalField, login_required,
render, create
class Booking(models.Model):
    guest = models.______(User, on_delete=models.CASCADE)
    room = models.______(max_length=50)
    amount = models.______(max_digits=10, decimal_places=2)
    booked_on = models.DateTimeField(______=True)

def booking_list(request):
    bookings = Booking.objects.______(confirmed=True)
    return ______(request, "bookings/list.html", {"bookings": bookings})

def booking_create(request):
    if request.method == "______":
        Booking.objects.______(room=request.POST["room"],
amount=request.POST["amount"])
        return ______("booking-list")
    return render(request, "bookings/form.html")

@______
def profile(request):
    return render(request, "profile.html")
14. Fill in the blanks so the URL configuration, the detail view, the session handling and the template
work correctly.

Choose from: include, get_object_or_404, path, course, pk, logout, get, if, extends, csrf_token
# project/urls.py
from django.urls import ______, include
urlpatterns = [
    path("catalog/", ______("catalog.urls")),
]

# catalog/urls.py
urlpatterns = [
    path("course/<int:______>/", views.course_detail, name="course-detail"),
]

# catalog/views.py
def course_detail(request, pk):
    course = ______(Course, pk=pk)
    previous = request.session.______("recent_course", None)
    request.session["recent_course"] = ______.pk
    return render(request, "catalog/detail.html", {"course": course, "previous":
previous})

def signout_view(request):
    ______(request)
    return redirect("login")


<!-- catalog/detail.html -->
{% ______ "layout.html" %}
{% block content %}
  <h1>{{ course.title }}</h1>
  {% ______ course.is_open %}
    <p>Admissions open</p>
  {% endif %}
  <form method="post">{% ______ %}<button>Enroll</button></form>
{% endblock %}
15. Fill in the blanks so the API serializer, ViewSet, router and estimation endpoint work correctly.

Choose from: DefaultRouter, ModelSerializer, Response, "__all__", api_view, ModelViewSet, urls,
BookSerializer, predict, IsAuthenticated
# serializers.py
class BookSerializer(serializers.______):
    class Meta:
        model = Book
        fields = ______

# views.py
class BookViewSet(viewsets.______):
    queryset = Book.objects.all()
    serializer_class = ______
    permission_classes = [______]

# urls.py
router = routers.______()
router.register("books", BookViewSet)
urlpatterns = [path("api/", include(router.______))]

# ml_views.py
@______(["POST"])
def price_estimate(request):
    inputs = request.data["inputs"]

     output = model.______([inputs])
     return ______({"estimate": output[0]})

Unit 3: Databases and Cloud (SQL, PostgreSQL, MongoDB, S3, Droplets)

SQL and PostgreSQL theory
1. Define a transaction. List the four ACID properties and give a one-line description of what each
ensures.

2. A bank transfer moves 500 from account 1 to account 2. Write, in order, the SQL statements that
ensure both updates either succeed together or fail together. What do SAVEPOINT and ROLLBACK TO let
you do within a transaction?

3. Distinguish between DDL, DML and DCL, with two example commands for each.

4. Define a primary key and a foreign key. Explain referential integrity, and describe how PostgreSQL
responds when you try to delete a row that is still referenced by another table.

5. Using two small tables of your own, explain how INNER JOIN differs from LEFT JOIN.

6. How does WHERE differ from HAVING? In what situations is GROUP BY used?

7. Describe how roles and privileges are used to secure a PostgreSQL database. Write the commands
that create a role named reader and grant it read access to the student table, and the command that
revokes that access.

8. Compare DELETE, TRUNCATE and DROP.

9. Describe any three PostgreSQL constraints in one line each.

SQL commands
10. The tables category(category_id, category_name) and publisher(publisher_id, publisher_name)
already exist, with category_id and publisher_id as their primary keys. Write the SQL command for each
situation.

    1. Create a table product with product_id as an auto-numbered primary key, name as text that
        cannot be empty, stock as an integer, and category_id as a foreign key to category.
    2. Add one product named Laptop with a stock of 25 in category 3.
    3. Show the name and stock of every product with a stock above 10, highest stock first.
    4. Show each product's name together with the name of its category.
    5. Show each category's category_id and the average stock of its products.
    6. Create a table magazine with magazine_id as an auto-numbered primary key, title as text that
        cannot be empty, price as a decimal number, and publisher_id as a foreign key to publisher.
    7. Add the magazine "Tech Today" at price 150.00 from publisher 4.
    8. Increase the price by 20 for every magazine that costs less than 100.
    9. Delete the magazine whose magazine_id is 12.
    10. Show each publisher's name with the number of magazines it has published.

    11. Create a table customer with cust_id as an auto-numbered primary key, name as text that
        cannot be empty, balance as a decimal number and city as text.
    12. Add a new text column phone to customer.
    13. Show all customers from Mumbai whose balance is above 20000.
    14. Show each city with the number of customers in it.
    15. Allow the role analyst to read the customer table.

NoSQL, S3 and cloud theory
11. Define a document in MongoDB. What are the MongoDB counterparts of a SQL table, row and
column, and what is the purpose of _id? List the four types of NoSQL database with an example of each.

12. Why are uploaded files stored in S3-compatible storage rather than in the database? Explain what a
presigned link is and why it is used for downloads.

13. Describe IaaS, PaaS and SaaS, giving an example of each. Which category does a DigitalOcean droplet
belong to, and why is Docker Compose used to deploy an application stack on a droplet?

14. Give any four differences between a relational database like PostgreSQL and a document database
like MongoDB. When would MongoDB be the better option?

15. Define the terms bucket and object in S3 storage. Give two advantages of using S3 instead of storing
files on the application server's local disk.

16. Outline the steps for creating a DigitalOcean droplet and running a containerised application on it.

17. Give two reasons for choosing MongoDB and two reasons for preferring PostgreSQL when building
an application.

18. Describe how an application saves a user's uploaded file to S3 while keeping it private. Which
credentials are required, and why should they never be hard-coded in the source code?

19. On a DigitalOcean droplet, what is the developer responsible for and what is the provider
responsible for? Name two settings you choose while creating a droplet.

MongoDB commands
20. Three MongoDB collections, books, items and staff, hold documents of the shapes shown. Write the
mongosh command for each situation.
// books
{ "_id": 1, "title": "Dune", "pages": 412, "genres": ["Sci-Fi", "Classic"],
"publisher": { "city": "London" } }

// items
{ "_id": 201, "name": "Headphones", "price": 2500, "tags": ["wireless", "bluetooth"],
"stock": { "warehouse": "Pune", "qty": 15 } }

// staff
{ "_id": 1, "name": "Neha", "team": "Sales", "salary": 45000, "skills": ["Excel",
"Communication"] }

    1. Insert one book titled Dune with 412 pages, the genres Sci-Fi and Classic, and the publisher city
        London.
    2. Find every book with more than 300 pages.
    3. Find every book whose publisher city is London.
    4. Change the pages of the book titled Dune to 420.
    5. Delete the document of the book titled Dune.
    6. Insert two items in one command: Charger at 800 and Speaker at 4500.
    7. Find every item whose price is 2500 or less.
    8. Find one item named Headphones.
    9. Change the warehouse of the Headphones to Chennai.
    10. Delete every item whose price is above 10000.
    11. Insert one staff document for Neha in the Sales team with salary 45000 and the skills Excel and
        Communication.
    12. Find every staff member in the Sales team.
    13. Find every staff member whose skills include Excel.
    14. Set the salary of the staff member named Neha to 50000.
    15. Delete every staff member in the Marketing team.

Unit 4: React

Theory
1. Give four differences between props and state in React. Why must state always be updated through
its setter function rather than modified directly?

2. Explain the purpose of the useState and useEffect hooks. How does the dependency array of
useEffect control when the effect runs?

3. What problem is the Context API designed to solve? Name its three parts (create, supply, consume),
and explain how combining useReducer with context gives a simple global store.

4. Define JSX and give three rules to follow when writing it.

5. Describe how a component fetches data from a backend API when it is first rendered. What purpose
do the loading and error states serve?

6. Define a controlled input. How do useState and onChange keep an input field and its state
synchronised?

7. Explain prop drilling. How does the Context API eliminate it? Describe the roles of the Provider and
the Consumer.

8. Define a reducer. Write a cart reducer that handles the "add" and "remove" actions, and explain the
role of dispatch.

9. Give two rules of hooks. Name one hook besides useState and useEffect and describe what it does.

React fill in the blanks
Write only the missing word or symbol. A tag written as a pair, such as
<Ctx.______>...</Ctx.______>, is one blank.

10. Fill in the blanks so the React code works correctly.

Choose from: useEffect, map, className, createContext, &&, useState, Provider, key, useContext,
onClick
import { useState, useEffect, createContext, useContext } from "react";

const LangCtx = ______(null);

function TaskList({ tasks }) {
  const [done, setDone] = ______(0);

    ______(() => {
      document.title = `Done: ${done}`;
    }, [done]);

    return (
       <ul ______="tasks">
         {tasks.______(t => (
           <li ______={t.id}>{t.title}</li>
         ))}
         {tasks.length === 0 ______ <p>No tasks yet</p>}
         <button ______={() => setDone(done + 1)}>Mark done</button>
       </ul>
    );
}

function App() {
  return (
     <LangCtx.______ value="en">
       <TaskList tasks={data} />
     </LangCtx.______>
  );
}

function Footer() {
  const lang = ______(LangCtx);
  return <p>Language: {lang}</p>;
}
11. Fill in the blanks so the component fetches books from the Django API and saves a new one.

Choose from: json, async, useEffect, [], stringify, useState, setLoading, key, method, onChange
import { useState, useEffect } from "react";

function Books() {
  const [books, setBooks] = ______([]);
  const [loading, setLoading] = useState(true);
  const [title, setTitle] = useState("");

    ______(() => {
      fetch("http://localhost:8000/api/books/")
        .then(res => res.______())
        .then(data => {
          setBooks(data);
          ______(false);
        });
    }, ______);

    ______ function addBook() {
      await fetch("http://localhost:8000/api/books/", {
        ______: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.______({ title }),
      });
    }

    if (loading) return <p>Please wait...</p>;

    return (
       <div>
         <input value={title} ______={e => setTitle(e.target.value)} />
         <button onClick={addBook}>Add book</button>
         <ul>
           {books.map(b => <li ______={b.id}>{b.title}</li>)}
         </ul>
       </div>
    );
}
12. Fill in the blanks so the wishlist store built with useReducer and context works correctly.

Choose from: useReducer, default, Provider, dispatch, switch, children, length, createContext, add,
useContext
import { createContext, useReducer, useContext } from "react";

function wishlistReducer(state, action) {
  ______ (action.type) {
    case "add":
      return [...state, action.item];
    case "reset":
      return [];
    ______:
      return state;
  }
}

const WishlistCtx = ______();

export function WishlistProvider({ ______ }) {
  const [wishlist, dispatch] = ______(wishlistReducer, []);
  return (
    <WishlistCtx.______ value={{ wishlist, dispatch }}>
      {children}
    </WishlistCtx.______>

    );
}

function SaveButton({ item }) {
  const { dispatch } = ______(WishlistCtx);
  return <button onClick={() => ______({ type: "______", item })}>Save</button>;
}

function WishlistCount() {
  const { wishlist } = useContext(WishlistCtx);
  return <p>Saved: {wishlist.______}</p>;
}

Unit 5: Docker and Deployment

Theory
1. Describe the role of each of these Dockerfile instructions: FROM, WORKDIR, COPY, RUN and CMD.

2. Using -p 8080:80 as an example, explain port mapping in Docker and why it is required. How can two
containers launched from the same Compose file communicate with each other?

3. Outline the Docker workflow, from writing a Dockerfile to running the application on a different
machine, naming the command used at each step.

4. Define Docker Compose. Describe the role of the services, ports, volumes and depends_on keys in a
compose.yaml file.

5. Outline how to containerise a Django project, covering the Dockerfile, requirements.txt, the
command that launches the server and the port that needs to be published.

6. Describe how a GitHub Actions workflow can automatically build and push a Docker image whenever
code is pushed to main. Identify the trigger, the job and the key steps.

7. List the three components of Docker's architecture with a one-line description of each. Give an
example of a registry, and explain how an image differs from a container.

8. Give two differences between a container and a virtual machine. What do namespaces and cgroups
each control?

9. Define a Docker volume and explain why a database uses one. How does docker compose down differ
from docker compose down -v? Where should a database password be stored so that it is not built into
the image?

10. Give three differences between a container and a virtual machine, and explain the roles of
namespaces and cgroups.

11. Define an image layer. How is an image different from a container?

12. Why is it a bad idea to write a database password into a Dockerfile? How should it be provided
instead? Name one more good security practice for containers.

13. Explain the "it works on my machine" problem and how Docker images address it. Give two further
benefits of using containers.

14. Describe bridge networking in Docker. How can a Django container connect to a PostgreSQL
container started from the same Compose file?

15. Define a Docker registry. Explain what docker pull and docker push do, and why using a version tag
like 1.0 is safer than latest in production.

Docker commands
Write the Docker command for each situation:

    1. Build an image named shop-api with the tag 2.1 from the Dockerfile in the current folder.
    2. Run httpd:alpine in the background, named site, with host port 3000 mapped to container port
        80.
    3. Open a shell (sh) inside the running container named site.
    4. Start all the services in compose.yaml in detached mode, rebuilding the images first.
    5. Tag shop-api:2.1 for the Docker Hub user ravi so that it is ready to push.
    6. List every container, including those that have stopped.
    7. Display the logs of the container named api.
    8. Stop the running container named api.
    9. Create a named volume called mysqldata.
    10. Bring down the Compose services and remove their volumes as well.
    11. Download the image mysql:8 without running it.
    12. Run mysql:8 in the background, named mysql-db, with the environment variable
        MYSQL_ROOT_PASSWORD=admin123 and the volume mysqldata mounted at /var/lib/mysql.
    13. Show all the images stored on the machine.
    14. Remove the stopped container named api.
    15. Delete the image shop-api:2.1.

