MauryaHub PYQ Practice

Tools in Data Science · End Term · Jan 2026 · FN

Tools in Data Science · End Term · Jan 2026 FN

← Course papers · Start practice / exam

Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.

25 / 27 published solutions

Question 2 MCQ · 1.0 marks

Your frontend app on
Source diagram or notation
tries to fetch data from your backend API on
Source diagram or notation
. The browser shows a "CORS error". Why? Choose the correct answer.
6406536935373.
The backend server crashed while processing the request.
6406536935374.
The frontend is running on the wrong port.
6406536935375.
Browsers always delete data sent from port 8000.
6406536935376.
Browsers block cross-origin requests by default.

Published solution

**1. Understand what defines an Origin:** An origin consists of the **scheme (protocol)**, **hostname (domain)**, and **port** (for example, `http://localhost:3000` vs. `http://localhost:8000`). Because the frontend and backend run on different ports (or domains), the browser treats the fetch call as a **cross-origin request**. **2. Explain the CORS error:** Under the browser's Same-Origin Policy, web browsers block frontend JavaScript from reading responses from a different origin by default unless the backend server explicitly includes Cross-Origin Resource Sharing (`Access-Control-Allow-Origin`) headers. **Answer: D — Browsers block cross-origin requests by default.** A: **Incorrect:** A CORS error is enforced by the browser when `Access-Control-Allow-Origin` headers are missing, even when the backend server is healthy. B: **Incorrect:** Running frontend and backend on separate ports (e.g., `3000` and `8000`) is standard during development; it simply requires CORS configuration on the backend. C: **Incorrect:** Browsers do not arbitrarily delete data based on port `8000`. D: **Correct:** Web browsers enforce the Same-Origin Policy and block cross-origin requests by default unless the server sends permissive CORS headers.

Report a correction for Q2

Question 3 MCQ · 1.0 marks

You deploy your portfolio website to GitHub Pages. You try to add a Python FastAPI backend to handle form submissions directly on GitHub Pages. What happens when users try to submit the form? Choose the correct answer.
6406536935377.
GitHub Pages converts Python to JavaScript for browser execution.
6406536935378.
Form submissions queue until you push new commits.
6406536935379.
Submission fails—GitHub Pages serves only static files, not backend code.
6406536935380.
GitHub creates a serverless function to handle POST requests.

Published solution

**1. Understand static web hosting vs. application servers:** GitHub Pages is a **static site host**: it simply serves pre-built static files (HTML, CSS, client-side JS, images) over HTTP. It does not run a Python interpreter or an ASGI server like Uvicorn. **2. Determine what happens on form submission:** Because GitHub Pages cannot execute backend Python FastAPI code or process dynamic POST routes, the form submission fails (typically returning `405 Method Not Allowed` or `404 Not Found`). **Answer: C — Submission fails—GitHub Pages serves only static files, not backend code.** A: **Incorrect:** GitHub Pages does not transpile Python backend frameworks into browser JavaScript. B: **Incorrect:** Static file hosts do not queue HTTP POST form submissions across Git commits. C: **Correct:** GitHub Pages only serves static assets and has no backend runtime to execute Python FastAPI endpoints. D: **Incorrect:** GitHub Pages does not automatically provision serverless Python functions for FastAPI routes.

Report a correction for Q3

Question 4 MCQ · 1.0 marks

You use Python's
Source diagram or notation
library to get data from an API.
Source diagram or notation
gives you the raw string. What does
Source diagram or notation
do? Choose the correct answer.
6406536935381.
Converts the JSON string into a Python dictionary.
6406536935382.
Contacts the API again to verify data format.
6406536935383.
Deletes special characters for safety before printing.
6406536935384.
Automatically fixes formatting mistakes in the string.

Published solution

**1. Compare `response.text` and `response.json()` in Python's `requests` library:** - `response.text` returns the raw HTTP response body decoded as a Python `str`. - `response.json()` parses that JSON-formatted string (equivalent to `json.loads(response.text)`) and returns the corresponding native Python data structure (typically a `dict` or `list`). **Answer: A — Converts the JSON string into a Python dictionary.** A: **Correct:** `response.json()` deserializes the JSON-formatted response body into a Python dictionary (or list). B: **Incorrect:** `response.json()` parses the already-downloaded response body in memory without making another network request. C: **Incorrect:** It parses valid JSON syntax rather than stripping special characters for printing. D: **Incorrect:** If the response body contains invalid JSON syntax, `response.json()` raises a `JSONDecodeError` rather than fixing mistakes.

Report a correction for Q4

Question 5 MCQ · 1.0 marks

You build a Docker image locally and push it to Docker Hub. Your colleague pulls it on Windows. Your code runs Ubuntu Linux inside the container. What happens? Choose the correct answer.
6406536935385.
Docker Hub converts Linux containers to Windows during push.
6406536935386.
Container runs successfully—Docker provides Linux compatibility on Windows.
6406536935387.
Container crashes with "Platform Mismatch" error.
6406536935388.
Docker refuses to pull and shows OS incompatibility warning.

Published solution

**1. Understand how Docker runs Linux containers on Windows:** Docker Desktop on Windows uses a lightweight Linux kernel environment (via WSL 2 or a Hyper-V Linux VM) to run Linux containers natively. **2. Conclude what happens when your colleague pulls and runs the image:** Because the container bundles the Ubuntu user-space filesystem and dependencies while Docker Desktop provides the Linux kernel compatibility layer on Windows, the container runs seamlessly. **Answer: B — Container runs successfully—Docker provides Linux compatibility on Windows.** A: **Incorrect:** Docker Hub stores the image layers as pushed; it does not convert Ubuntu Linux binaries into Windows binaries. B: **Correct:** Docker on Windows runs Linux containers using a lightweight Linux VM / WSL 2 backend, so the Ubuntu container runs as expected. C: **Incorrect:** Standard x86_64 Linux containers run smoothly on Windows via Docker's Linux subsystem without crashing. D: **Incorrect:** Docker pulls and executes Linux images on Windows by default.

