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.
Attack Example:
Mitigation:
{% csrf_token %}).Allowed Origins:
https://example.com → https://example.com/subdir).Access-Control-Allow-Origin header.Key Headers:
Access-Control-Allow-Origin: Specifies allowed origins (e.g., * or https://trusted.com).Access-Control-Allow-Methods: Allowed HTTP methods (e.g., GET, POST).localStorage vs. sessionStorage:
localStorage: Persists across sessions (until cleared).sessionStorage: Cleared when the tab closes.Methods:
setItem(key, value), getItem(key), removeItem(key), clear().Promise States:
Pending → Fulfilled (resolved) or Rejected.Chaining:
.then(): Handles fulfillment..catch(): Handles rejection..finally(): Executes regardless of outcome.Async/Await:
async functions return promises.await pauses execution until the promise settles.Example:
function parent() {
let a = 2;
return function child() { console.log(a); };
}
const closure = parent(); // `a` is retained in `child`'s scope.
closure(); // Output: 2setTimeout/setIntervalBehavior:
setTimeout(callback, delay): Executes callback once after delay ms.setInterval(callback, delay): Executes callback repeatedly every delay ms.Closure Pitfall:
setTimeout may reference the final loop variable value (use let or IIFE to capture values).Phases:
then/catch/finally).setTimeout, setInterval, I/O.State Change triggers reactive updates in components.
this.$store.dispatch('actionName', payload)commit('mutationName', payload)data(): Reactive properties (tracked by Vue).computed: Cached derived data.v-model: Two-way binding (e.g., <input v-model="message">).Use Cases:
@cache.cached(timeout=60) in Flask).Decorators:
@cache.cached(timeout=180): Caches function results for 180 seconds.@cache.memoize: Caches based on function arguments.Cache-Control:
max-age=3600: Cache for 1 hour.no-store: Never cache.no-cache: Revalidate with server before using.Expires: Absolute expiry time (e.g., Expires: Thu, 31 Dec 2023 23:59:59 GMT).Characteristics:
Example:
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
print("Received:", data)
return "OK", 200Features:
text/event-stream MIME type.Example:
const eventSource = new EventSource('/sse-endpoint');
eventSource.onmessage = (e) => console.log(e.data);ws:// or wss:// (secure).Example:
const socket = new WebSocket('wss://example.com/chat');
socket.onmessage = (e) => console.log(e.data);| Method | Direction | Protocol | Real-Time | Overhead |
|---|---|---|---|---|
| Polling | Client → Server | HTTP | ❌ No | High |
| Long Polling | Client → Server | HTTP | ✅ Yes | Medium |
| SSE | Server → Client | HTTP | ✅ Yes | Low |
| WebSockets | Bidirectional | WS/WSS | ✅ Yes | Low (after handshake) |
Use Cases:
Components:
Example:
@celery.task
def send_email(user_id):
user = User.query.get(user_id)
mail.send(...)Syntax:
<div :class="['errorClass', isActive ? 'activeClass' : '']"></div>
or
<div :class="{ 'activeClass': isActive, 'errorClass': true }"></div>Dynamic Routes:
{ path: '/profile/:id', component: Profile }Accessing Params:
this.$route.params.id // e.g., "1235"| Feature | REST API | Webhooks |
|---|---|---|
| Initiator | Client polls server | Server pushes to client |
| Efficiency | High latency | Low latency (event-driven) |
| Use Case | Fetch data on demand | Notify on events (e.g., payments) |
Example (Redis):
# Publisher
redis.publish("channel", "Hello, subscribers!")# Subscriber pubsub = redis.pubsub() pubsub.subscribe("channel") for message in pubsub.listen(): print(message["data"]) ```
| Operation | Complexity |
|---|---|
Redis GET/SET | O(1) |
Array push/pop | O(1) |
Array shift/unshift | O(n) |
| Binary Search | O(log n) |