MauryaHub PYQ Practice

Application Development - 1 · End Term · May 2026 · FN

Application Development - 1 · End Term · May 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.

32 / 32 published solutions

Question 2 MSQ · 3.0 marks

Which of the following statements about Git conflict resolution are TRUE?
6406537365946.
Conflicts occur when Git automatically merges conflicting changes without user intervention
6406537365947.
The pushing of code to remote repository before pulling is rejected by git to prevent merge conflicts
6406537365948.
Merge conflicts must be resolved manually in the conflicted files
6406537365949.
After resolving conflicts, you must run
Source diagram or notation
and
Source diagram or notation
to complete the merge

Published solution

**1. Understand how Git handles merge conflicts:** - **Statement A:** False — a merge conflict occurs precisely when Git **cannot** automatically merge competing changes to the same lines of a file and must pause for human intervention. - **Statement B:** True — if the remote repository has new commits that you haven't pulled yet (a non-fast-forward state), `git push` is rejected by Git until you pull (`git pull`) and reconcile any conflicts locally first. - **Statement C:** True — when a merge conflict occurs, Git inserts conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) into the affected files, and the developer must **manually edit and resolve** those files. - **Statement D:** True — after editing the conflicted files and removing the conflict markers, you must stage the resolved files using `git add` and finalize the merge commit using `git commit`. **Answer: B, C, D — Pushing before pulling is rejected to prevent overwriting remote changes, merge conflicts must be resolved manually, and git add + git commit complete the merge.** A: **Incorrect:** Merge conflicts happen when Git *cannot* automatically reconcile competing edits to the same region of a file. B: **Correct:** Git rejects non-fast-forward pushes when the remote branch has diverged, requiring you to pull and merge locally first. C: **Correct:** Conflicted lines marked with `<<<<<<<` and `>>>>>>>` must be inspected and resolved manually by the developer. D: **Correct:** Running `git add` marks the conflicted file as resolved, and `git commit` records the final merge commit.

Report a correction for Q2

Question 3 MCQ · 3.0 marks

Consider the following Python code.
Source diagram or notation
Assume that the above code is executed using the command “pytest -v test_fixture.py”. What is the output of the tested code? (Assume tests run in the same session and global state is preserved. )
6406537365950.Source diagram or notation
6406537365951.Source diagram or notation
6406537365952.Source diagram or notation
6406537365953.Source diagram or notation

Published solution

**1. Trace the pytest execution with function-scoped fixture `update`:** We have a global variable `value = 0` and a `@pytest.fixture` function `update()` (which has the default `"function"` scope, meaning `update()` runs once before each test function that requests it): ```python value = 0 @pytest.fixture def update(): global value value = value + 1 return value ``` 1. **When `test_case1(update)` runs:** - Pytest invokes the `update` fixture first: `value` is incremented from `0` to `1`, and `1` is returned. - Inside `test_case1`, `assert value == 1` evaluates `1 == 1`, which is `True` \(\implies\) **`test_case1` PASSED**. 2. **When `test_case2(update)` runs:** - Because `update` has function scope and global state is preserved in the same session, pytest invokes `update()` again: `value` is incremented from `1` to `2`, and `2` is returned as the `update` argument. - Inside `test_case2`, `assert update == 2` evaluates `2 == 2`, which is `True` \(\implies\) **`test_case2` PASSED**. **Answer: D — test_fixture.py::test_case1 PASSED and test_fixture.py::test_case2 PASSED.** A: **Incorrect:** Both assertions (`value == 1` on the first run and `update == 2` on the second run) evaluate to `True`. B: **Incorrect:** Because `update` is a function-scoped fixture (default scope), it runs a second time for `test_case2`, incrementing `value` from `1` to `2`. C: **Incorrect:** In `test_case1`, `update()` runs before the test body and increments `value` from `0` to `1`, so `test_case1` passes. D: **Correct:** The function-scoped fixture `update()` runs before each test, incrementing the global `value` to `1` for `test_case1` and to `2` for `test_case2`, so both pass.

Report a correction for Q3

Question 4 MCQ · 3.0 marks

Consider the following HTML templates and Python Flask code.
Source diagram or notation
Assume that the Flask app is running at
Source diagram or notation
. What will be rendered for the URL request
Source diagram or notation
?
6406537365954.
Parent content Child content
6406537365955.
Parent content
6406537365956.
Child content
6406537365957.
Child content Parent content

Published solution

**1. Check which template is rendered by the `/home` route in `app.py`:** Look at the route handler in `app.py`: ```python @app.route("/home") def index(): return render_template("base.html") ``` Notice that `index()` calls `render_template("base.html")` directly, **not** `render_template("child.html")`! **2. Determine what `base.html` renders:** Inside `base.html`, the `{% block content %}` block contains: `Parent content` Because `base.html` is rendered directly (and knows nothing about `child.html` unless `child.html` is the template passed to `render_template`), the browser renders only **`Parent content`**. **Answer: B — Parent content.** A: **Incorrect:** `child.html` is never rendered by `/home`, and even if it were, `child.html` overrides `block content` without calling `{{ super() }}`. B: **Correct:** Because `/home` calls `render_template("base.html")`, Jinja2 renders `base.html` directly, outputting `Parent content`. C: **Incorrect:** `Child content` would only be rendered if `/home` called `render_template("child.html")`. D: **Incorrect:** Only `base.html` is rendered.

Report a correction for Q4

Question 5 MCQ · 3.0 marks

Consider the following HTML and CSS code targeting a specific paragraph element on a webpage.
Source diagram or notation
6406537365971.
Orange
6406537365972.
Red
6406537365973.
Green
6406537365974.
Blue

Published solution

**1. Compare the CSS specificity of the four selectors targeting ``‹p id="para1" class="text"›`Hello World`‹/p›``:** In CSS, specificity is ranked by `(Inline, IDs, Classes/Attributes, Elements)`: 1. `p { color: red; }` — Element selector: specificity `(0, 0, 0, 1)`. 2. `div p { color: green; }` — Two element selectors: specificity `(0, 0, 0, 2)`. 3. `.text { color: blue; }` — Class selector: specificity `(0, 0, 1, 0)`. 4. `#para1 { color: orange; }` — **ID selector**: specificity **`(0, 1, 0, 0)`**. **2. Conclude:** Because an **ID selector (`#para1`)** has higher specificity than class (`.text`) and element (`p`, `div p`) selectors, `#para1 { color: orange; }` wins and renders `"Hello World"` in **Orange**. **Answer: A — Orange.** A: **Correct:** The ID selector `#para1` has the highest CSS specificity `(0, 1, 0, 0)` among the four rules, so `color: orange;` is applied. B: **Incorrect:** The element selector `p` has the lowest specificity `(0, 0, 0, 1)` and is overridden. C: **Incorrect:** The descendant element selector `div p` has specificity `(0, 0, 0, 2)`, which is lower than both `.text` and `#para1`. D: **Incorrect:** The class selector `.text` has specificity `(0, 0, 1, 0)`, which is overridden by the ID selector `#para1` `(0, 1, 0, 0)`.

Report a correction for Q5

Question 6 MCQ · 3.0 marks

