--- PDF page 448 ---
       NIGHT BEFORE · EXAM MORNING




       ∞
       The Command & Code Sheet
       Every command and code skeleton the papers have asked for, on a few pages. If a ques‐
       tion says "commands only", "write the code" or has blanks to fill, the answer pattern is
       here.

          Git      Django & DRF       SQL & MongoDB             JavaScript         React       Docker & Compose




    S.1 Git & GitHub commands
📚 Sources: Unit 1 Notes §8    LEC 3 (Git · Frameworks · JS)     Lab 3 Manual      One-Shot Revision


 Command                                                      What it does

  git init                                                    Start a repository in the current folder (creates .git )

  git config --global user.name "Asha"                        Set your name (and user.email ) once per machine

  git status · git diff                                       What changed / the exact line changes not yet staged

  git add file.py · git add .                                 Stage changes (working tree → staging area)

  git commit -m "Add login form"                              Save a snapshot (staging area → repository)

  git log --oneline --graph --all                             Compact history with branch graph

  git branch feature-x · git switch fea‐                      Create a branch / move onto it ( git switch -c feature-x or
 ture-x                                                        git checkout -b feature-x does both)

  git merge feature-x                                         Bring feature-x into the current branch (run from main)

  git rebase main                                             Replay the current branch's commits on top of main (linear history)

  git cherry-pick a1b2c3d                                     Copy one specific commit onto the current branch (e.g. a hotfix)

  git tag -a v1.0 -m "First release" · git                    Create an annotated release tag / publish it ( git push --tags for all)
 push origin v1.0

  git restore file.py · git restore --                        Discard working changes / unstage
 staged file.py

  git reset --soft HEAD~1 · git revert                        Undo last commit locally (keep changes) / safely undo a pushed commit
 a1b2c3d                                                      with a new commit

  git remote add origin                                       Set the remote named origin (2025-26 Q1e)
 https://github.com/user/repo.git




IMAP · The Exam Bible                                          448 / 459                              Intro to Modern Application Development

--- PDF page 449 ---
 Command                                                What it does

  git clone                                              Copy a remote repository to your machine (2025-26 Q1e)
 https://github.com/user/repo.git

  git push -u origin main · git pull · git              Upload and set upstream / download + merge / download only
 fetch

  git remote -v                                         List remotes and their URLs



  🔑 FOUR PLACES A CHANGE LIVES
  Working directory → (add) → staging area → (commit) → local repository → (push) → remote
  (GitHub). Merge conflict fix: open the file, keep the right lines between <<<<<<<               =======      >>>>>>> ,
  delete the markers, then git add and git commit .




    S.2 Django & DRF commands and skeletons
📚 Sources: Unit 2 Notes   LEC 5 (Django code-along)   Lecture 5 Commands Reference     One-Shot Revision


 Command                                                     Purpose

  python -m venv venv · source venv/bin/acti‐                Create / activate a virtual environment
 vate (Windows: venv\Scripts\activate )

  pip install django djangorestframework                     Install Django and DRF

  django-admin startproject myproject                        New project (settings, urls, wsgi, asgi, manage.py)

  python manage.py startapp myapp                            New app; then add 'myapp' to INSTALLED_APPS

  python manage.py makemigrations · python                   Model changes → migration files → tables in the DB
 manage.py migrate

  python manage.py createsuperuser                           Admin login; admin lives at /admin/

  python manage.py runserver                                 Dev server at http://127.0.0.1:8000/

  python manage.py shell                                     Python shell with Django loaded (ORM practice)

  python manage.py sqlmigrate myapp 0001                     Show the SQL a migration will run




IMAP · The Exam Bible                                     449 / 459                          Intro to Modern Application Development