Report a correction for Q5

Question 6 MCQ · 1.0 marks

Why is it highly recommended to use HTTPS instead of HTTP when sending an API token over the internet? Choose the correct answer.
6406536935389.
HTTPS transfers data faster than standard HTTP.
6406536935390.
HTTPS encrypts data, making it unreadable if intercepted.
6406536935391.
HTTP is only allowed for transferring images and videos.
6406536935392.
HTTPS automatically fixes spelling errors in API requests.

Published solution

**1. Compare HTTP vs. HTTPS:** Standard HTTP transmits headers, URLs, and request bodies in **plain text** across every router, Wi-Fi access point, and proxy along the network path. Anyone intercepting the traffic can read your secret API token directly. **2. Explain the role of HTTPS (HTTP over TLS):** HTTPS encrypts the entire HTTP communication channel (including headers and request bodies) using TLS, so even if an attacker intercepts the network packets, the API token is unreadable ciphertext. **Answer: B — HTTPS encrypts data, making it unreadable if intercepted.** A: **Incorrect:** HTTPS adds TLS encryption and handshake security, not raw speed over plain HTTP. B: **Correct:** HTTPS uses TLS encryption to protect headers, tokens, and payloads from eavesdropping and tampering in transit. C: **Incorrect:** Both HTTP and HTTPS can transfer any media type (JSON, HTML, text, images, video). D: **Incorrect:** Transport-layer encryption does not alter or spell-check application payload content.

Report a correction for Q6

Question 7 MCQ · 1.0 marks

You run five network requests using
Source diagram or notation
. Four finish in 1 second, one takes 10 seconds. How long does
Source diagram or notation
take total? Choose the correct answer.
6406536935393.
1 second—stops after the fastest request finishes.
6406536935394.
5 seconds—the average time of all requests.
6406536935395.
3 seconds—stops automatically to avoid long waits.
6406536935396.
10 seconds—must wait for the slowest request to finish.

Published solution

**1. Understand concurrent execution with `asyncio.gather()`:** `asyncio.gather()` launches all five network requests **concurrently** at time \(t = 0\) and waits until **all** of the passed coroutines have completed before returning their combined results. **2. Calculate the total elapsed wall-clock time:** - Four requests finish at \(t = 1\text{ second}\). - The fifth request finishes at \(t = 10\text{ seconds}\). - Because all five run in parallel and `asyncio.gather()` waits for the last one to complete, the total time is the maximum of the individual durations: \[T_{\text{total}} = \max(1, 1, 1, 1, 10) = 10\text{ seconds}\] **Answer: D — 10 seconds—must wait for the slowest request to finish.** A: **Incorrect:** `asyncio.gather()` waits for all tasks to complete, not just the first one. B: **Incorrect:** Concurrent execution takes the maximum duration of the parallel tasks, not their arithmetic mean. C: **Incorrect:** `asyncio.gather()` does not impose an automatic 3-second timeout unless explicitly wrapped in `asyncio.wait_for()`. D: **Correct:** Since all 5 requests run concurrently, total wall-clock time equals the slowest request's duration (\(10\text{ seconds}\)).

Report a correction for Q7

Question 8 MCQ · 1.0 marks

Why is it highly important to put your secret API keys in an
Source diagram or notation
file rather than typing them directly into the Python code? Choose the correct answer.
6406536935397.
It makes the API run faster by grouping keys in one location.
6406536935398.
It prevents secret keys from being uploaded to GitHub when you share code.
6406536935399.
It allows Python to cache variables during execution.
6406536935400.
It helps GitHub verify the cloud API is installed correctly.

Published solution

**1. Understand the purpose of `.env` files:** Hardcoding secret API keys directly inside `.py` source files means that whenever you push your code to a version control platform like GitHub, your secrets are published to the repository history. **2. Explain how `.env` + `.gitignore` protects secrets:** Storing secrets in a local `.env` file (which is listed in `.gitignore` and loaded at runtime via `os.environ` / `python-dotenv`) keeps credentials out of source code so they are never accidentally uploaded to GitHub. **Answer: B — It prevents secret keys from being uploaded to GitHub when you share code.** A: **Incorrect:** Reading environment variables has no effect on remote API execution speed. B: **Correct:** Keeping API keys in an unversioned `.env` file (excluded via `.gitignore`) prevents leaking credentials when pushing code to GitHub. C: **Incorrect:** `.env` files are for configuration and secret separation, not Python variable caching. D: **Incorrect:** GitHub does not use `.env` files to verify cloud API installations.

Report a correction for Q8

Question 9 MCQ · 1.0 marks

A delivery app calculates distances between restaurants and customers using the Haversine formula. For a customer 15 km away, the app shows "8 km" instead. Investigation reveals coordinates are stored as
Source diagram or notation
but the Haversine function expects
Source diagram or notation
. Why does this swap cause incorrect distances? Choose the correct answer.
6406536935401.
Longitude exceeds 90\(^{o}\), causing sine to return negative values.
6406536935402.
Formula uses latitude in trig calculations; swapping produces incorrect angles.
6406536935403.
Haversine detects swaps and falls back to Euclidean distance.
6406536935404.
Database indexes for latitude fail when queried with longitude first.