Consider the following Python code.
Source diagram or notation
6406537365975.
Student profile: Siya rAJ Sharma
6406537365976.
Student profile: SiyarAJSharma
6406537365977.
Student profile: SiyaRajSharma
6406537365978.
Student profile: Siya Raj Sharma

Published solution

**1. Trace the Jinja2 template filters applied to `s1`:** In `app.py`, the dictionary is `s1 = {'f_name': 'Siya', 'm_name': 'rAJ', 'l_name': 'Sharma'}` and the template string renders: - `{{ s1.f_name }}` \(\implies\) `'Siya'` - `{{ s1.m_name | title }}` (or `capitalize`): Applying the Jinja2 `title` / `capitalize` filter to `'rAJ'` capitalizes the first letter `'R'` and lowercases the remaining letters `'aj'`, producing **`'Raj'`**. - `{{ s1.l_name }}` \(\implies\) `'Sharma'` Separated by spaces after `Student profile: `, the rendered output is: `Student profile: Siya Raj Sharma` **Answer: D — Student profile: Siya Raj Sharma.** A: **Incorrect:** The Jinja2 filter converts `'rAJ'` to title case `'Raj'`, not leaving it as `'rAJ'`. B: **Incorrect:** Spaces between the template placeholders are preserved and `'rAJ'` is title-cased to `'Raj'`. C: **Incorrect:** The template includes spaces between first, middle, and last names. D: **Correct:** The template renders the three name fields separated by spaces and transforms `'rAJ'` into `'Raj'`, outputting `Student profile: Siya Raj Sharma`.

Report a correction for Q6

Question 7 MCQ · 3.0 marks

Consider the following Python Flask code.
Source diagram or notation
6406537366002.
bool(sys.argv[1])
6406537366003.
sys.argv[1] == "debug"
6406537366004.
sys.argv[1]
6406537366005.
int(sys.argv[1])

Published solution

**1. Understand how command-line arguments are stored in `sys.argv`:** When executing `python app.py debug` from the terminal: - `sys.argv[0]` is `'app.py'` - `sys.argv[1]` is the string `'debug'` (or any other argument passed by the user, such as `'production'` or `'false'`). **2. Check each candidate expression for `debug_mode`:** We want `debug_mode` to evaluate to `True` **only when `sys.argv[1]` is `"debug"`**, and `False` for any other argument: - **Option A (`bool(sys.argv[1])`):** In Python, *any* non-empty string (even `"false"` or `"production"`) is truthy (`bool("false") == True`), so this would always enable debug mode! - **Option B (`sys.argv[1] == "debug"`):** Evaluates to `True` if and only if the first argument equals `"debug"`, and `False` otherwise. (Correct!) - **Option C (`sys.argv[1]`):** Passes a raw string instead of the boolean check `== "debug"`. - **Option D (`int(sys.argv[1])`):** Raises `ValueError` when `sys.argv[1]` is `"debug"`. **Answer: B — sys.argv[1] == "debug".** A: **Incorrect:** `bool()` on any non-empty string returns `True`, so `python app.py prod` would still enable debug mode. B: **Correct:** The comparison `sys.argv[1] == "debug"` evaluates to `True` only when the argument is `"debug"` and `False` for any other argument. C: **Incorrect:** Any non-empty string in `sys.argv[1]` is truthy in Python, so passing `'off'` would still evaluate as truthy. D: **Incorrect:** Calling `int("debug")` raises a `ValueError: invalid literal for int()`.

Report a correction for Q7

Question 8 MCQ · 3.0 marks

Consider the following data model for a Music Streaming App:
Source diagram or notation
6406537366006.Source diagram or notation
6406537366007.Source diagram or notation
6406537366008.Source diagram or notation
6406537366009.Source diagram or notation

Published solution

**1. Compare `db.ForeignKey` and `db.relationship` in Flask-SQLAlchemy:** - **`db.ForeignKey('artist.id')`:** Defined inside a `db.Column(...)` on the `Song` model. It creates an actual **relational database foreign-key column constraint** at the SQL table level linking `song.artist_id` to `artist.id`. - **`db.relationship('Song', backref='artist')`:** Not an actual column in the SQL table! Instead, it is a **high-level Python ORM construct** provided by SQLAlchemy that dynamically loads related objects in Python code (allowing `artist.songs` and `song.artist`). **Answer: B — db.ForeignKey creates an actual database constraint at the database table level, whereas db.relationship is a high-level Python ORM property that makes navigating between related objects easier in code.** A: **Incorrect:** `db.ForeignKey` is used on integer ID columns here (`artist.id`), and `db.relationship` links ORM model classes, not column types. B: **Correct:** `db.ForeignKey` defines the SQL-level foreign key column constraint, while `db.relationship` provides object-oriented navigation between `Artist` and `Song` instances in Python. C: **Incorrect:** This reverses the two: `db.ForeignKey` stores the artist's integer ID, while `db.relationship` provides the list of `Song` objects. D: **Incorrect:** They serve distinct roles (SQL schema constraint vs. Python ORM navigation) and cannot be used interchangeably.

Report a correction for Q8

Question 9 MCQ · 3.0 marks

Consider the following Python Flask code.
Source diagram or notation
6406537366010.
[“IITM”, “BS”, “MAD1”]
6406537366011.
[“MAD1”]
6406537366012.
[ ]
6406537366013.
None

Published solution

**1. Understand variable scope (`local` vs. `global`) in `reset()`:** Look closely at `app.py`: ```python items = [] @app.route("/add/<name>") def add(name): items.append(name) return jsonify(items) @app.route("/reset") def reset(): items = [] return "RESET" ``` - In `add(name)`, `items.append(name)` mutates the **global list `items`** in place (no `global` keyword is needed to mutate an existing global list). - However, in `reset()`, there is **no `global items` declaration**! Therefore, assigning `items = []` inside `reset()` merely creates a **new local variable `items`** inside `reset()` that is immediately discarded when `reset()` returns, leaving the global list `items` **completely untouched**! **2. Trace the 4 requests in sequence:** 1. `/add/IITM` \(\implies\) global `items` becomes `["IITM"]`. 2. `/add/BS` \(\implies\) global `items` becomes `["IITM", "BS"]`. 3. `/reset` \(\implies\) local `items = []` does not modify global `items` (which remains `["IITM", "BS"]`). 4. `/add/MAD1` \(\implies\) appends `"MAD1"` to global `items`, returning **`["IITM", "BS", "MAD1"]`**. **Answer: A — ["IITM", "BS", "MAD1"].** A: **Correct:** Because `reset()` omits `global items`, assigning `items = []` inside `reset()` only creates a local variable and leaves the global `items` list intact, resulting in `["IITM", "BS", "MAD1"]`. B: **Incorrect:** This would only happen if `reset()` had declared `global items` or called `items.clear()`. C: **Incorrect:** The final request `/add/MAD1` appends `"MAD1"` and returns the JSON list. D: **Incorrect:** `jsonify(items)` returns a JSON array, not `None`.

Report a correction for Q9

Question 10 MCQ · 3.0 marks

Source diagram or notation
6406537366041.Source diagram or notation
6406537366042.Source diagram or notation
6406537366043.Source diagram or notation
6406537366044.Source diagram or notation

Published solution