--- PDF page 450 ---
              myapp/models.py                                           myapp/views.py


     from django.db import models                              from django.shortcuts import render, re‐
                                                               direct, get_object_or_404
     class Employee(models.Model):                             from django.http import HttpResponse,
          name =                                               JsonResponse
     models.CharField(max_length=100)                          from .models import Employee
          salary = models.DecimalField(max_dig‐
     its=10, decimal_places=2)                                 def hello(request):
          email = models.EmailField(unique=True)                   return HttpResponse("Hello")
          joined =                                             # raw text/HTML
     models.DateField(auto_now_add=True)
                                                               def api_list(request):
          def __str__(self):                                       data =
                return self.name                               list(Employee.objects.values("id",
                                                               "name"))

              myapp/admin.py                                       return JsonResponse({"employees":
                                                               data})     # JSON
     from django.contrib import admin
     from .models import Employee                              def emp_list(request):
                                                                   emps = Employee.objects.order_by("-
     admin.site.register(Employee)                             salary")
                                                                   return render(request,
                                                               "emp_list.html", {"emps": emps})




IMAP · The Exam Bible                              450 / 459                       Intro to Modern Application Development

--- PDF page 451 ---
              myapp/urls.py                                             templates/emp_list.html


     from django.urls import path                              {% extends "base.html" %}
     from . import views                                       {% block content %}
                                                                 <h1>Employees</h1>
     urlpatterns = [                                             <ul>
          path("", views.emp_list, name="em‐                     {% for e in emps %}
     p_list"),                                                     <li>{{ e.name }} — {{ e.salary }}</li>
          path("hello/", views.hello, name="hel‐                 {% empty %}
     lo"),                                                         <li>No employees yet</li>
          path("api/", views.api_list,                           {% endfor %}
     name="api_list"),                                           </ul>
     ]                                                           <form method="post">{% csrf_token %} …
                                                               </form>

              myproject/urls.py                                {% endblock %}


     from django.contrib import admin
     from django.urls import path, include


     urlpatterns = [
          path("admin/", admin.site.urls),
          path("", include("myapp.urls")),
     ]




ORM IN THE SHELL (PYTHON MANAGE.PY SHELL)

           Django shell


  from myapp.models import Employee
  from django.db.models import Avg, Sum, Max, Min, Count


  Employee.objects.create(name="Asha", salary=50000, email="asha@x.com")             # INSERT
  Employee.objects.all()                                          # SELECT *
  Employee.objects.order_by("salary")                             # ascending; "-salary" = descending
  Employee.objects.filter(salary__range=(30000, 60000))           # BETWEEN (also __gte, __lte, __gt,
  __lt)
  Employee.objects.first(); Employee.objects.last()               # first / last row (by pk unless or‐
  dered)
  Employee.objects.count()                                        # COUNT(*)
  Employee.objects.aggregate(Avg("salary"), Max("salary")) # {'salary__avg': ..., 'salary__max':
  ...}
  Employee.objects.values("name", "salary")                       # selected fields as dicts
  Employee.objects.values_list("name", flat=True)                 # just the names




IMAP · The Exam Bible                              451 / 459                       Intro to Modern Application Development

--- PDF page 452 ---
  e = Employee.objects.get(id=3); e.salary = 70000; e.save()                      # UPDATE
  Employee.objects.filter(id=5).delete()                                  # DELETE



DRF IN FOUR FILES


              serializers.py                                                     myapp/urls.py


     from rest_framework import serializers                            from django.urls import path, include
     from .models import Employee                                      from rest_framework.routers import
                                                                       DefaultRouter
     class EmployeeSerializer(serializers.Mod‐                         from . import views
     elSerializer):
          class Meta:                                                  router = DefaultRouter()
                model = Employee                                       router.register("employees", views.Employ‐
                fields = "__all__"                                     eeViewSet)



              views.py                                                 urlpatterns = [path("",
                                                                       include(router.urls))]
     from rest_framework import viewsets
     from .models import Employee
                                                                       Request                                 Action
     from .serializers import
                                                                       GET /api/employees/                     List (Read all)
     EmployeeSerializer
                                                                       POST /api/employees/                    Create (JSON
     class EmployeeViewSet(viewsets.ModelView‐                                                                 body)

     Set):                                                             GET /api/employees/3/                   Read one
          queryset = Employee.objects.all()
                                                                       PUT/PATCH                               Update
          serializer_class = EmployeeSerializer                        /api/employees/3/

                                                                       DELETE /api/employees/3/                Delete


                                                                  Remember 'rest_framework' in INSTALLED_APPS
                                                                  and path("api/", include("myapp.urls")) in the
                                                                  project urls.




    S.3 SQL & MongoDB templates
📚 Sources: Unit 3 Notes §3–6   LEC 8 (Databases & Deployment)   One-Shot Revision     Complete Revision deck




IMAP · The Exam Bible                                      452 / 459                         Intro to Modern Application Development