Published solution

**1. Recall the Haversine great-circle distance formula:** Given two points with latitudes \(\phi_1, \phi_2\) and longitudes \(\lambda_1, \lambda_2\), the Haversine formula computes: \[a = \sin^2\!\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_1)\cos(\phi_2)\sin^2\!\left(\frac{\Delta \lambda}{2}\right)\] **2. Analyze why latitude and longitude are not interchangeable:** Notice that the longitude difference term \(\sin^2(\Delta \lambda / 2)\) is scaled by \(\cos(\phi_1)\cos(\phi_2)\)—the cosines of the **latitudes**—because meridians of longitude converge toward the poles. If coordinates stored as `(longitude, latitude)` are passed into a function expecting `(latitude, longitude)`, the function plugs longitudes into \(\cos(\phi_1)\cos(\phi_2)\) instead of latitudes, producing completely wrong trigonometric scaling and an incorrect distance. **Answer: B — Formula uses latitude in trig calculations; swapping produces incorrect angles.** A: **Incorrect:** Even when longitude is under \(90^\circ\), swapping latitude and longitude changes the \(\cos(\text{lat}_1)\cos(\text{lat}_2)\) scaling factor. B: **Correct:** The Haversine formula treats latitude and longitude asymmetrically (multiplying the longitude term by \(\cos(\text{lat}_1)\cos(\text{lat}_2)\)), so swapping them feeds the wrong angles into the trigonometric terms. C: **Incorrect:** The Haversine mathematical function simply evaluates numbers; it has no way to detect swapped coordinates or switch to Euclidean distance. D: **Incorrect:** The error occurs inside the mathematical distance calculation itself, not in database indexing.

Report a correction for Q9

Question 10 MCQ · 1.0 marks

You write a script that loads a 2GB file into memory. It works on your laptop but crashes with "Out of Memory" on a free serverless cloud function. Why? Choose the correct answer.
6406536935405.
The cloud server detects the large file as malicious.
6406536935406.
Free-tier cloud environments enforce strict memory limits.
6406536935407.
Python cannot download external files inside cloud servers.
6406536935408.
Files over 1GB require a separate database installation.

Published solution

**1. Compare local workstation RAM vs. serverless cloud function limits:** A personal laptop typically has \(8\text{ GB}\) to \(32\text{ GB}\) of RAM, so loading a \(2\text{ GB}\) file into memory succeeds locally. **2. Identify why the free serverless cloud function crashes:** Free-tier serverless functions (such as AWS Lambda, Google Cloud Functions, or Vercel/Render free tiers) enforce strict container memory ceilings (often \(128\text{ MB}\) to \(512\text{ MB}\)). Attempting to allocate \(2\text{ GB}\) in RAM immediately exceeds the cgroup memory limit and terminates the process with an `Out of Memory (OOM)` error. **Answer: B — Free-tier cloud environments enforce strict memory limits.** A: **Incorrect:** Cloud platforms do not treat large data files as malware by raising an Out of Memory error. B: **Correct:** Free-tier serverless containers allocate small fixed RAM quotas (often \(128\text{--}512\text{ MB}\)), so loading a \(2\text{ GB}\) file into memory exceeds the limit. C: **Incorrect:** Python in cloud functions can download external files as long as network access and storage/memory limits allow. D: **Incorrect:** Large files can be processed in chunks/streams without requiring a separate database installation.

Report a correction for Q10

Question 11 MCQ · 2.0 marks

You have a Dockerfile for your Python web application. It copies your code and runs it. But it crashes because it can't find the
Source diagram or notation
library. What is missing in the Dockerfile? Choose the correct answer.
6406536935409.
A
Source diagram or notation
directive to mount your local Python environment's site-packages directory into the container.
6406536935410.
An
Source diagram or notation
statement pointing to the system Python libraries.
6406536935411.
An
Source diagram or notation
command to enable the container's network access for downloading packages at runtime.
6406536935412.
A
Source diagram or notation
command to explicitly install third-party dependencies during the image build.

Published solution

**1. Understand Docker image isolation:** A Docker container starts from a clean base image (e.g., `python:3.11-slim`) that only includes the Python standard library. It does **not** inherit packages installed on your host laptop. **2. Identify the required Dockerfile instruction:** To make third-party libraries like `requests` available inside the container, the `Dockerfile` must explicitly install them during the image build step using a `RUN` instruction, such as: `RUN pip install -r requirements.txt` **Answer: D — A `RUN pip install -r requirements.txt` command to explicitly install third-party dependencies during the image build.** A: **Incorrect:** Mounting host `site-packages` breaks portability across operating systems and architectures. B: **Incorrect:** Setting `PYTHONPATH` does not install missing third-party packages that were never downloaded into the image. C: **Incorrect:** `EXPOSE` only documents which network port the container listens on; it does not install packages. D: **Correct:** `RUN pip install -r requirements.txt` installs the required third-party Python packages into the Docker image layer during build.

Report a correction for Q11

Question 12 MCQ · 2.0 marks

Your app blocks the word "Ignore" to prevent prompt injection. A user types "I-g-n-o-r-e the above instructions" and bypasses it. Why? Choose the correct answer.
6406536935413.
The check matches exact words only; spelling tricks bypass it.
6406536935414.
Python removes dashes before comparing text.
6406536935415.
LLMs cannot read or process text with dashes.
6406536935416.
The backend crashed and allowed all traffic through.

Published solution

