Home / Past papers / MAD2 End Term / this paper

https://api.example.com

http://example.com/api

https://example.com:8080

https://example.com/subdir
Match the following technologies with their typical use cases: | | | |---|---| | 1. Webhooks | A. Real-time communication in chat applications | | 2. Web Sockets | B. Fetching data periodically from an API endpoint | | 3. API | C. Receiving notifications when a specific event occurs | | 4. Polling | D. Exchanging data between client and server using HTTP requests | | 5. Pub/Sub | E. Broadcasting messages to multiple subscribers simultaneously |

Consider the below javascript program.
```javascript
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?
Consider the following JavaScript code snippet.
```javascript
// Code Snippet 1
sessionStorage.setItem('username', 'course_user');
let storedUsername = sessionStorage.getItem('username');
// Code Snippet 2
sessionStorage.removeItem('username');
let removedUsername = sessionStorage.getItem('username');
// Code Snippet 3
sessionStorage.clear();
let clearedStorage = sessionStorage.username;
```
What will be the values of 'storedUsername', 'removedUsername', and 'clearedStorage' after the execution of the above code snippets?
Consider the following javascript code
```javascript
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?
Consider the below 2 approaches:
Approach 1:
```html
<script>
setInterval(() => document.title = "Title A", 2000)
setInterval(() => document.title = "Title B", 1000)
</script>
```
Approach 2:
```html
<script>
setInterval(() => document.title = "Title A", 1000)
setInterval(() => document.title = "Title B", 2000)
</script>
```
Choose the correct statement:
Consider the below JavaScript program.
```html
<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?
0 1 2 3 Minimum time taken will be: 15 sec

1 2 3 4 Minimum time taken will be: 9 sec

3 3 3 3 Minimum time taken will be: 6 sec

4 4 4 4 Minimum time taken will be: 6 sec

```html <div :class="[isActive ? 'activeClass' : 'errorClass']"></div> ```

```html
<div :class="[{ isActive : 'activeClass' }, 'errorClass']"></div>
```
```html <div :class="[activeClass ? 'isActive' : '', 'errorClass']"></div> ```

```html
<div :class="[{'activeClass': isActive }, 'errorClass']"></div>
```
Consider the following Vue.js 2 component using CDN. After entering "Orange" in the input box and clicking the "Add" button, what will be seen in the browser?```html
<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>
```
Consider the following javascript code running on browser What will be the output in the browser console?```javascript
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'));
```
Consider the below JavaScript program.
```javascript
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?
Consider the below flask application. 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?```python
from flask import Flask
from flask_caching import Cache
from 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:
Consider the below JavaScript program.
Consider the below JavaScript program. What will be the output of the above program?```javascript
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;
}
});
```
```javascript
})
.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");
})
```
In a Vue CLI project with Vuex, you have the following configuration:
In a Vue CLI project with Vuex, you have the following configuration: src/store/index.js:
```javascript
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:
```html
<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?
API Value

"" ""

undefined

null

Consider the below JavaScript code.
```javascript
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?
Consider the following Flask application with Redis caching. Redis is running
normally on port 6379.
```python
from flask import Flask, jsonify
from flask_caching import Cache
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_REDIS_HOST'] = 'localhost'
app.config['CACHE_REDIS_PORT'] = 6379
cache = 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)
```
Options:
Options: Based on the above data, answer the given subquestions.



Suppose the application is running on port 8080. What will be rendered inside router-view for the URL "http://127.0.0.1:8080/#/profile/1235"?

Suppose the application is running on port 8080. What will be rendered inside router-view for the URL "http://127.0.0.1:8080/#/profile/Arnav"?
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 core topics, concepts, and principles for the "Modern Application Development II" exam, along with key equations (where applicable) and Mermaid knowledge graphs to visualize relationships.
CSRF (Cross-Site Request Forgery)
CORS (Cross-Origin Resource Sharing)
https://example.com can only fetch from https://example.com by default).Same-Origin Policy (SOP)
Vuex Workflow:
Scalable Architecture for Data-Intensive Apps:
Use Cases for Celery:
Closures
Example:
function parent() {
let a = 2;
return function child() { console.log(a); }; // Logs 2
}
const closure = parent();
closure();this Binding
this = object calling the method.this (inherits from parent scope).Example:
const obj = {
num: 40,
regular: function() { return this.num; }, // 40
arrow: () => this.num // undefined (global/window)
};Hoisting
var: Hoisted with undefined; let/const: Hoisted but uninitialized (Temporal Dead Zone).Storage APIs
sessionStorage: Cleared when tab closes.localStorage: Persists across sessions.Methods:
setItem(key, value)getItem(key) → null if missing.removeItem(key)clear()Event Loop & Timers
setTimeout/setInterval delays are minimum guarantees (not exact).Example:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // Logs 3, 3, 3 (closure over `i`)
}| Technology | Use Case | Protocol | Direction | Connection |
|---|---|---|---|---|
| Webhooks | Server-to-server events | HTTP (POST) | Server → Server | Stateless |
| WebSockets | Real-time chat/gaming | WS/WSS | Bidirectional | Persistent |
| SSE | Server-to-client updates | HTTP | Server → Client | Persistent |
| Polling | Periodic client checks | HTTP | Client → Server | Stateless |
| Long Polling | Near real-time updates | HTTP | Client → Server | Pseudo-persistent |
SSE vs. Webhooks:
HTTP Headers:
Cache-Control: max-age, no-cache, no-store.Expires: Legacy header (use Cache-Control instead).Flask-Caching:
@cache.memoize(timeout=180): Caches function results for 180 seconds.html <div :class="['errorClass', { 'activeClass': isActive }]"></div> ``Vue Router:
/profile/:id) → Access via this.$route.params.id.Reactivity:
v-model binds input to data property.v-for renders lists reactively.Promise Chaining:
new Promise((resolve, reject) => { /* ... */ })
.then(data => { /* ... */ })
.catch(error => { /* ... */ })
.finally(() => { /* ... */ });Error Handling:
catch handles rejections; finally runs regardless of success/failure.Caching with flask_caching:
@cache.memoize(timeout=180)
def get_data(param):
sleep(5) # Simulate slow operation
return f"Data for {param}"
Total Execution Time for setTimeout in loops:
If delays are (i+1)*1500 ms for i = 0, 1, 2, 3:
4 * 1500 = 6000 ms (6 seconds).Cache Hit/Miss:
0 ms (served from cache).this in Arrow Functions: Lexical binding (parent scope).Storage APIs:
sessionStorage → tab-scoped.localStorage → persistent.Real-Time:
@cache.memoize skips function execution on cache hits..finally runs always; .catch handles rejections.