Home / Past papers / MAD1 End Term / this paper

Consider the following models Library and Book corresponding to tables library and book in SQLite database.
```python
class Library(db.Model):
id = db.Column(db.Integer(), primary_key = True)
name = db.Column(db.String(), unique = True)
class Book(db.Model):
id = db.Column(db.Integer(), primary_key = True)
name = db.Column(db.String(), unique = True)
library = db.Column(db.Integer(), unique = True, db.ForeignKey("section.id"))
```
Based on the model schemas, what relationship do the classes Library and Book share?
Consider the following python code snippet "app.py", the HTML files, "base.html" and "home.html" residing in "templates" folder.
app.py
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
app.run(debug=True)
```
home.html
```html
{% extends "base.html" %}
{% block content %}
<h3>This is from home.html</h3>
{% endblock %}
```
base.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h3 style="color: blue;"> This is from base.html </h3>
{% block content %}
{% endblock %}
</body>
</html>
```
What will be the rendered output for base URL if flask app is running locally on
http://localhost:5000
This is from home.html

This is from base.html This is from home.html

This is from home.html This is from base.html

Error

Consider the following Python code snippet.
```python
from string import Template
sentence = Template("A $var1 fox $var2 over the $var3 dog")
output = sentence.safe_substitute(word_dict)
print(output)
```
Which of the following options correctly represent(s) the dictionary `word_dict`, such that the code does not throw any error when run in the terminal?
```python
word_dict = {'var1': 'quick'}
```
```python
word_dict = {'var1': 'quick', 'var2': 'jumps'}
```
```python
word_dict = {'var1': 'quick', 'var2': 'jumps', 'var3': 'lazy'}
```
All of these
Match the platforms given in column A with their correct features in column B.
| Column A | Column B | |---|---| | 1. Desktop | A. Data center storage | | 2. Mobile | B. Keyboard | | 3. Web-based | C. Single function | | 4. Embedded | D. tilt |

Consider the following view function.
```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/employee', methods=['GET', 'POST'])
def show_info():
info = request.args
details = {
'Department': info['dept'],
'ID': info['id'],
'Role': info['role']
}
return details
app.run()
```
If this flask app is running locally on http://127.0.0.1:5000, which of the following URLs will be handled by the controller correctly?
``` http://127.0.0.1:5000?dept=HR&id=101&role=manager ```

http://127.0.0.1:5000/HR/101/manager

``` http://127.0.0.1:5000/employee?dept=HR&id=1018&role=manager ```

``` http://127.0.0.1:5000/employee/HR/101/manager ```

A certain internet connection is established such that its bandwidth reduces to half of its current value every hour. A user connects to this connection at 01:00 pm with the network speed of 4 Mbps, how much data (in GBs) will be consumed by the user by 04:00 p.m in the evening? [round off upto 2 decimal places](Assume that the user is using the entire bandwidth)

Consider the following function to be tested and test functions given in the Python code snippet below.
file.py
```python
def sample_function(x):
var = []
for i in range(x):
var.append((i)**3)
return var
def test_func1():
assert 125 in sample_function(6)
def test_func2():
assert 64 in sample_function(8)
def sample_test3():
assert 125 in sample_function(5)
```
What will be the summary of the output for the command
`pytest file.py` on the terminal?
``` =========== 1 failed, 2 passed in 0.06s =========== ```

``` ========== 2 failed, 1 passed in 0.06s ========== ```

``` ============================= 3 passed in 0.06s ============================= ```

``` ============================= 2 passed in 0.06s ============================= ```
Consider the following HTML document. ```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function makeBold(){
//MISSING JS CODE
}
</script>
</head>
<body>
Enter your name : <input type="text" id="txt1" name="txt1">
<br>
<input type="button" onclick="makeBold();" value="Click Me">
</body>
</html>
```
Replace the **MISSING JS CODE** part with the correct JS code that will change the text box content to bold?
```javascript
t=document.getElementsByName("txt1").value;
t.style.fontWeight="bold";
```
```javascript
t=document.getElementById("txt1").value;
t.style.fontWeight="bold";
```
```javascript
t=document.getElementById("txt1");
t.style.fontWeight="bold";
```
```javascript
t=document.getElementById("txt1");
t.style.fontWeight="bold";
```
Match the following terms with their correct descriptions:
| | | | :--- | :--- | | A. DOM Event | 1. The structure that represents the HTML document and allows interaction with it. | | B. Attributes | 2. A method or action triggered by user interactions like clicks, typing, etc. | | C. Document | 3. The individual elements or parts of a page, such as elements, attributes, or text. | | D. Node | 4. The properties that define the characteristics of an HTML element, like `id`, `class`, etc. | | E. DOM (Document Object Model) | 5. A programming interface for web documents that provides structured access to the document's elements. |