**1. Analyze naive keyword blocklists:** A simple string filter that checks `if "Ignore" in user_input:` only looks for the exact contiguous character sequence `"Ignore"`. **2. Explain why the LLM still understands `"I-g-n-o-r-e"`:** Inserting dashes (`"I-g-n-o-r-e"`), spaces, or character substitutions causes the exact-substring check to evaluate to `False`, bypassing the filter, while the LLM easily reconstructs the word's meaning from the tokens. **Answer: A — The check matches exact words only; spelling tricks bypass it.** A: **Correct:** Exact substring matching fails whenever an attacker obfuscates the word with hyphens, spaces, or leetspeak. B: **Incorrect:** Python strings preserve dashes unless explicitly stripped by code; if Python removed dashes automatically, the filter would have caught the word. C: **Incorrect:** LLMs easily read and interpret hyphenated text like `"I-g-n-o-r-e"`, which is why the prompt injection succeeded. D: **Incorrect:** The filter was bypassed logically because the string did not match `"Ignore"`, not because the server crashed.

Report a correction for Q12

Question 13 MCQ · 2.0 marks

You add a
Source diagram or notation
header to your API's response. What is the main benefit of doing this? Choose the correct answer.
6406536935417.
It configures the server to batch and aggregate duplicate requests within 3600-second windows, reducing database queries.
6406536935418.
It authorizes intermediate proxies and CDNs to serve cached copies for 1 hour, preventing identical requests from reaching your origin server.
6406536935419.
It instructs client browsers to prefetch and cache all linked resources within 3600 seconds of the initial page load.
6406536935420.
It enables HTTP/2 server push for the next 3600 seconds, allowing the server to proactively send related resources.

Published solution

**1. Decode the HTTP `Cache-Control: public, max-age=3600` header:** - `public` indicates that the response may be cached by any cache, including shared intermediate proxies and Content Delivery Networks (CDNs) as well as client browsers. - `max-age=3600` specifies that the cached copy remains fresh for \(3,600\text{ seconds} = 1\text{ hour}\). **2. Identify the main architectural benefit:** Shared proxies and CDNs can serve identical requests directly from their edge cache for 1 hour without forwarding those requests to your origin server, drastically reducing server load and latency. **Answer: B — It authorizes intermediate proxies and CDNs to serve cached copies for 1 hour, preventing identical requests from reaching your origin server.** A: **Incorrect:** `Cache-Control` is an HTTP response caching directive, not a server-side database query batching setting. B: **Correct:** `public, max-age=3600` allows shared CDN/proxy caches (and browsers) to reuse the response for 1 hour (`3600` seconds) without hitting the origin server. C: **Incorrect:** `Cache-Control` applies only to the current response resource; it does not instruct browsers to prefetch all linked pages. D: **Incorrect:** `Cache-Control` does not configure HTTP/2 server push.

Report a correction for Q13

Question 14 MCQ · 2.0 marks

Your server expects an integer for age. An API sends
Source diagram or notation
(string, not number). Using Pydantic, what happens? Choose the correct answer.
6406536935421.
Server crashes—string types are incompatible.
6406536935422.
Encrypts the string so it can't be read as number.
6406536935423.
Automatically converts the string "25" to integer 25.
6406536935424.
Deletes the variable due to wrong format.

Published solution

**1. Understand Pydantic's default validation and type coercion:** When a Pydantic model field is annotated as `age: int` and receives a numeric string such as `"25"` in JSON, Pydantic's default (lax) mode automatically **coerces/converts** the valid numeric string `"25"` into the Python integer `25`. **Answer: C — Automatically converts the string "25" to integer 25.** A: **Incorrect:** Pydantic does not crash on numeric strings for `int` fields; it parses and coerces `"25"` to `25` (or raises a clean validation error if non-numeric like `"abc"`). B: **Incorrect:** Pydantic is a data validation and parsing library, not an encryption tool. C: **Correct:** By default, Pydantic coerces compatible types, converting the string `"25"` into the integer `25`. D: **Incorrect:** Pydantic never silently deletes declared fields.

Report a correction for Q14

Question 15 MCQ · 2.0 marks

When sending instructions to an LLM, developers often place core rules (like "you are a strict assistant") into a "System" prompt, while placing the user's question into a "User" prompt. Why is separating this useful? Choose the correct answer.
6406536935425.
It cuts down prompt word count to save money.
6406536935426.
Models pay closer attention to System prompts, reducing user override attempts.
6406536935427.
System prompts work offline without internet connection.
6406536935428.
It blocks users from typing words listed in System prompts.

Published solution

**1. Understand role separation in LLM chat APIs (`System` vs. `User`):** Modern instruction-tuned LLMs are trained with a privileged **instruction hierarchy** where the `system` role defines high-priority behavioral rules, constraints, and persona, while the `user` role contains untrusted end-user input. **2. Identify the benefit:** Placing core instructions in the `System` prompt and user queries in the `User` prompt helps the model distinguish trusted developer instructions from untrusted user text, making it harder for users to override core rules. **Answer: B — Models pay closer attention to System prompts, reducing user override attempts.** A: **Incorrect:** Splitting the same text across `system` and `user` messages uses roughly the same number of tokens. B: **Correct:** Instruction-tuned models prioritize `System` messages over `User` messages in the instruction hierarchy, helping resist prompt overrides. C: **Incorrect:** Both `System` and `User` prompts are sent together in the same online API request to the LLM server. D: **Incorrect:** The `System` prompt does not block the user's keyboard or input box from typing specific words.

Report a correction for Q15