--- PDF page 453 ---
                 the 5-step CRUD question                                  queries that get asked


     CREATE TABLE Contact (                                        -- top 5 with marks > 75, highest first
          ID             INT PRIMARY KEY,                          SELECT name, marks FROM students
          firstName VARCHAR(50) NOT NULL,                          WHERE marks > 75
          LastName       VARCHAR(50),                              ORDER BY marks DESC
          Email          VARCHAR(100) UNIQUE,                      LIMIT 5;
          Salary         DECIMAL(10,2) CHECK (Salary
     >= 0)                                                         -- average of those above 75
     );                                                            SELECT AVG(marks) AS avg_marks
     INSERT INTO Contact VALUES                                    FROM students WHERE marks > 75;
      (1,'Asha','Rao','asha@x.com',45000),
      (2,'Vikram','Shah','vik@x.com',52000),                       -- group + filter groups
      (3,'Neha','Iyer','neha@x.com',39000),                        SELECT dept_id, COUNT(*) AS n, AVG(marks)
      (4,'Rohan','Das','rohan@x.com',61000),                       FROM students GROUP BY dept_id
      (5,'Sara','Khan','sara@x.com',48000);                        HAVING COUNT(*) > 3;
     ALTER TABLE Contact ADD Address
     VARCHAR(200);                                                 -- join
     UPDATE Contact SET Salary = 60000, Address                    SELECT s.name, d.name AS dept
     = 'Pune'                                                      FROM students s
      WHERE ID = 3;                                                INNER JOIN departments d ON s.dept_id =
     DELETE FROM Contact WHERE ID = 5;                             d.id;
     SELECT * FROM Contact;




  🔑 EXECUTION ORDER
  Written: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. Executed:
  FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That is why a
  SELECT alias works in ORDER BY but not in WHERE. Command groups: DDL
  CREATE/ALTER/DROP/TRUNCATE · DML INSERT/UPDATE/DELETE · DQL SELECT · DCL
  GRANT/REVOKE · TCL COMMIT/ROLLBACK/SAVEPOINT.


               mongosh


  use college
  db.students.insertOne({ name: "Asha", marks: 82, skills: ["python", "sql"] })
  db.students.insertMany([{ name: "Ravi", marks: 71 }, { name: "Meera", marks: 90 }])
  db.students.find({ marks: { $gt: 75 } }).sort({ marks: -1 }).limit(5)
  db.students.updateOne({ name: "Ravi" }, { $set: { marks: 78 } })
  db.students.deleteOne({ name: "Meera" })
  db.students.aggregate([{ $match: { marks: { $gt: 75 } } }, { $group: { _id: null, avg: { $avg:
  "$marks" } } }])




IMAP · The Exam Bible                                  453 / 459                      Intro to Modern Application Development

--- PDF page 454 ---
    S.4 JavaScript patterns