Consider the following Table products in SQLite database created using model class Product and the python file main.py given below.
products:
| id | pro_name | section |
|:---|:----------|:-----------|
| 1 | Palm Oil | food |
| 2 | Butter | food |
| 3 | Pencil | art |
| 4 | Face wash | cosmetics |
| 5 | Olive | vegetables |
main.py
```python
from jinja2 import Template
templates = """
{% if result %}
<ol>
{% for product in products %}
<li>{{product.pro_name}}</li>
<li>{{product.section}}</li>
{% endfor %}
</ol>
{% endif %}
"""
products = Product.query.filter_by(section = 'food').all()
Templates = Template(templates)
result = Templates.render(products = products)
print(result)
```
What will be the output on the terminal?
Palm Oil food Butter food

```html
<ol>
<li>Palm Oil food</li>
<li>Butter food</li>
</ol>
```
Palm Oil food Butter food

```html
<ol>
<li>Palm Oil</li>
<li>food</li>
<li>Butter</li>
<li>food</li>
</ol>
```
Consider the following Python code snippet.
```python
from math import factorial
def prettify(func):
def wrapper(num):
try:
return func(num)
except:
return "Please check your number!"
return wrapper
@prettify
def fact(num):
return factorial(num)
out = fact(5)
print(out)
```
What will the output if the above Python code is run on the terminal?
-120

120

Please check your number!

None of these.

Consider the following Python code snippet.
file.py
```python
from string import Template as makeTemplate
from jinja2 import Template
import sys
var = sys.argv[2]
data = {"name": "Alice", "activity": "data analysis",
"tool": "Python", "goal": "insights"}
temp = "{{name}} performs $activity using $tool to gain {{goal}}."
if var == "python":
temp = makeTemplate(temp)
out = temp.substitute(data)
output = Template(out)
output = output.render(data)
print(output)
else:
temp = Template(temp)
output = temp.render(data)
print(output)
```
What will be printed on the terminal for the command `python file.py ml python`?
Alice performs $activity using $tool to gain insights.

```
{{name}} performs $activity using $tool to gain {{goal}}.
```
Alice performs data analysis using Python to gain insights.

```
Alice performs $activity using $tool to gain {{goal}}.
```
Consider the following HTML document.
How will the browser render above HTML file?```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
p {
background-color: yellow;
color: red;
display: inline-block;
}
#id {
border: 2px solid purple;
color:blue ;
}
.class1 {
background-color: aqua;
color: red;
}
.class2{
background-color: lightgreen;
color: darkgreen;
}
</style>
</head>
<body>
<p class="class1" id="id">Code 1</p>
<p class="class1 class2" >Code 2</p>
<p class="class1">Code 3</p>
<p >Code 4</p>
</body>
</html>
```
This is a diagram showing four stacked rectangular blocks, each with text. The top block is light blue with a purple border and contains the text "Code 1" in blue. The second block is light green and contains the text "Code 2" in green. The third block is light blue and contains the text "Code 3" in brown. The bottom block is yellow and contains the text "Code 4" in orange.

This is a diagram showing four colored horizontal bars, each with text. - Top bar (cyan with a purple border): Code 1 - Second bar (cyan): Code 2 - Third bar (light green): Code 3 - Bottom bar (yellow): Code 4

Code 1 Code 2 Code 3 Code 4

The image displays four rectangular boxes arranged horizontally. 1. The first box has a purple border and a light blue fill. Inside, the text "Code 1" is written in blue. 2. The second box has a light green fill. Inside, the text "Code 2" is written in green. 3. The third box has a light blue fill. Inside, the text "Code 3" is written in red. 4. The fourth box has a yellow fill. Inside, the text "Code 4" is written in red.