Question 16 MCQ · 3.0 marks

Two users attempt to sign up with the same username simultaneously. Your server checks if the username exists, then adds it if available. Without locking, what will likely occur? Choose the correct answer.
6406536935429.
Both requests check simultaneously, see it's available, and both create the user.
6406536935430.
Python pauses the server to queue incoming requests automatically.
6406536935431.
The database detects duplicates and delete both requests.
6406536935432.
The network router blocks duplicate requests before reaching the server.

Published solution

**1. Identify the concurrency bug (Check-Then-Act Race Condition):** When two signup requests for the same username arrive at the same time and there is no database `UNIQUE` constraint, transaction isolation, or lock: 1. Request A checks if `username` exists \(\to\) sees `False`. 2. Request B checks if `username` exists (before A inserts) \(\to\) also sees `False`. 3. Both Request A and Request B proceed to insert the username, creating duplicate user records. **Answer: A — Both requests check simultaneously, see it's available, and both create the user.** A: **Correct:** This is a classic Time-of-Check to Time-of-Use (TOCTOU) race condition where both concurrent requests pass the check before either writes. B: **Incorrect:** Web frameworks handle requests concurrently (via threads, processes, or async workers) and do not automatically serialize application-level database checks. C: **Incorrect:** Without a unique constraint or lock, the database has no rule telling it to reject or delete both inserts. D: **Incorrect:** Network routers forward IP packets and do not inspect or deduplicate application-level signup usernames.

Report a correction for Q16

Question 17 MCQ · 3.0 marks

A team trains a sentiment classifier achieving 94% test accuracy. They discover 200 test reviews accidentally appeared in training data. After removing duplicates and retraining, accuracy drops to 76%. What does this reveal? Choose the correct answer.
6406536935433.
Removing training data naturally reduces accuracy.
6406536935434.
The 94% was inflated by test leakage—the model memorized test examples.
6406536935435.
The duplicates contained critical patterns needed for learning.
6406536935436.
The random seed changed, causing different train-test splits.

Published solution

**1. Analyze the accuracy drop from \(94\%\) to \(76\%\):** Initially, \(200\) test reviews were accidentally included in the training set. Because the model saw those exact test examples during training, it **memorized** them, inflating the reported test accuracy to \(94\%\). **2. Define Data Leakage (Train-Test Contamination):** When duplicate examples appear in both the training and test sets, the test set no longer measures generalization to unseen data. Removing the leaked test reviews revealed the model's true generalization accuracy of \(76\%\). **Answer: B — The 94% was inflated by test leakage—the model memorized test examples.** A: **Incorrect:** Removing \(200\) leaked test duplicates did not deprive the model of legitimate training data; it removed cheating on the test set. B: **Correct:** Overlapping examples between training and test sets is train-test data leakage, which artificially inflates test accuracy via memorization. C: **Incorrect:** Test samples should never be used for training; their removal exposed the real unseen performance. D: **Incorrect:** The drop was caused by eliminating leaked test reviews from the training set, not by a random seed fluke.

Report a correction for Q17

Question 18 MCQ · 1.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
When the student opens their testing HTML file in Chrome, why does it block the connection to their backend API? Choose the correct answer.
6406536935437.
Backend lacks CORS headers for cross-origin requests.
6406536935438.
Browsers don't allow JavaScript in local HTML files.
6406536935439.
The API broke and returned a blank error page.
6406536935440.
Antivirus stopped the network connection.

Published solution

**1. Analyze the local HTML testing setup:** When the student opens a local HTML file in Chrome (`file://` or a local dev server port like `http://localhost:5500`) and JavaScript inside that page attempts to `fetch()` the backend API (e.g., `http://localhost:8000`), the browser treats the call as a **cross-origin request**. **2. Identify why Chrome blocks the connection:** Because the backend API has not configured **CORS headers** (`Access-Control-Allow-Origin`), Chrome's Same-Origin Policy blocks the frontend JavaScript from accessing the response. **Answer: A — Backend lacks CORS headers for cross-origin requests.** A: **Correct:** A local HTML file has a different origin from the backend API server, so Chrome blocks the request unless the backend sends CORS headers. B: **Incorrect:** Browsers execute JavaScript in local HTML files normally, though they restrict cross-origin network fetches via CORS. C: **Incorrect:** The passage states the API works and caches responses, and the browser itself blocked the connection. D: **Incorrect:** The browser's built-in CORS policy—not third-party antivirus software—blocks cross-origin `fetch` calls.

Report a correction for Q18

Question 19 MCQ · 1.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
The API uses
Source diagram or notation
. How long does the cache hold data? Choose the correct answer.
6406536935441.
7,200 milliseconds
6406536935442.
7,200 minutes
6406536935443.
2 hours
6406536935444.
72 days

Published solution

**1. Read the `max-age` directive in `Cache-Control: public, max-age=7200`:** In HTTP `Cache-Control` headers, the `max-age` value is always specified in **seconds**. Here: \[\text{max-age} = 7,200\text{ seconds}\] **2. Convert seconds to hours:** Since \(1\text{ hour} = 60\text{ minutes} \times 60\text{ seconds} = 3,600\text{ seconds}\): \[\text{Duration} = \frac{7,200\text{ seconds}}{3,600\text{ seconds/hour}} = 2\text{ hours}\] **Answer: C — 2 hours** A: **Incorrect:** HTTP `max-age` is measured in seconds, not milliseconds. B: **Incorrect:** `7200` is in seconds (\(120\text{ minutes}\)), not minutes. C: **Correct:** \(7,200\text{ seconds} \div 3,600\text{ seconds/hour} = 2\text{ hours}\). D: **Incorrect:** \(7,200\text{ seconds}\) is \(2\text{ hours}\), not \(72\text{ days}\).

Report a correction for Q19

Question 20 MCQ · 1.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
The API expects
Source diagram or notation
. The LLM outputs
Source diagram or notation
. What happens with
Source diagram or notation
? Choose the correct answer.
6406536935445.
Throws
Source diagram or notation
—extra text breaks JSON syntax.
6406536935446.
Drops the extra word and reads the dictionary.
6406536935447.
Ignores the response and re-queries the LLM.
6406536935448.
Converts everything into a long string list.

Published solution

**1. Analyze the LLM output vs. strict JSON syntax:** The API expects a pure JSON object like `{"score": 5}`, but the LLM prepends conversational text such as `Sure! {"score": 5}`. **2. Determine what `json.loads()` does:** Python's `json.loads()` requires the entire input string to be valid JSON from the first non-whitespace character. When it encounters `Sure!`, it immediately raises a `json.JSONDecodeError` because conversational text outside the JSON braces violates JSON syntax. **Answer: A — Throws `JSONDecodeError`—extra text breaks JSON syntax.** A: **Correct:** `json.loads()` strictly parses JSON and raises `JSONDecodeError` when extra conversational words appear before or after the JSON object. B: **Incorrect:** `json.loads()` does not strip conversational prefixes or suffixes automatically. C: **Incorrect:** `json.loads()` is a local string parser and has no connection to re-query the LLM. D: **Incorrect:** Invalid JSON syntax raises an exception rather than returning a list of strings.

Report a correction for Q20

Question 21 MCQ · 1.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
The student wants to bypass the cache to get fresh results. What technical trick forces a new request? Choose the correct answer.
6406536935449.
Add a random query parameter (like
Source diagram or notation
) to mutate the cache key.
6406536935450.
Turn off the router and reconnect to wifi.
6406536935451.
Hard-refresh the browser tab by pressing F5 once.
6406536935452.
Email the cloud provider to clear the server cache.

Published solution

**1. Understand how HTTP and API caches index responses:** Caches use the request URL (including its query string) as the **cache key**. When the exact same URL is requested again, the cache returns the stored response. **2. Explain cache busting:** Appending a unique or random query parameter (such as `?time=1234` or `?nocache=9876`) changes the URL string, creating a **new cache key** that misses the poisoned cache entry and forces a fresh request to the backend. **Answer: A — Add a random query parameter (like `?time=1234`) to mutate the cache key.** A: **Correct:** Adding a unique query string parameter (cache busting) alters the URL cache key, bypassing the cached entry. B: **Incorrect:** Reconnecting to Wi-Fi only changes local network state and has no effect on the server-side or shared API cache. C: **Incorrect:** Pressing `F5` refreshes the browser page but does not clear the backend API's application cache. D: **Incorrect:** Emailing a cloud provider is not a technical mechanism for bypassing an application cache on a request.

Report a correction for Q21

Question 22 MCQ · 2.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
What's the key difference between LLM "Structured Outputs" and Python validation for preventing malformed JSON? Choose the correct answer.
6406536935453.
Structured outputs run server-side; Python runs client-side.
6406536935454.
Structured outputs constrain token generation; Python detects errors post- generation.
6406536935455.
Structured outputs cache results for 3600s; Python rechecks each response.
6406536935456.
Structured outputs encrypt JSON; Python leaves data unencrypted.

Published solution

**1. Compare LLM Structured Outputs vs. Post-Generation Python Validation:** - **LLM Structured Outputs (Constrained Decoding):** Uses a grammar or JSON schema during token generation to mask out invalid tokens at each step, guaranteeing that the model can **only** generate tokens that form valid schema-compliant JSON. - **Python Validation (e.g., Pydantic / `json.loads`):** Runs **after** the LLM has finished generating the response string, detecting syntax or schema errors post-generation so the app can reject or retry. **Answer: B — Structured outputs constrain token generation; Python detects errors post-generation.** A: **Incorrect:** Both LLM generation and Python backend validation run on the server side. B: **Correct:** Structured outputs enforce the schema during token sampling (preventing invalid syntax from being generated), whereas Python validation checks the text after generation completes. C: **Incorrect:** Neither mechanism defines a 3,600-second cache policy. D: **Incorrect:** Structured outputs control syntax/schema compliance, not encryption.

Report a correction for Q22

Question 23 MCQ · 2.0 marks

Read the following passage carefully: A student builds a simple API that connects to a Large Language Model (LLM). To save time and expenses, the student configures a cache so that repeated questions skip the LLM entirely and return an instant answer. To stop prompt injection attacks, the developer filters the user's text for bad words before safely sending it. During a testing session, a user cleverly tricks the API using a formatting loophole, causing the LLM to output a badly formatted hallucination. Because of the cache rules, the system memorizes this bad response. When other users ask the exact same question, they also receive the incorrect hallucination directly from the cache. Meanwhile, when the student tries testing their API locally from an HTML file, the browser blocks the connection outright. Based on the above data, answer the given subquestions.
User bypasses "Ignore" filter with "IGNORE" or "Ign0re". What validation is more robust? Choose the correct answer.
6406536935457.
Convert to lowercase and use regex for character substitutions.
6406536935458.
Increase cache timeout to 7200 seconds.
6406536935459.
Add CORS policy blocking uppercase characters.
6406536935460.
Configure asyncio.gather() to skip suspicious requests.

Published solution

**1. Analyze why `"IGNORE"` and `"Ign0re"` bypassed the filter:** - `"IGNORE"` uses uppercase letters to defeat a case-sensitive check for `"Ignore"`. - `"Ign0re"` substitutes the digit `0` for the letter `o` (leetspeak) to defeat literal word matching. **2. Formulate a more robust text normalization and pattern check:** Converting the input string to **lowercase** (`.lower()`) normalizes case variations, and using **regular expressions (regex)** that account for common character substitutions (e.g., `[o0]`, `[i1]`, optional punctuation/separators) catches obfuscated variants. **Answer: A — Convert to lowercase and use regex for character substitutions.** A: **Correct:** Lowercasing normalizes case (`IGNORE` \(\to\) `ignore`) and regex patterns match leetspeak/character substitutions (`Ign0re`). B: **Incorrect:** Cache timeout settings have nothing to do with input text filtering. C: **Incorrect:** CORS headers control browser origin access and cannot filter uppercase characters in request payloads. D: **Incorrect:** `asyncio.gather()` is a concurrency primitive for awaiting coroutines, not a text-validation filter.

Report a correction for Q23

Question 24 SUBJECTIVE · 2.0 marks

FASTAPI_ENDPOINT_RELIABILITY **Scenario Context:** A student develops a simplistic sentiment analysis API using FastAPI. However, during staging, the endpoint behaves inconsistently when invalid inputs are processed, and the overall API contract remains severely unclear to downstream clients. For example, if the
Source diagram or notation
parameter is entirely missing, the API occasionally fails silently without throwing clear errors. Moreover, if the
Source diagram or notation
parameter is passed but is completely empty (e.g.
Source diagram or notation
), the system defaults to returning a "positive" sentiment. This renders the inference service highly unreliable for real-world integration architectures. **Given Application State (**
Source diagram or notation
**):**
Source diagram or notation
Please provide a comprehensive structural analysis addressing the given two core logic flaws: Based on the above data, answer the given subquestions.
**Robust Improvements :** Write the necessary Python/FastAPI technical improvements required (e.g., Type Hinting) to structurally force the endpoint to become reliable. **NOTE:** Your answer should not exceed 200 words.

A published solution is not available for this question yet.

Report a correction for Q24

Question 25 SUBJECTIVE · 2.0 marks

FASTAPI_ENDPOINT_RELIABILITY **Scenario Context:** A student develops a simplistic sentiment analysis API using FastAPI. However, during staging, the endpoint behaves inconsistently when invalid inputs are processed, and the overall API contract remains severely unclear to downstream clients. For example, if the
Source diagram or notation
parameter is entirely missing, the API occasionally fails silently without throwing clear errors. Moreover, if the
Source diagram or notation
parameter is passed but is completely empty (e.g.
Source diagram or notation
), the system defaults to returning a "positive" sentiment. This renders the inference service highly unreliable for real-world integration architectures. **Given Application State (**
Source diagram or notation
**):**
Source diagram or notation
Please provide a comprehensive structural analysis addressing the given two core logic flaws: Based on the above data, answer the given subquestions.
**RESTful Semantics :** Should an LLM/Sentiment inference endpoint ideally operate via a GET mapped method, or a POST method? Provide a rigid technical justification analyzing payload limits and REST architectures. **NOTE:** Your answer should not exceed 200 words.

A published solution is not available for this question yet.

Report a correction for Q25

Question 26 MCQ · 1.0 marks

Read the passage carefully and answer the given subquestions. StreamFlix, a video streaming platform, serves 50 million users across 200 countries. Their mobile app, web player, and smart TV apps all connect to over 80 different backend microservices—user profiles, recommendations, video encoding, billing, analytics, and more. Managing 80 different API endpoints created chaos: mobile developers hardcoded URLs that broke during server migrations, and each service implemented its own authentication logic inconsistently. The engineering team deployed an API gateway—a single entry point at
Source diagram or notation
that routes requests to appropriate backends. Now the mobile app calls one endpoint, and the gateway forwards
Source diagram or notation
to the profile service,
Source diagram or notation
to the content service, and
Source diagram or notation
to the payment service. Authentication happens once at the gateway using OAuth tokens, eliminating redundant auth code across 80 services. However, last month the gateway crashed during a traffic spike, taking down the entire platform for 12 minutes despite all backend services running fine. The incident report revealed that debugging was harder—errors could originate from the gateway's routing logic, authentication middleware, backend services, or network issues between layers. The team now implements health checks, circuit breakers, and runs multiple gateway instances for redundancy.
You need to add a new
Source diagram or notation
endpoint to the API gateway. Which component handles routing this request to the payment service?
6406536935463.
The mobile app's HTTP client library configuration
6406536935464.
The gateway's routing rules and path-matching logic
6406536935465.
The payment service's database connection pooling settings
6406536935466.
OAuth token validation middleware in each backend service

Published solution

**1. Understand how an API Gateway routes requests:** As described in the passage, clients call a single entry point (`api.streamflix.com`), and the API gateway inspects the request URL path (such as `/users/*`, `/videos/*`, `/billing/*`, or `/payments/*`) and forwards the request to the matching internal microservice. **2. Identify the responsible component:** Adding a new `/payments` endpoint requires configuring the **gateway's routing rules and path-matching logic** so that requests matching `/payments` are forwarded to the payment service. **Answer: B — The gateway's routing rules and path-matching logic** A: **Incorrect:** The mobile app only knows the single gateway URL (`api.streamflix.com`); internal microservice routing is hidden behind the gateway. B: **Correct:** The API gateway's path-matching and routing rules map incoming URL prefixes (like `/payments`) to the target backend microservice. C: **Incorrect:** Database connection pools manage how the payment service talks to its database, not how HTTP requests reach the payment service. D: **Incorrect:** The passage states that OAuth authentication happens once centrally at the gateway, and auth middleware does not perform path routing.

