Question 1
What of the following is the primary objective of a CSRF token?
To encrypt the user's session
To validate that the request comes from the authenticated user
To store the user's password securely
To compress the HTTP request
The IIT Madras BS Modern Application Development II (MAD 2) End Term paper sat on 1 Sept 2024, in the May 2024 term: 32 questions for 100 marks in 180 minutes. Every question is below with its answer. Take it as a timed mock test to be marked, or read it through first.
What of the following is the primary objective of a CSRF token?
To encrypt the user's session
To validate that the request comes from the authenticated user
To store the user's password securely
To compress the HTTP request
Correct answer
To validate that the request comes from the authenticated user
Suppose an application is being loaded from the origin https://example.com. Which of the following origins will the browser allow while making a fetch call, by default?
Correct answer
What is the correct sequence of steps to update the state in Vuex when handling an asynchronous operation?
State → Dispatch an action → Commit a mutation → State change
Dispatch an action → Commit a mutation → State change
Commit a mutation → Dispatch an action → State change
State change → Commit a mutation → Dispatch an action
Correct answer
Dispatch an action → Commit a mutation → State change
Suppose you are developing an application for millions of users that will perform intensive data analysis and return the results asynchronously. Arrange the following set of actions/operations to achieve an efficient and scalable design.
I) Save the result to a database
II) Invoke a callback URL
III) Queue the analysis job
II, I, III
III, I, II
III, II, I
I, II, III
Correct answer
III, I, II
Which of the following statements about Redis is true?
Redis is a relational database that uses SQL for querying data.
Redis is an in-memory data structure store, commonly used as a database, cache, and message broker.
Redis can only store string data types and does not support complex data structures like lists or sets.
Redis cannot handle numerous operations per second.
Correct answer
Redis is an in-memory data structure store, commonly used as a database, cache, and message broker.
Which of the following scenarios is an example of a Cross-Site Request Forgery (CSRF) attack?
A user receives an email containing a link to a phishing site that asks for their login credentials.
A user clicks on a malicious link while logged into their bank account, and without their knowledge, a money transfer request is sent to the bank's server using the user's authenticated session.
A hacker uses a brute-force attack to guess the password of a user's online account.
A user is tricked into downloading and installing malware that steals their sensitive information.
Correct answer
A user clicks on a malicious link while logged into their bank account, and without their knowledge, a money transfer request is sent to the bank's server using the user's authenticated session.
Match the following technologies with their typical use cases:
1 - C, 2 - A, 3 - D, 4 - B, 5 - E
1 - D, 2 - E, 3 - A, 4 - C, 5 - B
1 - C, 2 - C, 3 - E, 4 - A, 5 - D
1 - D, 2 - A, 3 - C, 4 - D, 5 - B
Correct answer
1 - C, 2 - A, 3 - D, 4 - B, 5 - E
Consider the below javascript program.
function parent() { var a = 1; function child() { console.log(a); } a = 2; return child;}
var closure = parent();closure();What will be the output of the above program, if executed?
2
1
undefined
Error
Correct answer
2
Consider the following JavaScript code snippet.
// Code Snippet 1sessionStorage.setItem('username', 'course_user');let storedUsername = sessionStorage.getItem('username');
// Code Snippet 2sessionStorage.removeItem('username');let removedUsername = sessionStorage.getItem('username');
// Code Snippet 3sessionStorage.clear();let clearedStorage = sessionStorage.username;What will be the values of 'storedUsername', 'removedUsername', and 'clearedStorage' after the execution of the above code snippets?
storedUsername: 'course_user', removedUsername: null, clearedStorage: null
storedUsername: 'course_user', removedUsername: undefined,
clearedStorage: null
storedUsername: 'course_user', removedUsername: null, clearedStorage: undefined
storedUsername: 'course_user', removedUsername: undefined,
clearedStorage: undefined
Correct answer
storedUsername: 'course_user', removedUsername: null, clearedStorage: undefined
Consider the following javascript code
const obj = { num: 40, regularFunction: function() { return this.value; }, arrowFunction: () => { return this.value; }};
const regularResult = obj.regularFunction();const arrowResult = obj.arrowFunction();What are the values of regularResult and arrowResult?
regularResult = 40, arrowResult = 40
regularResult = undefined, arrowResult = undefined
regularResult = 40, arrowResult = undefined
regularResult = undefined, arrowResult = 40
Correct answer
regularResult = 40, arrowResult = undefined
Consider the below 2 approaches:
Approach 1:
<script> setInterval(() => document.title = "Title A", 2000) setInterval(() => document.title = "Title B", 1000)</script>Approach 2:
<script> setInterval(() => document.title = "Title A", 1000) setInterval(() => document.title = "Title B", 2000)</script>Choose the correct statement:
The approach 1 will toggle the page title between “Title A” and “Title B” after every 1 second (approx).
The approach 2 will toggle the page title between “Title A” and “Title B” after every 1 second (approx).
None of the approaches will toggle the page title after every 1 second.
None of these
Correct answer
None of the approaches will toggle the page title after every 1 second.
Consider the below JavaScript program.
<script> for (var i = 0; i <= 3; i++) { setTimeout(() => console.log(i), (i+1)*1500); }</script>What will be the output of the above program, if executed? Also, predict the minimum number of seconds the program will take to complete the execution?
Correct answer
Which of the following statement(s) is/are true about webhooks?
Webhooks use HTTP requests to communicate events from one service to another.
Webhooks require the recipient service to periodically poll the sender for updates.
Webhooks are typically implemented using HTTP POST requests.
Webhooks guarantee that events will be delivered in order and exactly once.
Correct answers
Webhooks use HTTP requests to communicate events from one service to another.
Webhooks are typically implemented using HTTP POST requests.
Which of the following statement(s) is/are true regarding javascript?
Function declarations are hoisted along with their definitions.
Variable declarations with var are hoisted with their initializations.
let and const declarations are hoisted to the top of their block but remain uninitialized until execution reaches the declaration.
Only function declarations are hoisted, not function definition.
Correct answers
Function declarations are hoisted along with their definitions.
let and const declarations are hoisted to the top of their block but remain uninitialized until execution reaches the declaration.
Which of the following scenarios are best suited for using Celery tasks?
Handling real-time user interactions on a website.
Sending out periodic email notifications to users.
Generating and displaying dynamic content on a web page.
Performing long-running data processing tasks in the background.
Correct answers
Sending out periodic email notifications to users.
Performing long-running data processing tasks in the background.
Which of the following statements is/are true regarding webhooks and server sent events (SSE)?
Webhooks are typically used for server-to-server communication, while SSE is used for server-to-client communication.
Webhooks require the client to maintain an open connection to receive updates, while SSE does not.
Webhooks are initiated by the server, while SSE connections are initiated by the client.
SSE supports bidirectional communication, whereas webhooks do not.
Correct answers
Webhooks are typically used for server-to-server communication, while SSE is used for server-to-client communication.
Webhooks are initiated by the server, while SSE connections are initiated by the client.
Which of the following is/are the correct ways to achieve the following.
1. Always apply class named “errorClass”,
2. The class named “activeClass” should only be applied when the Vue data variable “isActive” is truthy
Correct answers
Which of the following is/are true about Server-Sent Events (SSE)?
SSE connections are established using HTTP.
SSE supports bidirectional communication between client and server.
SSE automatically switches to web socket if the connection is successful.
SSE is suitable for sending updates to multiple clients simultaneously.
Correct answers
SSE connections are established using HTTP.
SSE is suitable for sending updates to multiple clients simultaneously.
Which of the following HTTP header(s) can be used to control caching behavior in web applications?
Cache-Control
Expires
Bearer
Content-Type
Correct answers
Cache-Control
Expires
Which of the following statement(s) is/are true regarding long and short polling?
A webhook is the same as short polling.
The short polling can be used to know the state of an asynchronous task, and trigger an action if the task gets completed.
The long polling cannot be achieved using HTTP protocol.
Long Polling can be used to achieve real time communication.
Correct answers
The short polling can be used to know the state of an asynchronous task, and trigger an action if the task gets completed.
Long Polling can be used to achieve real time communication.
Consider the following Vue.js 2 component using CDN.
<div id="app"> <input v-model="newItem" placeholder="Add an item" /> <button @click="addItem">Add</button>
<ul> <li v-for="(item, index) in items" :key="index"> {{ index + 1 }}. {{ item }} </li> </ul></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script><script> new Vue({ el: '#app', data: { newItem: '', items: ['Apple', 'Banana'] }, methods: { addItem() { if (this.newItem) { this.items.push(this.newItem, this.newItem); this.newItem = ''; } } } });</script>After entering "Orange" in the input box and clicking the "Add" button, what will be seen in the browser?
1. Apple
2. Banana
3. Orange
4. Orange
1. Apple
2. Banana
3. Orange
1. Apple
2. Banana
3. Orange
3. Orange
1. Apple
2. Banana
Correct answer
1. Apple
2. Banana
3. Orange
4. Orange
Consider the following javascript code running on browser
localStorage.setItem('counter', '0');sessionStorage.setItem('total', '5');
for (let i = 0; i < 3; i++) { let counter = localStorage.getItem('counter'); let total = sessionStorage.getItem('total');
counter += 2; total *= 2;
localStorage.setItem('counter', counter); sessionStorage.setItem('total', total);}
sessionStorage.clear();
console.log(localStorage.getItem('counter'));console.log(sessionStorage.getItem('total'));What will be the output in the browser console?
6
40
null
40
6
null
0222
null
Correct answer
0222
null
Consider the below JavaScript program.
class Animal { constructor(name) { this.name = name; }
speak() { console.log(`${this.name} makes a noise.`); }}
class Dog extends Animal { speak() { console.log(`${this.name} barks`); }}
const d = new Dog('Rex');d.speak();console.log(d.__proto__ === Dog.prototype);console.log(d.__proto__.__proto__ === Animal.prototype);What will be the output of the above program?
Rex barks
true
true
Rex barks
false
true
Rex barks.
true
false
Rex barks.
false
false
Correct answer
Rex barks
true
true
Consider the below flask application.
from flask import Flaskfrom flask_caching import Cachefrom time import sleep
config = { "CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 180}
app = Flask(__name__)app.config.from_mapping(config)cache = Cache(app)
@cache.memoize(timeout=180)def get_data(param): sleep(5) return f"Data for {param}"
@app.route('/data/<param>')def data(param): result = get_data(param) return f"Result: {result}"
if __name__ == '__main__': app.run(debug=True)If the application is running on “http://127.0.0.1:5000” and the user visits the URL “http://127.0.0.1:5000/data/test” three times in the following sequence:
1. First visit
2. Second visit after 2 minutes and 30 seconds
3. Third visit after 1 minute from the second visit
What will be the approximate difference in response times between the first and third requests?
5 seconds
0 seconds
10 seconds
180 seconds
Correct answer
0 seconds
Consider the below JavaScript program.
new Promise((resolve, reject) => { const num = 0.6; if (num > 0.5) { resolve(num); } else { reject(num); }}).then(data => { console.log("Step 1:", data); if (data > 0.75) { return data * 2; } else { return Promise.reject(new Error("Less than 0.75")); }}).then(data => { console.log("Step 2:", data); return data + 5;}).catch(error => { console.log("Step 3:", error.message); if (error.message === "Less than 0.75") { return 1; } else { throw error; }}) .then(data => { console.log("Step 4:", data); if (data === 1) { throw new Error("Fallback value"); } else { return data * 3; }}) .catch(error => { console.log("Step 5:", error.message); return "Error handled";
}).finally(() => { console.log("Step 6: Finally block executed");})What will be the output of the above program?
Step 1: 0.6
Step 2: 1.2
Step 4: 6.2
Step 6: Finally block executed
Step 1: 0.6
Step 3: Less than 0.75
Step 4: 1
Step 5: Fallback value
Step 6: Finally block executed
Step 1: 0.6
Step 2: 1.2
Step 3: Error
Step 4: 1
Step 5: Fallback value
Step 6: Finally block executed
Step 1: 0.6
Step 3: Less than 0.75
Step 4: 1
Step 6: Finally block executed
Correct answer
Step 1: 0.6
Step 3: Less than 0.75
Step 4: 1
Step 5: Fallback value
Step 6: Finally block executed
In a Vue CLI project with Vuex, you have the following configuration:
src/store/index.js:
import Vue from 'vue';import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({ state: { value: " ", }, mutations: { setValue(state, payload) { state.value = payload; } }, actions: { async fetchValue({ commit }) { // Simulate async API call const response = await new Promise(resolve => setTimeout(() =>resolve('API Value'), 500)); commit('setValue', response); } }});src/App.vue:
<template> <div> <p>{{ value }}</p> <button @click="updateValue">Update Value</button> </div></template>
<script>export default { computed: { value() { return this.$store.state.value; } }, methods: { async updateValue() { await this.$store.dispatch('fetchValue'); } }}</script>After running “npm run serve”, if you click the "Update Value" button, what will be displayed in the <p> tag?
Correct answer
Consider the below JavaScript code.
async function newFetch(url) { try { console.log(url) const res = await fetch(url) if (!res.ok) { throw new Error(`HTTP Error: ${res.status}`) } try { const data = await res.json() console.log(data) } catch { throw new Error('Error') } } catch { throw new Error('Data is not JSON serializable') }}newFetch('https://example.com/api/users/23').catch((err) => { console.error(err)})Suppose the API URL “https://example.com/api/users/23” returns a valid HTML output. What will be logged on to console?
“Network Error”
“HTTP Error: 404”
“Data is not JSON serializable”
Data returned by the API
Correct answer
“Data is not JSON serializable”
Consider the following Flask application with Redis caching. Redis is running normally on port 6379.
from flask import Flask, jsonifyfrom flask_caching import Cache
app = Flask(__name__)app.config['CACHE_TYPE'] = 'redis'app.config['CACHE_REDIS_HOST'] = 'localhost'app.config['CACHE_REDIS_PORT'] = 6379cache = Cache(app)
def compute_value(x, y): result = x * y return result
@app.route('/compute/<int:x>/<int:y>')@cache.cached(timeout=60, key_prefix='compute')def compute(x,y): result = compute_value(x, y) return jsonify({'result': result})
if __name__ == '__main__': app.run(debug=True, port=5000)Two requests are given to localhost:5000/compute/10/20 and localhost:5000/compute/5/10 within 60 seconds. What would be the json response from the server respectively?
{“result” : 200} and {“result”: 50}
{“result” : 50} and {“result”: 200}
{“result”: 100} and {“result” : 100}
{“result”: 200} and {“result”: 200}
Correct answer
{“result”: 200} and {“result”: 200}
Options:
A.
import requests
response = requests.get('https://some-api')print(response.json())B.
from flask import Flask, request
app = Flask(__name__)
@app.route('/server-route, methods=['POST'])def server_route(): data = request.json print(data) return 'OK', 200C.
from flask import Flask, Responseimport time
app = Flask(__name__)
def stream(): while True: time.sleep(5) yield f'data: The time is {time.strftime("%Y-%m-%d %H:%M:%S")}\n\n'
@app.route('/server-route')def server_route(): return Response(stream(), mimetype='text/event-stream')
if __name__ == '__main__': app.run(debug=True, port=5000)D.
import timeimport requests
while True: response = requests.get('https://some-endpoint') print(response.json()) time.sleep(10)Based on the above data, answer the given subquestions.
Which code snippet represents a Webhook receiver implementation?
A
B
C
D
Correct answer
B
Options:
A.
import requests
response = requests.get('https://some-api')print(response.json())B.
from flask import Flask, request
app = Flask(__name__)
@app.route('/server-route, methods=['POST'])def server_route(): data = request.json print(data) return 'OK', 200C.
from flask import Flask, Responseimport time
app = Flask(__name__)
def stream(): while True: time.sleep(5) yield f'data: The time is {time.strftime("%Y-%m-%d %H:%M:%S")}\n\n'
@app.route('/server-route')def server_route(): return Response(stream(), mimetype='text/event-stream')
if __name__ == '__main__': app.run(debug=True, port=5000)D.
import timeimport requests
while True: response = requests.get('https://some-endpoint') print(response.json()) time.sleep(10)Based on the above data, answer the given subquestions.
Which code snippet represents a Pub/Sub implementation?
A
B
C
D
Correct answer
C
Filename: script.js
const Error = {template: `<div>Page Not Found</div>`}const Profile = { template: `<div> <div v-if='user'> Name: {{user.name}}, State: {{user.state}} </div> <div v-else> Unknown User </div> </div>`, data() { return { profiles: [ { id: '1234', name: 'Animesh', state: 'MP' }, { id: '1235', name: 'Arnav', state: 'Goa' }, ], } }, computed: { user(){ let user = this.profiles.find((profile) => { return profile.id == this.$route.params.id }) return user }, computed: { user(){ let user = this.profiles.find((profile) => { return profile.id == this.$route.params.id }) return user }, },}
const routes = [ { path: '/profile/:id', component: Profile }, { path: '*', component: Error },]
const router = new VueRouter({ routes,})
new Vue({ el: '#app', router,})Page Not Found
Unknown User
Name: Animesh, State: MP
Name: Arnav, State: Goa
Correct answer
Name: Arnav, State: Goa
Filename: script.js
const Error = {template: `<div>Page Not Found</div>`}const Profile = { template: `<div> <div v-if='user'> Name: {{user.name}}, State: {{user.state}} </div> <div v-else> Unknown User </div> </div>`, data() { return { profiles: [ { id: '1234', name: 'Animesh', state: 'MP' }, { id: '1235', name: 'Arnav', state: 'Goa' }, ], } }, computed: { user(){ let user = this.profiles.find((profile) => { return profile.id == this.$route.params.id }) return user }, computed: { user(){ let user = this.profiles.find((profile) => { return profile.id == this.$route.params.id }) return user }, },}
const routes = [ { path: '/profile/:id', component: Profile }, { path: '*', component: Error },]
const router = new VueRouter({ routes,})
new Vue({ el: '#app', router,})Page Not Found
Name: Animesh, State: MP
Name: Arnav, State: Goa
Unknown User
Correct answer
Unknown User