Refer to the project with three files: `conftest1.py`, `test_multiples_of_3_and_6.py`, and `test_multiples_of_13.py`.
The purpose of the tests is to verify if numbers generated by each function are divisible by 39. However, there is a setup issue in this project.
* `conftest1.py` contains a fixture that provides test data.
* `test_multiples_of_3_and_6.py` has two functions: one checks divisibility by 3, and the other by 6.
* `test_multiples_of_13.py` contains a function to check divisibility by 13.
Here is the content of each file:
**conftest1.py**
```python
import pytest
@pytest.fixture
def divisible_by_39():
return 39 # Fixture providing the number to be tested
```
**test_multiples_of_3_and_6.py**
```python
import pytest
def test_divisible_by_3(divisible_by_39):
assert divisible_by_39 % 3 == 0 # Checks if divisible by 3
def test_divisible_by_6(divisible_by_39):
assert divisible_by_39 % 6 == 0 # Checks if divisible by 6
```
**test_multiples_of_13.py**
```python
import pytest
def test_divisible_by_13(divisible_by_39):
assert divisible_by_39 % 13 == 0 # Checks if divisible by 13
```
When you run `pytest -k divisible`, which of the following is **true**?
``` ========== 1 passed in 0.02s ========== ```

``` ========== 3 passed in 0.02s ========== ```

``` ========= 1 failed, 2 passed in 0.06s ========= ```

``` ========== 3 errors in 0.02s ========== ```

Consider the following Python code snippet that returns the potential energy stored in an object of a certain mass at a certain height. (PE = mgh, where "g" is acceleration due to gravity). ```python from jinja2 import Template x = Template(template) ``` What should be the value of template if; `print(x.render(mass = "5", height = "22"))` returns 1100 and `print(x.render())` returns 3000

```
"{{ mass|default(3)|int*gravity|default(10)|int*height|default(100)|int }}"
```
```
"{{ mass|int|default(3)*gravity|int|default(10)*height|int|default(100) }}"
```
```
"{{ mass|default(5)|int*gravity|default(10)|int*height|default(100)|int }}"
```
```
"{{ mass|int|default(5)*gravity|int|default(10)*height|int|default(100) }}"
```
Consider the following flask app. Given that `test_request_context()` allows text to be printed on the terminal, which of the following statements is/are correct?
```python
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/products')
def products():
return 'Product List'
@app.route('/product/<int:product_id>/<string:name>')
def product_detail(product_id, name):
return f'Product ID: {product_id}, Name: {name}'
with app.test_request_context():
#== print statement ==#
```
If `print statement` is replaced by:
```python
print(url_for('products', category="electronics"))
```
the output on the terminal will be;
`/products?category=electronics`
If #== *print statement* ==# is replaced by:
```python
print(url_for('products', category="electronics")),
```
the output on the terminal will be;
/products/electronics
If #== print statement ==# is replaced by:
```python
print(url_for('product_detail', product_id=101, name="Gadget", discount=20))
```
the output on the terminal will be;
/product/101/Gadget?discount=20
If #== print statement ==# is replaced by:
```python
print(url_for('product_detail', product_id=101, name="Gadget", discount=20))
```
the output on the terminal will be;
/product/101/Gadget/20
Consider the following code snippet.
```python
from flask import Flask
import logging
app = Flask(__name__)
logging.basicConfig(filename='logger.log', level=logging.INFO,
format=f'%(asctime)s : %(message)s')
@app.route('/home')
def home():
app.logger.debug('This is a debug log')
app.logger.warning('This is a warning log')
return f"Application Dashboard"
if __name__ == "__main__":
app.run()
```
Suppose the given flask application is running locally on http://127.0.0.1:5000, which of the following statements is/are true if you hit the URL http://127.0.0.1:5000/home ?
A file called "logger.log" will be created inside the Flask application root folder.

The message "Application Dashboard" will be displayed within the log file.

The message "This is a debug log" will be logged inside the "logger.log" file.

The message "This is a warning log" will be logged inside the "logger.log" file.
Consider the following flask application running on the base URL and is accessed through a browser. Select the correct option(s).
```python
app = Flask(__name__)
users = {
1 : {"Name": "Mukesh", "role": "Admin", "access": True},
2 : {"Name": "Gautam", "role": "User", "access": True},
3 : {"Name": "Narendra", "role": "Admin", "access": True},
4 : {"Name": "Amit", "role": "User", "access": False}
}
@app.route('/login')
def auth():
cred = request.args
if users[int(cred["id"])].get("access"):
id = int(cred["id"])
user = users[id]
return "Welcome, "+ user.get("Name")+", you have "+user.get("role") \
+ " access"
else:
abort(403)
@app.errorhandler(403)
def no_access(error):
return "You are an unauthorized user!"
app.run(debug = True)
```
For the URL: http://127.0.0.1:5000?id=2, The browser will render; Welcome, Gautam, you have User access.