📚 Sources: Unit 1 Notes §7   LEC 3 (Git · Frameworks · JS)   Lab 3 Manual




               callback → promise → async/await                                    test.js — form validation skeleton


     // promise-returning step                                           document.getElementById("empForm")
     function step(msg, ms) {                                                .addEventListener("submit", function (e)
         return new Promise((resolve) => {                               {
          setTimeout(() => { console.log(msg);                                let ok = true;
     resolve(); }, ms);                                                       const name = document.getElement‐
         });                                                             ById("name").value.trim();
     }                                                                        const salary = document.getElement‐
     // .then chain                                                      ById("salary").value;
     step("Order placed", 2000)                                               const email = document.getElement‐
         .then(() => step("Payment done", 4000))                         ById("email").value.trim();
         .then(() => console.log("Delivered"))
         .catch(err => console.error(err));                                   if (!/^[A-Za-z ]{2,}$/.test(name)) {
     // async/await                                                      show("nameErr", "Letters only"); ok =
     async function run() {                                              false; }
         try {                                                                else show("nameErr", "");
          await step("Order placed", 2000);                                   if (salary === "" || isNaN(salary) ||
          await step("Payment done", 4000);                              Number(salary) <= 0) { show("salErr",
          console.log("Delivered");                                      "Positive number"); ok = false; }
         } catch (err) { console.error(err); }                                else show("salErr", "");
     }                                                                        if (!/^[^\s@]+@[^\s@]+\.
     run();                                                              [^\s@]+$/.test(email)) { show("emailErr",
     // parallel instead of sequential (inside                           "Invalid email"); ok = false; }
     an async function)                                                       else show("emailErr", "");
     const [a, b] = await
     Promise.all([fetchA(), fetchB()]);                                       if (!ok) e.preventDefault();                 //
                                                                         stop submission
                                                                             });


                                                                         function show(id, msg) { document.getEle‐
                                                                         mentById(id).textContent = msg; }




 Function type                 One-line example

 Declaration (hoisted)          function add(a, b) { return a + b; }

 Expression / anonymous         const add = function (a, b) { return a + b; };

 Arrow                          const add = (a, b) => a + b;

 IIFE                           (function () { console.log("runs once"); })();




IMAP · The Exam Bible                                        454 / 459                        Intro to Modern Application Development

--- PDF page 455 ---
 Function type                One-line example

 Callback                      setTimeout(() => console.log("later"), 1000);

 Higher-order                  [1, 2, 3].map(n => n * 2);

 Constructor                   function Car(m) { this.model = m; } const c = new Car("i20");

 Async                         async function load() { const r = await fetch(url); }

 Generator                     function* ids() { yield 1; yield 2; }




    S.5 React skeletons
📚 Sources: Unit 4 Notes   LEC 9 (React)   ShopLite React Manual




IMAP · The Exam Bible                                     455 / 459        Intro to Modern Application Development

--- PDF page 456 ---
              terminal                                                       fetch with loading / error


     npm create vite@latest my-app -- --tem‐                       const [items, setItems] = useState([]);
     plate react                                                   const [loading, setLoading] = useS‐
     cd my-app                                                     tate(true);
     npm install                                                   const [error, setError] = useState(null);
     npm run dev             # http://localhost:5173
                                                                   useEffect(() => {
                                                                       let ignore = false;
              Counter.jsx — state + effect
                                                                       fetch(`/api/products/?q=${query}`)
     import { useState, useEffect } from                                   .then(r => { if (!r.ok) throw new
     "react";                                                      Error(r.status); return r.json(); })
                                                                           .then(data => { if (!ignore) set‐
     export default function Counter({ start =                     Items(data); })
     0 }) {       // props                                                 .catch(err => { if (!ignore) setEr‐
         const [count, setCount] = useS‐                           ror(err.message); })
     tate(start);             // state                                     .finally(() => { if (!ignore) setLoad‐
                                                                   ing(false); });
         useEffect(() => {                                             return () => { ignore = true; };                //
     // runs after render                                          ignore stale responses
          document.title = `Count: ${count}`;                      }, [query]);                                       //
          return () => { /* cleanup on                             query IS a dependency
     unmount/re-run */ };
         }, [count]);
                                                                             Context + reducer
     // only when count changes
                                                                   const CartContext = createContext(null);
         return (
          <div>                                                    function reducer(state, action) {
              <h2>{count}</h2>                                         switch (action.type) {
              <button onClick={() => setCount(c =>                         case "add": return [...state, ac‐
     c + 1)}>+</button>                                            tion.item];
              <button onClick={() => setCount(c =>                         case "remove": return state.filter(i
     c - 1)}>-</button>                                            => i.id !== action.id);
              <button onClick={() =>                                       default: return state;
     setCount(start)}>Reset</button>                                   }
          </div>                                                   }
         );                                                        export function CartProvider({ children })
     }                                                             {
                                                                       const [cart, dispatch] = useReducer(re‐
                                                                   ducer, []);
                                                                       return (
                                                                           <CartContext.Provider value={{ cart,
                                                                   dispatch }}>
                                                                            {children}
                                                                           </CartContext.Provider>



IMAP · The Exam Bible                                  456 / 459                         Intro to Modern Application Development

--- PDF page 457 ---
                                                                          );
                                                                      }
                                                                      // consumer: const { cart, dispatch } =
                                                                      useContext(CartContext);




  🔑 USEEFFECT IN ONE TABLE
     useEffect(fn)                                  after every render

     useEffect(fn, [])                              once, after the first render (mount)

     useEffect(fn, [a, b])                          after first render and whenever a or b changes

     return () => {…} inside fn                     cleanup: before the next run and on unmount




    S.6 Docker & Compose
📚 Sources: Unit 5 Notes   LEC 6 (Docker)   Docker Lab    Docker Cheatsheet


 Image commands                                                 Container commands

  docker build -t app:1.0 . build from Dockerfile                docker run -d -p 8000:8000 --name web
                                                                app:1.0 create + start (detached, host:container port)

  docker images list images                                      docker ps running · docker ps -a all

  docker pull python:3.12-slim download from a                   docker stop web · docker start web · docker
 registry                                                       restart web

  docker tag app:1.0 user/app:1.0 name it for                    docker logs -f web follow the logs
 Docker Hub

  docker push user/app:1.0 upload to a registry                  docker exec -it web sh shell inside a running container

  docker rmi app:1.0 remove an image                             docker rm web · docker rm -f web remove (force if
                                                                running)

  docker image prune remove dangling images                      docker inspect web full JSON details · docker
                                                                stats live usage

  docker history app:1.0 show the layers                         docker volume create pgdata · docker network
                                                                create appnet