Report a correction for Q26

Question 27 MCQ · 1.0 marks

Read the passage carefully and answer the given subquestions. StreamFlix, a video streaming platform, serves 50 million users across 200 countries. Their mobile app, web player, and smart TV apps all connect to over 80 different backend microservices—user profiles, recommendations, video encoding, billing, analytics, and more. Managing 80 different API endpoints created chaos: mobile developers hardcoded URLs that broke during server migrations, and each service implemented its own authentication logic inconsistently. The engineering team deployed an API gateway—a single entry point at
Source diagram or notation
that routes requests to appropriate backends. Now the mobile app calls one endpoint, and the gateway forwards
Source diagram or notation
to the profile service,
Source diagram or notation
to the content service, and
Source diagram or notation
to the payment service. Authentication happens once at the gateway using OAuth tokens, eliminating redundant auth code across 80 services. However, last month the gateway crashed during a traffic spike, taking down the entire platform for 12 minutes despite all backend services running fine. The incident report revealed that debugging was harder—errors could originate from the gateway's routing logic, authentication middleware, backend services, or network issues between layers. The team now implements health checks, circuit breakers, and runs multiple gateway instances for redundancy.
During a traffic spike, your single API gateway instance crashes. What architectural change prevents complete platform outages?
6406536935467.
increase database connection pool size on each backend service
6406536935468.
Deploy multiple gateway instances with load balancing redundancy
6406536935469.
Cache all API responses permanently on client devices
6406536935470.
Remove authentication to reduce gateway processing overhead

Published solution

**1. Identify the Single Point of Failure (SPOF):** When all client traffic passes through a single API gateway instance and that instance crashes during a traffic spike, the entire platform goes down even though all 80 backend microservices are healthy. **2. Determine the high-availability architectural fix:** Deploying **multiple API gateway instances behind a load balancer** eliminates the single point of failure: if one gateway instance crashes or becomes overloaded, the load balancer routes traffic to the remaining healthy gateway instances. **Answer: B — Deploy multiple gateway instances with load balancing redundancy** A: **Incorrect:** The backend services and their databases were running fine; the outage occurred because the single gateway instance crashed. B: **Correct:** Running multiple redundant gateway instances behind a load balancer prevents a single gateway crash from taking down the platform. C: **Incorrect:** Dynamic actions like billing, authentication, and personalized recommendations cannot be cached permanently on client devices. D: **Incorrect:** Removing authentication creates a massive security vulnerability and still leaves a single gateway instance as a single point of failure.

Report a correction for Q27

Question 28 MCQ · 1.0 marks

Read the passage carefully and answer the given subquestions. StreamFlix, a video streaming platform, serves 50 million users across 200 countries. Their mobile app, web player, and smart TV apps all connect to over 80 different backend microservices—user profiles, recommendations, video encoding, billing, analytics, and more. Managing 80 different API endpoints created chaos: mobile developers hardcoded URLs that broke during server migrations, and each service implemented its own authentication logic inconsistently. The engineering team deployed an API gateway—a single entry point at
Source diagram or notation
that routes requests to appropriate backends. Now the mobile app calls one endpoint, and the gateway forwards
Source diagram or notation
to the profile service,
Source diagram or notation
to the content service, and
Source diagram or notation
to the payment service. Authentication happens once at the gateway using OAuth tokens, eliminating redundant auth code across 80 services. However, last month the gateway crashed during a traffic spike, taking down the entire platform for 12 minutes despite all backend services running fine. The incident report revealed that debugging was harder—errors could originate from the gateway's routing logic, authentication middleware, backend services, or network issues between layers. The team now implements health checks, circuit breakers, and runs multiple gateway instances for redundancy.
A request to
Source diagram or notation
returns a 500 error. Which layers should you check when debugging?
6406536935471.
Only the mobile app's HTTP request formatting code
6406536935472.
Gateway routing, authentication middleware, video service, and network connectivity
6406536935473.
Only the PostgreSQL database query performance metrics
6406536935474.
Only the CDN cache configuration for video content

Published solution

**1. Trace the path of a request through an API Gateway architecture:** When a client sends a request to `/videos/123` (or `api.streamflix.com/videos/...`) and receives an HTTP `500 Internal Server Error`, the request traverses multiple server-side layers: 1. The API gateway's routing logic, 2. The gateway's authentication middleware, 3. The internal network connection between the gateway and the backend microservice, and 4. The backend video/content service itself. **2. Conclude which layers must be checked:** As the passage notes, a `500` error could originate in any of these server-side components, so engineers must check **gateway routing, authentication middleware, the video service, and network connectivity** between layers. **Answer: B — Gateway routing, authentication middleware, video service, and network connectivity** A: **Incorrect:** Client-side request formatting errors typically return `400 Bad Request`, whereas `500` is a server-side failure across the gateway/backend stack. B: **Correct:** As stated in the incident report, errors behind an API gateway can stem from gateway routing, auth middleware, the target backend service, or inter-service network links. C: **Incorrect:** Checking only PostgreSQL metrics ignores gateway crashes, auth middleware failures, network timeouts, and application bugs in the video service. D: **Incorrect:** Checking only CDN cache settings ignores the API gateway and backend microservice layers that generate `500` errors.

Report a correction for Q28