For the URL: http://127.0.0.1:5000/login?id=1, The browser will render; Welcome, Mukesh, you have Admin access.

For the URL: http://127.0.0.1:5000/login?id=3, The browser will render, Welcome, Narendra, you have User access.

For the URL: http://127.0.0.1:5000/login?id=4, The browser will render, You are an unauthorized user!
Consider the following Python code snippet. File name: main.py
```python
import sys
def func1(x):
return x > 0
def func2(x):
return x % 2 == 0
def test_fun3(x):
assert func1(x) == True, str(x) + " is not even/odd"
assert func2(x) == True, str(x) + " is even number"
assert x % 2 != 0, str(x) + " is odd number"
x = int(sys.argv[1])
test_fun3(x)
```
Which of the following is the correct combinations of “command line argument” and “assertion error”?
Command: python main.py 9 AssertionError: 9 is even number

Command: python main.py 90 AssertionError: 90 is odd number

``` Command: python main.py 0 AssertionError: 0 is not even/odd ```

Command: python main.py 9 AssertionError: 9 is odd number

Command: python main.py 90 AssertionError: 90 is even number
Consider the following HTML document.
Which of the following statements is/are correct about the above code snippet?```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IITM</title>
</head>
<body>
<h2>Welcome to IITM </h2>
<h3>Online Degree</h3>
Courses offered
<ol>
<li>Foundation</li>
<ul>
<li>CT</li>
<li>Python</li>
<li>Maths-I</li>
</ul>
<li>Diploma</li>
<ul>
<li>PDSA</li>
<li>MAD-I</li>
<li>MAD-II</li>
</ul>
</ol>
</body>
</html>
```
Consider a comma-separated values (CSV) file with all characters set ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b"]. You need to store a file consisting of 2000 characters mentioned only in the above list without spaces. How many minimum number of bytes are required to store this CSV file efficiently?

You are connected to a server that can process 1500 requests per second. Each request is a constant size of 100KB. You are connected to the above server through a network line with a speed of 2Gbps. What is the maximum number of requests per second that the server can handle(in KBps)? (Consider that 1000Bytes=1KB, 1000KB = 1MB)?


Which of the following urls will display [Joker] on the browser?

http://127.0.0.1:5000/action

http://127.0.0.1:5000/thriller

http://127.0.0.1:5000/comedy

http://127.0.0.1:5000?genre=thriller

What will be displayed on the browser for the url: http://127.0.0.1:5000?genre=action ?

[5, 3]

``` ["Spider man 1", "Batman"] ```

``` ["Sam Raimi", "Matt Reeves"] ```

None of these.


What will be the output of the below terminal request? ``` curl http://127.0.0.1:5000/api/get_account/fd101 -X GET ```

```json
{
"name": "Jack",
"balance": 71600
}
```
Sorry, account no. fd101 does not exist

Account no. fd101 does not exist and balance not updated...

```json
{
"name": "Syam",
"balance": 9600
}
```
Which of the following command will update balance of account no. **ca101**?

```
curl http://127.0.0.1:5000/api/update_balance/ca101 -X POST -d
"{\"balance\":\"15890\"}" -H "Content-Type: application/json"
```
```
curl http://127.0.0.1:5000/api/get_balance/ca101 -X POST -d
"{\"balance\":\"15890\"}" -H "Content-Type: application/json"
```
```
curl http://127.0.0.1:5000/api/get_balance/ca101 -X PUT -d
"{\"balance\":\"15890\"}" -H "Content-Type: application/json"
```
```
curl http://127.0.0.1:5000/api/update_balance/ca101 -X PUT -d
"{\"balance\":\"15890\"}" -H "Content-Type: application/json"
```
Use the Python code given below for answering the subquestions:

Assume you have the following Item API endpoint as shown in the code. If a client sends a POST request with an existing item name but missing the price field in the JSON payload, what will happen, and why?

The server will add a new item with **None** as the price value and return a 201 status code since there is no validation for the price field.