IMAP · The Exam Bible                                    457 / 459                         Intro to Modern Application Development

--- PDF page 458 ---
              Dockerfile (Django)                                             compose.yaml


     FROM python:3.12-slim                                           services:
     ENV PYTHONDONTWRITEBYTECODE=1                                     db:
     PYTHONUNBUFFERED=1                                                  image: postgres:16
     WORKDIR /app                                                        environment:
     COPY requirements.txt .                                                 POSTGRES_DB: app
     RUN pip install --no-cache-dir -r require‐                              POSTGRES_USER: app
     ments.txt                                                               POSTGRES_PASSWORD: secret
     COPY . .                                                            volumes:
     EXPOSE 8000                                                             - pgdata:/var/lib/postgresql/data
     CMD ["gunicorn", "myproject.wsgi:applica‐                         web:
     tion", "--bind", "0.0.0.0:8000"]                                    build: .
                                                                         ports:
                                                                             - "8000:8000"
    Compose command                  Does
                                                                         environment:
     docker compose up -d --         Build and start
                                                                             DATABASE_HOST: db               # service
    build                            the stack
                                                                     name = hostname
     docker compose ps · docker      Status / logs                       depends_on:
    compose logs -f web
                                                                             - db
     docker compose exec web         Run a command                   volumes:
    python manage.py migrate         in a service                      pgdata:

     docker compose down ( -v        Stop and
    also deletes volumes)            remove




  ⚠️ TWO BUGS EXAMINERS LOVE
  localhost inside a container means the container itself, not your laptop or another container. Inside
  Compose, reach the database by its service name ( db ). And a server inside a container must listen on
    0.0.0.0 , not 127.0.0.1 , or -p port publishing cannot reach it.




    S.7 Ten answers to have ready

 If they ask…                          Lead with…

 Props vs state                        Props are read-only inputs passed from parent to child; state is data a component owns
                                       and changes with a setter, which triggers a re-render.

 Why setState isn't immediate          State is a snapshot per render; React batches updates and applies them on the next
                                       render. Use setX(prev => …) when the new value depends on the old.

 CSR vs SSR vs RSC                     CSR: browser runs JS and fetches data. SSR: server renders HTML per request, then
                                       hydrates. RSC: components run only on the server, send a serialized tree, ship zero JS
                                       for themselves.

 Aliasing vs copying                    y = x binds a second name to the same list ( [1, 2, 3, 4] printed);
                                        z.copy() makes a new list ( [5, 6, 7] printed).


IMAP · The Exam Bible                                    458 / 459                         Intro to Modern Application Development

--- PDF page 459 ---
 If they ask…                                 Lead with…

 SQL vs NoSQL                                 Tables + fixed schema + joins + ACID + vertical scaling (banking) vs documents + flexi‐
                                              ble schema + embedding + BASE + horizontal scaling (social media feeds).

 Django MVT                                   Model = data (models.py), View = logic (views.py), Template = HTML; urls.py routes a
                                              URL to a view.

 Docker vs VM                                 A VM virtualises hardware and runs a full guest OS on a hypervisor; a container shares
                                              the host kernel and isolates processes, so it is MBs, starts in seconds.

 Docker architecture                          Client (CLI) → REST API → daemon (dockerd) on the host, which builds images, runs
                                              containers, manages volumes/networks, and pulls/pushes images from a registry.

 Git merge vs rebase                          Merge keeps history and adds a merge commit; rebase rewrites your commits on top of
                                              the target for a linear history. Never rebase shared/public branches.

 Droplet                                      A DigitalOcean droplet is a Linux virtual machine (IaaS) you create by choosing image,
                                              size, region and SSH key, then reach with ssh root@<ip> .



You have prepared for every question these three papers ever asked, plus the ones they skipped. Read the paper twice, choose wisely,
                                           draw the diagram, write the code. All the best.




IMAP · The Exam Bible                                          459 / 459                          Intro to Modern Application Development