**1. Analyze the defined HTTP methods on `ProductResource`:** In the Flask-RESTful code: ```python class ProductResource(Resource): def get(self, product_id): ... def post(self, product_id): ... api.add_resource(ProductResource, '/product/<int:product_id>') ``` The URL route `/product/101` **exists** and is registered to `ProductResource`, which implements handlers only for **`GET`** and **`POST`** (`get()` and `post()`), and does **not** define `delete()`. **2. Determine the HTTP response for `DELETE /product/101`:** When a client sends an HTTP request using a method (`DELETE`) that is not implemented for an existing valid route (`/product/101`), Flask / Flask-RESTful automatically responds with **HTTP Status Code `405 Method Not Allowed`** and the JSON message: `{"message": "The method is not allowed for the requested URL."}` **Answer: B — {"message": "The method is not allowed for the requested URL."} with HTTP Status Code 405.** A: **Incorrect:** `400 Bad Request` indicates malformed request syntax/payload, not an unsupported HTTP method. B: **Correct:** Because `/product/101` is a valid route that supports `GET` and `POST` but not `DELETE`, Flask-RESTful returns HTTP `405 Method Not Allowed` with the standard message. C: **Incorrect:** `404 Not Found` is returned only when the URL path itself does not match any registered route. D: **Incorrect:** Missing an HTTP verb handler on a resource triggers a clean `405` client error, not a `500 Internal Server Error`.

Report a correction for Q10

Question 11 MCQ · 3.0 marks

You have a DRAM module with bus width of 64 bits, clock speed of 1 GHz, and operating in DDR (double-data-rate or two values per clock cycle) mode. What is the maximum bandwidth (in Giga- bytes per second) of data transfer achievable with this module?
6406537366045.
8 GigaBytes/s
6406537366046.
16 GigaBytes/s
6406537366047.
24 GigaBytes/s
6406537366048.
None of these

Published solution

**1. Identify the given DRAM module specifications:** - Bus width \(= 64\text{ bits} = \frac{64}{8}\text{ Bytes} = 8\text{ Bytes}\) per transfer. - Clock speed \(= 1\text{ GHz} = 10^9\text{ cycles/second}\). - Mode: **DDR (Double Data Rate)** \(= 2\text{ transfers per clock cycle}\). **2. Calculate the maximum memory bandwidth:** \[\text{Bandwidth} = (\text{Bytes per transfer}) \times (\text{Transfers per clock cycle}) \times (\text{Clock frequency})\] \[\text{Bandwidth} = 8\text{ Bytes} \times 2 \times 1\text{ GHz} = 16\text{ GigaBytes/s}\] **Answer: B — 16 GigaBytes/s.** A: **Incorrect:** `8 GigaBytes/s` is the Single Data Rate (SDR) bandwidth (1 transfer per clock cycle), forgetting to multiply by 2 for DDR. B: **Correct:** Transferring \(64\text{ bits} = 8\text{ Bytes}\) twice per clock cycle at \(1\text{ GHz}\) yields \(8 \times 2 \times 1 = 16\text{ GigaBytes/s}\). C: **Incorrect:** Triple data rate is not used here; \(8 \times 2 = 16\text{ GB/s}\). D: **Incorrect:** `16 GigaBytes/s` is listed in Option B.

Report a correction for Q11

Question 12 MCQ · 5.0 marks

Examine the following Python test file:
Source diagram or notation
Source diagram or notation
6406537365958.
pytest payment_tests.py -m unit
6406537365959.
pytest payment_tests.py -m integration
6406537365960.
pytest payment_tests.py -m "not slow"
6406537365961.
pytest payment_tests.py -m "slow or integration"
6406537365962.
None of these

Published solution

**1. Count the tests and markers in `payment_tests.py`:** There are **4 test functions** in total: 1. `test_tax_calculation`: marked with `@pytest.mark.unit` (passes: `100 * 0.1 == 10`). 2. `test_valid_payment`: marked with `@pytest.mark.integration` (passes: `50 == 50`). 3. `test_tax_and_payment_flow`: marked with `@pytest.mark.slow` and `@pytest.mark.integration` (**fails!** Because `calculate_tax(200)` is `20.0`, and `assert result == 2` fails since `20.0 != 2`!). 4. `test_negative_tax`: marked with `@pytest.mark.unit` (passes: `-50 * 0.1 == -5`). **2. Match the output `2 passed, 2 deselected`:** We need a `-m` marker expression that selects **2 tests that both pass** and deselects the other **2 tests**: - **`pytest payment_tests.py -m unit` (Option A):** Selects the 2 `@pytest.mark.unit` tests (`test_tax_calculation` and `test_negative_tax`), both of which **pass** (`2 passed`), and deselects the 2 integration tests (`2 deselected`)! - (Note: `-m integration` would select 2 tests, one of which fails: `1 failed, 1 passed, 2 deselected`; `-m "not slow"` selects 3 tests: `3 passed, 1 deselected`.) **Answer: A — pytest payment_tests.py -m unit.** A: **Correct:** Running `-m unit` selects the 2 unit tests (both of which pass) and deselects the 2 integration tests, producing `2 passed, 2 deselected`. B: **Incorrect:** In `-m integration`, `test_tax_and_payment_flow` asserts `20.0 == 2`, which fails (`1 failed, 1 passed, 2 deselected`). C: **Incorrect:** Only 1 test is marked `slow`, so `-m "not slow"` selects 3 tests and deselects 1 (`3 passed, 1 deselected`). D: **Incorrect:** This selects the 2 integration tests (including the failing one). E: **Incorrect:** Option A (`pytest payment_tests.py -m unit`) produces the exact output shown.

Report a correction for Q12

Question 13 MCQ · 2.0 marks

Which of the following statements is/are correct? **Statement 1:** A single physical machine can simultaneously run software performing the roles of a client, web server, and database server. **Statement 2:** The terms client and server describe logical software roles rather than requiring separate physical machines.
6406537365963.
Only Statement 1 is correct
6406537365964.
Both are incorrect
6406537365965.
Both are correct
6406537365966.
Only Statement 2 is correct

Published solution

**1. Evaluate Statement 1 and Statement 2:** - **Statement 1:** *"A single physical machine can simultaneously run software performing the roles of a client, web server, and database server."* **Correct!** For example, during local web development, your laptop runs the web browser (client), the Flask app (`127.0.0.1:5000`, web server), and SQLite/PostgreSQL (database server) all on the same physical machine. - **Statement 2:** *"The terms client and server describe logical software roles rather than requiring separate physical machines."* **Correct!** "Client" (the process initiating a request) and "server" (the process listening for and responding to requests) are logical communication roles in a network protocol, not hardware constraints. **Answer: C — Both are correct.** A: **Incorrect:** Statement 2 is also correct because client and server are logical software roles. B: **Incorrect:** Both statements are foundational truths of client-server architecture. C: **Correct:** Client, web server, and database server are logical software roles that can all run concurrently on a single physical host or across separate machines. D: **Incorrect:** Statement 1 is also correct.

Report a correction for Q13

Question 14 MCQ · 2.0 marks

In a standard web-based MVC implementation, what is the typical flow when an end-user submits a web form to update their profile information?
6406537365967.
View → Model → Controller → View
6406537365968.
Controller → Model → View → Controller
6406537365969.
Model → Controller → View → Model
6406537365970.
View → Controller → Model → View

Published solution

**1. Trace a form submission in a web-based Model-View-Controller (MVC) architecture:** 1. **View:** The user interacts with the rendered HTML form in the **View** and clicks submit. 2. **Controller:** The HTTP form submission request is routed to the **Controller** (e.g., a Flask route handler), which parses the input and orchestrates the business logic. 3. **Model:** The Controller calls the **Model** (e.g., SQLAlchemy ORM models) to validate and update the user's profile data in the database. 4. **View:** Once the Model updates, the Controller renders and returns the updated **View** back to the user's browser. Thus, the flow is **View -> Controller -> Model -> View**. **Answer: D — View -> Controller -> Model -> View.** A: **Incorrect:** In standard web MVC, the View does not bypass the Controller to mutate the Model directly on form submission. B: **Incorrect:** The user starts by submitting the form from the View, and ends by seeing the updated View. C: **Incorrect:** An end-user interacts with the View, not directly with the database Model. D: **Correct:** The user submits the form in the View, which sends a request to the Controller, which updates the Model and renders the updated View.

Report a correction for Q14

Question 15 MCQ · 2.0 marks

When constructing an HTML5 form, which
Source diagram or notation
element correctly uses native browser validation to require an email address and displays a hint inside the empty field?
6406537366015.Source diagram or notation
6406537366016.Source diagram or notation
6406537366017.Source diagram or notation
6406537366018.Source diagram or notation

Published solution

**1. Check the HTML5 ``‹input›`` attributes required by the question:** We need an ``‹input›`` element that: 1. Validates that the input is a properly formatted **email address** \(\implies\) `type="email"` 2. Displays a **hint inside the empty text field** before the user types \(\implies\) `placeholder="Enter your email"` 3. Prevents form submission if the field is left **empty** \(\implies\) `required` **2. Match with the options:** Option B (``‹input type="email" placeholder="Enter your email" required›``) includes all three standard HTML5 attributes (`type="email"`, `placeholder`, and `required`). **Answer: B — `‹input type="email" placeholder="Enter your email" required›`.** A: **Incorrect:** Uses non-standard or wrong attributes (`type="text"` does not validate email format, or `hint` instead of `placeholder`). B: **Correct:** `type="email"` enforces email format validation, `placeholder` shows a hint inside the empty input box, and `required` ensures the field cannot be submitted blank. C: **Incorrect:** `value` pre-fills actual submitted text rather than displaying a disappearing hint (`placeholder`), or omits `type="email"`. D: **Incorrect:** Does not use the standard HTML5 `type="email"`, `placeholder`, and `required` attributes.

Report a correction for Q15

Question 16 MCQ · 2.0 marks

Sessions are used primarily to:
6406537366050.
Give the server information about what the client was doing previously.
6406537366051.
Limit the amount of time a user can connect to a system.
6406537366052.
Allow the government to intercept communications.
6406537366053.
None of these

Published solution

**1. Understand the purpose of Sessions in HTTP web applications:** HTTP is inherently a **stateless** protocol—each HTTP request is independent, and by default the server has no memory of previous requests from the same client. **Sessions** solve this by associating a session identifier (typically stored in a cookie) with state data so that across multiple requests, **the server has information about who the client is and what the client was doing previously** (e.g., logged-in user identity, shopping cart contents, previous steps in a workflow). **Answer: A — Give the server information about what the client was doing previously.** A: **Correct:** Because HTTP is stateless, sessions maintain state across multiple HTTP requests so the server knows what the client did in earlier requests. B: **Incorrect:** While sessions can have expiration timeouts, their primary purpose is maintaining state across stateless HTTP requests, not restricting connection duration. C: **Incorrect:** Sessions are an application-state mechanism, unrelated to communication interception. D: **Incorrect:** Option A accurately states the primary purpose of sessions.

Report a correction for Q16

Question 17 MCQ · 2.0 marks

Source diagram or notation
6406537366064.
Both Statement 1 and Statement 2 are correct.
6406537366065.
Both Statement 1 and Statement 2 are incorrect.
6406537366066.
Statement 1 is incorrect, but Statement 2 is correct.
6406537366067.
Statement 1 is correct, but Statement 2 is incorrect.

Published solution

**1. Evaluate Statement 1 and Statement 2 on software testing:** - **Statement 1:** *"Unit testing is strictly a black-box testing technique because developers only care about the final function output."* **Incorrect!** Unit testing is primarily a **white-box** (glass-box) testing technique written by developers who have full visibility into the internal code structure, branches, edge cases, and implementation details of the function/class being tested. - **Statement 2:** *"Test-Driven Development (TDD) requires developers to write unit test cases before writing the actual production code implementation."* **Correct!** TDD follows the **Red-Green-Refactor** cycle: first write a failing unit test (**Red**), then write the minimal production code to make the test pass (**Green**), and finally clean up the code (**Refactor**). **Answer: C — Statement 1 is incorrect, but Statement 2 is correct.** A: **Incorrect:** Statement 1 is false because unit testing is typically a white-box testing technique where internal code paths and branches are tested. B: **Incorrect:** Statement 2 is true because writing tests before implementation is the core principle of Test-Driven Development (TDD). C: **Correct:** Unit testing is white-box (not strictly black-box), making Statement 1 incorrect, while TDD indeed requires writing unit tests before production code, making Statement 2 correct. D: **Incorrect:** Statement 1 is incorrect and Statement 2 is correct.

Report a correction for Q17

Question 18 MCQ · 2.0 marks

Consider the following Flask-SQLAlchemy models and data.
Source diagram or notation
Source diagram or notation
Source diagram or notation
Based on the above data, answer the given subquestions.
What does the **result** represent when the following code is executed?
Source diagram or notation
6406537365979.
A list containing the Order objects with order_id 101 and 102
6406537365980.
A list containing only the Order object with order_id 101
6406537365981.
A list containing only the amount values 500 and 700
6406537365982.
A single Order object with order_id 101

Published solution

**1. Trace the Flask-SQLAlchemy query and relationship access:** Looking at the `customer` and `order` tables in the comprehension passage: - In `customer`, `Alice` has `customer_id = 1`. - In `order`, the rows with `customer_id = 1` are `order_id = 101` (`amount = 500`) and `order_id = 102` (`amount = 700`). Now trace the code: ```python customer = Customer.query.filter_by(name="Alice").first() result = customer.orders ``` - `customer` is the `Customer` object for `Alice` (`customer_id = 1`). - Because `orders = db.relationship("Order", backref="customer")` is defined on `Customer`, accessing `customer.orders` returns a **Python list of all `Order` model instances** associated with `customer_id = 1`—namely, the `Order` objects with **`order_id` 101 and 102**. **Answer: A — A list containing the Order objects with order_id 101 and 102.** A: **Correct:** `customer.orders` is a one-to-many ORM relationship attribute that returns the list of `Order` instances belonging to Alice (`order_id` 101 and 102). B: **Incorrect:** Alice has two orders in the `order` table (`101` and `102`), both of which are returned in the list. C: **Incorrect:** `customer.orders` returns `Order` model instances, not raw integer `amount` values. D: **Incorrect:** A one-to-many `db.relationship` (with default `uselist=True`) always returns a collection (list) of objects, not a single object.

Report a correction for Q18

Question 19 MSQ · 3.0 marks

Consider the following Flask-SQLAlchemy models and data.
Source diagram or notation
Source diagram or notation
Source diagram or notation
Based on the above data, answer the given subquestions.
Which of the following statements is/are correct when the following code is executed?
Source diagram or notation
6406537365983.Source diagram or notation
6406537365984.Source diagram or notation
6406537365985.Source diagram or notation
6406537365986.Source diagram or notation
6406537365987.
The result will give value David

Published solution

**1. Trace the query on the `Order` model:** ```python order = Order.query.filter_by(amount=500).order_by(Order.order_id).all() result = order[1].customer.name ``` Looking at the `order` table for rows where `amount == 500`: - `order_id = 101`: `customer_id = 1` (`Alice`), `amount = 500` - `order_id = 104`: `customer_id = 4` (`David`), `amount = 500` Sorted by `Order.order_id`, `.all()` returns a two-element list: - `order[0]`: the `Order` object with `order_id = 101` (belongs to `Alice`) - `order[1]`: the `Order` object with `order_id = 104` (belongs to `David`) **2. Evaluate each statement:** - **Statement B:** `order` is a list containing the `Order` objects with `order_id` 101 and 104. (**Correct!**) - **Statement D:** Using the `backref="customer"`, `order[1].customer` navigates from `order_id = 104` (`customer_id = 4`) to the `Customer` object with name `David`. (**Correct!**) - **Statement E:** `result = order[1].customer.name` evaluates to `"David"`. (**Correct!**) - Statements A and C are false because `Alice` corresponds to `order[0]`, not `order[1]` (Python uses 0-based indexing). **Answer: B, D, E — order contains Order objects 101 and 104, order[1].customer is David's Customer object, and result is David.** A: **Incorrect:** Python lists are 0-indexed, so `order[0]` is Alice's order (`101`), while `order[1]` is David's order (`104`). B: **Correct:** Filtering `Order` by `amount=500` ordered by `order_id` returns the list of `Order` objects with `order_id` 101 and 104. C: **Incorrect:** `order[1]` is the second element (`order_id = 104`), whose customer is `David`, not `Alice`. D: **Correct:** Via `backref="customer"`, `order[1].customer` returns the `Customer` instance for `customer_id = 4` (`David`). E: **Correct:** Accessing `.name` on `order[1].customer` yields `'David'`.

Report a correction for Q19

Question 20 MCQ · 2.0 marks

Consider the following Python Flask code.
Source diagram or notation
Based on the above data, answer the given subquestions.
Source diagram or notation
6406537365988.
Product 10
6406537365989.
This site can’t be reached
6406537365990.
Not Found
6406537365991.
/product/10

Published solution

**1. Examine the `/product/new` route handler in `app.py`:** ```python @app.route("/product/<int:id>") def product(id): return f"Product {id}" @app.route("/product/new") def new_product(): return url_for("product", id=10) ``` Notice that `new_product()` calls `return url_for("product", id=10)` **directly** without wrapping it in `redirect(...)`! **2. Determine what `url_for("product", id=10)` returns:** `url_for("product", id=10)` generates and returns the relative URL string for the `product` endpoint with `id=10`, which is the string: `"/product/10"` Because `new_product()` returns this string directly as the HTTP response body (instead of calling `redirect(url_for(...))`), the browser simply displays **`/product/10`**. **Answer: D — /product/10.** A: **Incorrect:** `new_product()` returns the string from `url_for(...)` directly without calling `redirect()`, so it does not redirect to `/product/10` to render `Product 10`. B: **Incorrect:** The server is running on port `5001` and `/product/new` is a valid registered route. C: **Incorrect:** `/product/new` is explicitly defined, so no `404 Not Found` occurs. D: **Correct:** `url_for("product", id=10)` returns the URL string `"/product/10"`, which Flask sends directly as the response text.

Report a correction for Q20

Question 21 MSQ · 3.0 marks

Consider the following Python Flask code.
Source diagram or notation
Based on the above data, answer the given subquestions.
Source diagram or notation
6406537365992.Source diagram or notation
6406537365993.Source diagram or notation
6406537365994.Source diagram or notation
6406537365995.Source diagram or notation
6406537365996.Source diagram or notation

Published solution

**1. Check which URLs result in `Product 10` being displayed on the browser screen:** From the comprehension code: 1. `@app.route("/product/<int:id>")` renders `f"Product {id}"`. 2. `@app.route("/product/new")` returns the plain string `"/product/10"` (no redirect). 3. `@app.route("/item/<int:id>")` returns `redirect(url_for("product", id=id))`, which sends an HTTP `302` redirect to `/product/<id>`, causing the browser to fetch `/product/10` and display `Product 10`! **2. Test each option:** - **Option A (`http://127.0.0.1:5001/product/new`):** Displays `"/product/10"`, not `"Product 10"`. - **Option B (`http://127.0.0.1:5001/product/10`):** Matches `/product/<int:id>` with `id=10` and renders **`Product 10`**. (**Correct!**) - **Option C (`http://127.0.0.1:5001/item/10`):** Matches `/item/<int:id>` with `id=10`, which redirects the browser to `/product/10` and renders **`Product 10`**. (**Correct!**) - **Options D & E (`/item?id=10` and `/product?id=10`):** Use query parameters `?id=10` instead of path parameters `/10`, resulting in `404 Not Found` because no `/item` or `/product` route without `<int:id>` is defined. **Answer: B, C — http://127.0.0.1:5001/product/10 and http://127.0.0.1:5001/item/10.** A: **Incorrect:** `/product/new` returns the URL string `"/product/10"` without redirecting. B: **Correct:** Directly visiting `/product/10` invokes `product(10)`, which returns `"Product 10"`. C: **Correct:** Visiting `/item/10` invokes `item(10)`, which redirects the browser to `/product/10` and displays `"Product 10"`. D: **Incorrect:** The route expects a path parameter `/item/<int:id>`, not a query string `/item?id=10` (which gives 404). E: **Incorrect:** The route expects a path parameter `/product/<int:id>`, not a query string `/product?id=10` (which gives 404).

Report a correction for Q21

Question 22 MSQ · 5.0 marks

Consider the following Python Flask code.
Source diagram or notation
6406537365997.Source diagram or notation
6406537365998.Source diagram or notation
6406537365999.Source diagram or notation
6406537366000.Source diagram or notation
6406537366001.Source diagram or notation

Published solution

**1. Trace `session` and `counter` across three requests to `http://127.0.0.1:5000/`:** Look carefully at `app.py`: ```python session = {} @app.route("/") def home(): counter = 0 user = request.args.get("user") if "visits" not in session: session["visits"] = 0 session["visits"] += 1 counter += 1 return f"User={user}, SessionVisits={session['visits']}, GlobalCounter={counter}" ``` - **`session`:** Defined at the module level as a global Python dictionary `session = {}` (shadowing `flask.session`). On the 1st request, `session["visits"]` is initialized to `0` and incremented to `1`. On the 2nd request, `"visits"` is already in the global dict `session`, so it increments to `2`. On the 3rd request, it increments to **`3`**! - **`counter`:** Inside `home()`, the first line is `counter = 0`! Because `counter` is a **local variable** re-initialized to `0` at the beginning of **every request** and then incremented by `1` (`counter += 1`), `GlobalCounter` **always remains `1`** on every single call! **Answer: B, C — GlobalCounter always remains 1 even when called thrice, and SessionVisits reaches 3 when called thrice.** A: **Incorrect:** Because `session = {}` is a module-level dictionary that persists in memory across requests, `session['visits']` increments on each call (`1, 2, 3`). B: **Correct:** Because `counter = 0` is a local variable reset to `0` inside `home()` on every request before `counter += 1`, `GlobalCounter` is always `1`. C: **Correct:** After three requests, `session['visits']` is incremented three times in the module-level `session` dictionary, reaching `3`. D: **Incorrect:** `counter` is local to `home()` and resets to `0` on every call, so it never reaches `3`. E: **Incorrect:** `counter` starts at `0` and executes `counter += 1`, so it is `1`, not `0`.

Report a correction for Q22

Question 23 MSQ · 5.0 marks

Source diagram or notation
6406537366019.Source diagram or notation
6406537366020.Source diagram or notation
6406537366021.Source diagram or notation
6406537366022.Source diagram or notation

Published solution

**1. Understand Python's `string.Template` substitution rules:** In `code.py`, `from string import Template` is used with: ```html `‹div›` `‹h2›`User Profile: $username`‹/h2›` `‹p›`Role: ${role_name}`‹/p›` `‹p›`Status: $status_msg`‹/p›` `‹/div›` ``` In `string.Template`, `$identifier` matches the longest valid Python identifier characters (letters, digits, and underscores `_`), or `${identifier}` when braced. Therefore: - `$username` looks up `"username"` (`"John Doe"`). - `${role_name}` looks up `"role_name"` (`"Admin"`). - `$status_msg` (because `_` is a valid identifier character) looks up the full key **`"status_msg"`** (`"Account Verified"`), **not** `"status"`! **2. Evaluate each statement:** - **Statement A:** False — `$status_msg` matches `"status_msg"`, not `"status"` (to match `"status"` followed by literal `"_msg"`, it would have to be written `${status}_msg`). - **Statement B:** True — `$status_msg` matches `"status_msg"` and renders ``‹p›`Status: Account Verified`‹/p›``. - **Statement C:** False — if `"Admin"` (the second argument `args[1]`) were omitted in `python code.py "John Doe"`, `args[0]` is still `"John Doe"`, so `user` would still be `"John Doe"` (while `role` would default to `"Standard"`), not `"Guest"`. - **Statement D:** True — if `"status_msg"` were removed from `data_context`, `template.substitute(data_context)` would raise a **`KeyError`** for the missing placeholder `$status_msg`, which is caught by `except Exception as e:`! **Answer: B, D — $status_msg matches "status_msg" and renders `‹p›`Status: Account Verified`‹/p›`, and removing "status_msg" raises a KeyError caught by the except block.** A: **Incorrect:** Because underscores are valid identifier characters in `string.Template`, `$status_msg` parses as the single identifier `status_msg`, not `status`. B: **Correct:** `$status_msg` looks up the key `"status_msg"` in `data_context` and substitutes `"Account Verified"`. C: **Incorrect:** Omitting only the second argument `"Admin"` leaves `args[0] = "John Doe"`, so `user` is `"John Doe"` and `role` defaults to `"Standard"`. D: **Correct:** `Template.substitute()` raises a `KeyError` whenever a template placeholder key is missing from the mapping, which is caught by `except Exception`.

Report a correction for Q23

Question 24 MSQ · 5.0 marks

Source diagram or notation
6406537366024.Source diagram or notation
6406537366025.Source diagram or notation
6406537366026.Source diagram or notation
6406537366027.Source diagram or notation
6406537366028.Source diagram or notation

Published solution

**1. Analyze the three route definitions and their allowed HTTP methods in `app.py`:** 1. `@app.route('/resource', methods=['GET'])` - `get_resource()` returns `"Resource Data", 200`. 2. `@app.route('/resource', methods=['POST'])` - `create_resource()` returns `"Resource Created", 201`. 3. `@app.route('/resource/<int:res_id>', methods=['DELETE', 'PUT'])` - `modify_resource(res_id)` returns `f"Deleted {res_id}", 200` on `DELETE` and `f"Updated {res_id}", 200` on `PUT`. **2. Evaluate each statement:** - **Statement A:** Sending a `GET` request to `/resource` invokes `get_resource()`, returning status code `200` with body `"Resource Data"`. (**Correct!**) - **Statement B:** Sending a `POST` request to `/resource` invokes `create_resource()`, returning status code `201` with body `"Resource Created"`. (**Correct!**) - **Statements C & D:** Sending a `GET` request to `/resource/10` fails with `405 Method Not Allowed` because `/resource/<int:res_id>` only allows `['DELETE', 'PUT']`, not `GET`! (**Incorrect.**) - **Statement E:** Sending a `PUT` request to `/resource` (without `/<int:res_id>`) fails with **`405 Method Not Allowed`** because `/resource` only allows `GET` and `POST`. (**Correct!**) **Answer: A, B, E — GET /resource returns 200 "Resource Data", POST /resource returns 201 "Resource Created", and PUT /resource returns 405 Method Not Allowed.** A: **Correct:** `GET /resource` matches `get_resource()` and returns `"Resource Data"` with status `200`. B: **Correct:** `POST /resource` matches `create_resource()` and returns `"Resource Created"` with status `201`. C: **Incorrect:** `/resource/<int:res_id>` only permits `DELETE` and `PUT`, so a `GET` request to `/resource/10` returns `405 Method Not Allowed`. D: **Incorrect:** A `GET` request to `/resource/10` returns `405 Method Not Allowed`. E: **Correct:** The `/resource` route only registers `GET` and `POST`, so sending a `PUT` request to `/resource` returns `405 Method Not Allowed`.

Report a correction for Q24

Question 25 NAT · 3.0 marks

A passenger ferry departs from a port terminal equipped with a maritime Wi-Fi transmitter having a line-of-sight range of 9 kilometers and a constant throughput of 4 Mbps. The ferry leaves the port terminal and travels directly out to sea at a steady speed of 36 km/h. Assuming a passenger on board continuously streams video using the full available bandwidth, how much data (in Megabytes) will be transferred before the connection drops? (Assume 8 bits = 1 Byte, 1000 Bytes = 1 KB, 1000 KB = 1 MB).

Published solution

**1. Calculate how long the ferry stays within the Wi-Fi transmitter's range:** We are given: - Transmitter line-of-sight range: \(d = 9\text{ km}\) - Ferry speed: \(v = 36\text{ km/h}\) The time \(t\) until the ferry travels \(9\text{ km}\) and loses the connection is: \[t = \frac{d}{v} = \frac{9\text{ km}}{36\text{ km/h}} = 0.25\text{ hours}\] Convert \(0.25\text{ hours}\) into seconds: \[t = 0.25 \times 3600\text{ seconds} = 900\text{ seconds}\] **2. Calculate the total data transferred in Megabytes (MB):** The constant throughput is \(R = 4\text{ Mbps} = 4 \times 10^6\text{ bits/second}\). With \(8\text{ bits} = 1\text{ Byte}\), \(1000\text{ Bytes} = 1\text{ KB}\), and \(1000\text{ KB} = 1\text{ MB}\), the transfer rate in Megabytes per second (MB/s) is: \[R = \frac{4\text{ Megabits/s}}{8\text{ bits/Byte}} = 0.5\text{ MegaBytes/second}\] Multiplying by the connection duration \(t = 900\text{ seconds}\): \[\text{Total Data} = 0.5\text{ MB/s} \times 900\text{ s} = 450\text{ MB}\] **Answer: 450.**

Report a correction for Q25

Question 26 NAT · 3.0 marks

Source diagram or notation

Published solution

**1. Understand trailing slash behavior in Flask routing (Werkzeug):** In Flask (`@app.route`): - **Rule 1 (`'/api/v1/status/'` — defined WITH a trailing slash, default `strict_slashes=True`):** Works like a filesystem folder: - Requesting `/api/v1/status` (without slash) returns a `308 Permanent Redirect` to `/api/v1/status/` (not a 404). - Requesting `/api/v1/status/` (with slash) returns `200 OK`. - **Rule 2 (`'/api/v1/metrics'` — defined WITHOUT a trailing slash, default `strict_slashes=True`):** Works like a filesystem file: - Requesting `/api/v1/metrics` (without slash) returns `200 OK`. - Requesting **`/api/v1/metrics/` (WITH a trailing slash)** does **not** match and returns **`404 Not Found`**! - **Rule 3 (`'/api/v1/logs/'`, with `strict_slashes=False`):** Because `strict_slashes=False` is explicitly set, both `/api/v1/logs` and `/api/v1/logs/` match and return `200 OK`. **2. Count how many of the 4 requests return `404 Not Found`:** 1. `GET /api/v1/status` \(\implies 308\) Redirect (then `200 OK`) 2. `GET /api/v1/status/` \(\implies 200\) OK 3. `GET /api/v1/metrics/` \(\implies \mathbf{404\text{ Not Found}}\) 4. `GET /api/v1/logs` \(\implies 200\) OK Thus, exactly **1** request results in a `404 Not Found` response. **Answer: 1.**

Report a correction for Q26

Question 27 NAT · 3.0 marks

A magnetic disk operating at 7200 rpm is being used to store data. The disk can only spin in one direction at a constant speed of 7200 revolutions per minute. If the operating system sends a request to the disk controller to fetch data from the disk, what is the worst case latency (in msec) before it can start retrieving data?

Published solution

**1. Understand worst-case rotational latency of a magnetic disk:** We are given a disk spinning at a constant speed of \(7200\text{ rpm}\) (revolutions per minute) in one direction. In the **worst case**, the target sector has just passed beneath the read/write head at the exact instant the request arrives, forcing the disk to complete **1 full revolution** before the sector reaches the head again. **2. Calculate the time for 1 full revolution in milliseconds (ms):** - Revolutions per second: \[\frac{7200\text{ revolutions}}{60\text{ seconds}} = 120\text{ revolutions/second}\] - Time for 1 full revolution (worst-case rotational latency): \[T_{\text{worst}} = \frac{1\text{ second}}{120} = \frac{1000\text{ ms}}{120} = \frac{25}{3}\text{ ms} \approx 8.3333\text{ ms} \approx 8.33\text{ ms}\] **Answer: 8.33.**

Report a correction for Q27

Question 28 NAT · 3.0 marks

Source diagram or notation

Published solution

**1. Recall pytest's default test discovery naming conventions:** When executing `pytest test_user.py`, pytest discovers test methods inside classes according to two strict default rules: 1. **Class name rule:** The class name **must start with `Test`** (and the class must not have an `__init__` method). 2. **Method name rule:** The method name inside that class **must start with `test_`**. **2. Check the classes and methods in `test_user.py`:** - **`class TestUserAuth`:** Starts with `Test` (discovered by pytest!): - `def test_login(self)`: Starts with `test_` \(\implies\) **Discovered and executed (#1)!** - `def check_logout(self)`: Starts with `check_`, not `test_` \(\implies\) Ignored by pytest. - **`class AuthTests`:** Does **not** start with `Test` (starts with `Auth`) \(\implies\) The entire class is ignored by pytest, so `test_reset_password` inside it is **not** discovered! Thus, pytest discovers and executes only **1** test method (`TestUserAuth.test_login`). **Answer: 1.**

Report a correction for Q28

Question 29 MCQ · 4.0 marks

Source diagram or notation
6406537366029.Source diagram or notation
6406537366030.Source diagram or notation
6406537366031.Source diagram or notation
6406537366032.Source diagram or notation

Published solution

**1. Trace `render_template_string` and Flask's default Jinja2 template context:** In `app.py`: ```python @app.route('/profile/<username>') def user_profile(username): return render_template_string(NAV_TEMPLATE, user=username) ``` When a client sends `GET /profile/iitm-bs`: - `username` is `'iitm-bs'`, passed into the template as `user='iitm-bs'`. - In Flask, Jinja2 templates rendered via `render_template` or `render_template_string` automatically have access to standard Flask globals/functions including **`url_for`** and **`request`**! - `{{ url_for('user_profile', username=user) }}` evaluates to `"/profile/iitm-bs"`. - `{{ request.path }}` evaluates to `"/profile/iitm-bs"`. - `{{ request.method }}` evaluates to `"GET"`. **2. Assemble the rendered HTML:** ```html `‹nav›` `‹a href="/profile/iitm-bs"›`Profile`‹/a›` `‹p›`Current Path: /profile/iitm-bs`‹/p›` `‹p›`Method: GET`‹/p›` `‹/nav›` ``` **Answer: A — `‹nav›``‹a href="/profile/iitm-bs"›`Profile`‹/a›``‹p›`Current Path: /profile/iitm-bs`‹/p›``‹p›`Method: GET`‹/p›``‹/nav›`.** A: **Correct:** Flask automatically injects `url_for` and `request` into Jinja2 templates, resolving the URL and path to `/profile/iitm-bs` and the method to `GET`. B: **Incorrect:** `url_for('user_profile', username=user)` generates the full route URL `/profile/iitm-bs`, not the function name `user_profile`. C: **Incorrect:** Flask's template context processor automatically provides `request`, `session`, `g`, and `url_for` inside `render_template_string`. D: **Incorrect:** The endpoint `'user_profile'` and required parameter `username=user` are both valid, so no `BuildError` occurs.

Report a correction for Q29

Question 30 MCQ · 4.0 marks

Source diagram or notation
Based on the above data, answer the given subquestions.
Source diagram or notation
6406537366033.
0 and then 1
6406537366034.
1 and then 1
6406537366035.
None and then None
6406537366036.
None and then 1

Published solution

**1. Understand when SQLAlchemy assigns an auto-incrementing primary key (`id`):** In the `Student` model, `id = db.Column(db.Integer, primary_key=True)` is an auto-incrementing integer primary key generated by the SQLite database upon `INSERT`. Let us trace the interactive session: 1. `s1 = Student(name="IITM", gpa=8.8)`: Creates a transient Python object in memory; `id` was not passed, so `s1.id` is **`None`**. 2. `db.session.add(s1)`: Places `s1` in the session's pending state in memory, but **has not yet flushed an `INSERT` statement to the database**! 3. First `print(s1.id)`: Because no database flush/commit has occurred yet, `s1.id` is still **`None`**. 4. `db.session.commit()`: Flushes the `INSERT` statement to SQLite and commits the transaction. SQLite assigns the first auto-increment primary key **`1`** to `s1.id`. 5. Second `print(s1.id)`: Now prints **`1`**. **Answer: D — None and then 1.** A: **Incorrect:** Before flushing to the database, an unassigned column attribute in SQLAlchemy is `None`, not `0`. B: **Incorrect:** `db.session.add(s1)` only stages the object in memory; the auto-increment ID is not generated until flush/commit. C: **Incorrect:** After `db.session.commit()`, the row is inserted into SQLite and `s1.id` is populated with `1`. D: **Correct:** Before `commit()` (and before any flush), `s1.id` is `None`; after `commit()` inserts the first row into the table, `s1.id` becomes `1`.

Report a correction for Q30

Question 31 MCQ · 4.0 marks

Source diagram or notation
Based on the above data, answer the given subquestions.
Source diagram or notation
6406537366037.Source diagram or notation
6406537366038.Source diagram or notation
6406537366039.Source diagram or notation
6406537366040.Source diagram or notation

Published solution

**1. Compare `.first()` and `.all()` in Flask-SQLAlchemy when no rows match:** - **`res1 = Student.query.filter_by(id=99).first()`:** `.first()` returns the first matching model instance, or **`None`** if no rows match the query (it never raises an exception). Thus, `res1` is **`None`**. - **`res2 = Student.query.filter_by(name="NonExistent").first()`:** Similarly, since no student has `name="NonExistent"`, `.first()` returns **`None`**. Thus, `res2` is **`None`**. - **`res3 = Student.query.filter_by(name="NonExistent").all()`:** `.all()` always returns a **Python `list`** of matching objects. When zero rows match, `.all()` returns an **empty list `[]`**. **Answer: C — res1 is None, res2 is None, and res3 is an empty list [ ].** A: **Incorrect:** `.all()` never raises `NoResultFound` (only `.one()` raises `NoResultFound`); `.all()` returns an empty list `[]`. B: **Incorrect:** `.all()` returns an empty list `[]`, not `None`. C: **Correct:** When a query matches no rows, `.first()` returns `None` (`res1` and `res2`) and `.all()` returns an empty list `[]` (`res3`). D: **Incorrect:** `filter_by(id=99).first()` safely returns `None` without raising `KeyError`.

Report a correction for Q31

Question 32 MSQ · 2.0 marks

Suppose you have an HTML element with **id="box"**. Which of the following JavaScript statements will successfully change the background color of the element to blue?
6406537366054.Source diagram or notation
6406537366055.Source diagram or notation
6406537366056.Source diagram or notation
6406537366057.Source diagram or notation

Published solution

**1. Check each JavaScript DOM statement for setting the background color of `id="box"`:** - **Option A (`document.getElementById('box').style.backgroundColor = 'blue';`):** In the JavaScript DOM `style` object, hyphenated CSS property names (`background-color`) are accessed using **camelCase** (`backgroundColor`). This is valid and sets the background color to blue! (**Correct!**) - **Option B (`document.getElementById('box').style.background-color = 'blue';`):** In JavaScript, the hyphen `-` is parsed as the **subtraction operator** (`style.background - color = 'blue'`), which throws a `ReferenceError: Invalid left-hand side in assignment`! (**Incorrect.**) - **Option C (`document.getElementById('box').css('background-color', 'blue');`):** `.css(...)` is a jQuery method on a jQuery wrapper object, not a native DOM `HTMLElement` method (`TypeError: ...css is not a function`). (**Incorrect.**) - **Option D (`document.getElementById('box').setAttribute('style', 'background-color: blue;');`):** `setAttribute('style', ...)` sets the HTML `style` attribute string directly using standard CSS syntax (`background-color: blue;`). This is valid and sets the background color to blue! (**Correct!**) **Answer: A, D — style.backgroundColor = 'blue' and setAttribute('style', 'background-color: blue;').** A: **Correct:** Accessing `style.backgroundColor` in camelCase is the standard DOM API way to set `background-color`. B: **Incorrect:** Using a hyphen in `style.background-color` is interpreted as subtraction in JavaScript and causes a syntax/reference error. C: **Incorrect:** Native DOM elements returned by `getElementById` do not have a `.css()` method (that belongs to jQuery). D: **Correct:** `setAttribute('style', 'background-color: blue;')` sets the inline HTML `style` attribute directly with valid CSS.

Report a correction for Q32

Question 33 MSQ · 4.0 marks

Source diagram or notation
6406537366058.Source diagram or notation
6406537366059.Source diagram or notation
6406537366060.Source diagram or notation
6406537366061.Source diagram or notation
6406537366062.Source diagram or notation

Published solution

**1. Understand how stacked Python decorators are applied and executed:** We have: ```python @bold @italic def greet(): return "Hello" ``` In Python, stacking decorators `@bold` above `@italic` above `def greet():` is syntactic sugar for applying them **bottom-to-top (inside-out)**: \[\text{greet} = \text{bold}(\text{italic}(\text{greet}))\] - First, `@italic` wraps the original `greet` function so calling it returns `"`‹i›`Hello`‹/i›`"`. - Second, `@bold` wraps that already-decorated function so calling the outer wrapper returns `"`‹b›`" + "`‹i›`Hello`‹/i›`" + "`‹/b›`" = "`‹b›``‹i›`Hello`‹/i›``‹/b›`"`. **2. Check each statement:** - **Statement A:** The output of `print(greet())` is ``‹b›``‹i›`Hello`‹/i›``‹/b›``. (**Correct!**) - **Statement B:** Decorators are applied from bottom-to-top (inside-out): `@italic` decorates `greet` first, and `@bold` decorates the result. (**Correct!**) - **Statement C:** False, because ``‹b›`` is the outer wrapper and ``‹i›`` is the inner wrapper. - **Statement D:** `@bold` followed by `@italic` on `def greet():` is equivalent to `greet = bold(italic(greet))`. (**Correct!**) - **Statement E:** False (`greet` is the inner function being passed, not the outer caller). **Answer: A, B, D — Output is `‹b›``‹i›`Hello`‹/i›``‹/b›`, decorators apply bottom-to-top, and syntax is equivalent to greet = bold(italic(greet)).** A: **Correct:** `italic(greet)` returns `"`‹i›`Hello`‹/i›`"`, which `bold(...)` then wraps in ``‹b›`...`‹/b›`` to produce ``‹b›``‹i›`Hello`‹/i›``‹/b›``. B: **Correct:** Stacked decorators are evaluated from the bottom decorator closest to the function definition (`@italic`) upward to the top decorator (`@bold`). C: **Incorrect:** That output would require `@italic` to be on top of `@bold`. D: **Correct:** Stacking `@bold` over `@italic` on `def greet` is defined in Python as `greet = bold(italic(greet))`. E: **Incorrect:** `greet` is the target function passed as an argument to `italic`, not a decorator wrapping `italic(bold)`.

Report a correction for Q33