The server will raise a KeyError because it tries to access data['price'] without validating if price is present, returning a 500 Internal Server Error.

The server will return a 400 status code with the message "Item already exists" because it first checks for the item's existence before attempting to access price.

The server will reject the request and return a 404 status code, indicating a missing field, because price is required.

What will be the status code of the response for the request: ``` curl http://127.0.0.1:5000/item/candle?price=120 -X POST ```
Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of the core topics, concepts, and principles essential for the Diploma Level: Modern Application Development I exam, along with key equations (where applicable) and Mermaid knowledge graphs.
One-to-Many: A single record in Table A relates to multiple records in Table B (e.g., Library → Book).
Book), a column references the primary key of the parent table (Library).library column in Book references section.id (non-existent table), so the tables are unrelated (Answer: D).Key Equation (Foreign Key Syntax):
library = db.Column(db.Integer(), db.ForeignKey("library.id")) # Correct reference
Template Inheritance: {% extends "base.html" %} inherits from a parent template.
{% block content %}{% endblock %} defines replaceable sections.Example (Q3):
<!-- base.html -->
<body>{% block content %}{% endblock %}</body><!-- home.html --> {% extends "base.html" %} {% block content %}<h3>This is from home.html</h3>{% endblock %} `` **Rendered Output**: Content from base.html + home.html` (Answer: B).
Safe Substitution: Template.safe_substitute() ignores missing keys (unlike substitute(), which raises KeyError).
Example (Q4):
word_dict = {'var1': 'quick'} # Missing var2/var3 → No error with safe_substituteQuery Parameters: Accessed via request.args (e.g., /employee?dept=HR&id=101).
Example (Q7):
@app.route('/employee')
def show_info():
info = request.args # {'dept': 'HR', 'id': '101', 'role': 'manager'}
Correct URL: http://127.0.0.1:5000/employee?dept=HR&id=101&role=manager (Answer: C).
URL Generation: url_for() generates URLs dynamically.
Example (Q19):
url_for('products', category='electronics') # Output: /products?category=electronicsCustom Errors: Use @app.errorhandler to define responses for HTTP errors (e.g., 403 Forbidden).
Example (Q21):
@app.errorhandler(403)
def no_access(error):
return "You are an unauthorized user!", 403Configuration: Log messages to files with logging.basicConfig.
Example (Q20):
logging.basicConfig(filename='logger.log', level=logging.WARNING)
app.logger.warning("This will be logged") # Logs to fileResources: Define APIs using Resource classes (e.g., GET, POST).
Example (Q30):
class Accounts(Resource):
def get(self, id):
return accounts_data.get(id, {"error": "Not found"}), 404 if missing else 200JavaScript: Modify element styles/properties.
Example (Q10):
document.getElementById("txt1").style.fontWeight = "bold"; // Makes text boldInline vs. Class vs. ID: ID (#id) overrides class (.class) and inline styles.
Example (Q16):
<p class="class1" id="id">Code 1</p> <!-- ID styles take precedence -->Ordered (<ol>) vs. Unordered (<ul>) Lists:
Example (Q25):
<ol>
<li>Foundation <!-- Numbered (1) -->
<ul>
<li>CT</li> <!-- Bulleted -->
</ul>
</li>
</ol>Assertions: Verify function outputs.
Example (Q9):
def test_func1():
assert 125 in sample_function(6) # Passes (5³=125 in [0,1,8,27,64,125])
def test_func2():
assert 64 in sample_function(8) # Fails (8³=512 not in first 8 cubes)
Output: 1 failed, 2 passed (Answer: D).
Fixtures: Reusable test data (e.g., divisible_by_39 in Q17).
conftest1.py (should be conftest.py) → 3 errors (Answer: D).InfluxDB: Optimized for time-stamped data (e.g., metrics, logs).
Other Options (Q5):
| Platform | Feature |
|---|---|
| Desktop | Keyboard |
| Mobile | Tilt |
| Web-based | Data center storage |
| Embedded | Single function |
Correct Match (Answer: C): 1 → B, 2 → D, 3 → A, 4 → C.
Problem: Bandwidth halves hourly; initial = 4 Mbps.
Bits per Character: For 12 unique chars, \(\lceil \log_2(12) \rceil = 4\) bits/char.
Server Limit: 1500 requests/sec (bottleneck).
ABAC (Attribute-Based):
Client-Side Validation:
Limitations:
Rules: