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 exam, along with key equations (where applicable) and Mermaid knowledge graphs to visualize relationships.
CSRF (Cross-Site Request Forgery)
Same-Origin Policy (SOP)
protocol://domain:port) from accessing resources from another origin.Exceptions:
https://example.com ↔ https://example.com/subdir (allowed).https://example.com ↔ https://api.example.com (blocked unless CORS headers permit).Access-Control-Allow-Origin) to relax SOP.Session Storage vs. Local Storage
sessionStorage: Cleared when the tab closes. Scope: per-tab.localStorage: Persists across sessions. Scope: per-origin.Methods:
localStorage.setItem('key', 'value');
sessionStorage.getItem('key');
sessionStorage.removeItem('key');
sessionStorage.clear();Closures & var vs. let in Loops
var in loops creates a single binding; let creates block-scoped bindings.Example (Closure Issue):
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // Outputs: 3, 3, 3
}Fix: Use let or an IIFE:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // Outputs: 0, 1, 2
}Promises & Async/Await
Chaining:
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));Async/Await:
async function fetchData() {
try {
const res = await fetch(url);
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}setInterval vs. setTimeout
setInterval: Repeats a function every X ms (overlapping executions possible).setTimeout: Executes once after X ms (recursive calls for repetition).Vuex Flow:
Example:
// Action
actions: {
fetchData({ commit }) {
api.call().then(response => {
commit('SET_DATA', response);
});
}
},
// Mutation
mutations: {
SET_DATA(state, payload) {
state.data = payload;
}
}Flask-Caching
Decorators:
@cache.cached(timeout=60): Caches the entire view.@cache.memoize(timeout=60): Caches based on function arguments.Redis Config:
app.config['CACHE_TYPE'] = 'redis'
app.config['CACHE_REDIS_URL'] = 'redis://localhost:6379/0'HTTP Caching Headers
Cache-Control: max-age=3600, no-cache, no-store.Expires: Absolute expiry time (e.g., Expires: Thu, 01 Jan 2025 00:00:00 GMT).WebSockets
Example:
const socket = new WebSocket('ws://example.com');
socket.onmessage = (event) => console.log(event.data);Server-Sent Events (SSE)
Example:
const eventSource = new EventSource('/updates');
eventSource.onmessage = (e) => console.log(e.data);Content-Type: text/event-stream.Webhooks
Example:
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
print(data)
return 'OK', 200Use Cases:
Example:
@celery.task
def process_data(data):
# Long-running task
return resultReactivity
v-model: Two-way data binding (e.g., <input v-model="message">).v-for: Render lists:
<li v-for="(item, index) in items" :key="index">{{ item }}</li>Computed Properties: Cached derived data:
computed: {
filteredItems() {
return this.items.filter(item => item.active);
}
}Conditional Rendering
v-if/v-else: Toggles DOM elements.v-show: Toggles display: none.Class Bindings
Object Syntax:
<div :class="{ active: isActive, 'error-class': hasError }"></div>Array Syntax:
<div :class="[isActive ? 'active-class' : '', 'static-class']"></div>Vue Router
Dynamic Routes:
{ path: '/user/:id', component: User }Access Route Params:
this.$route.params.idUse Cases:
@cache.cached with Redis backend).Example:
import redis
r = redis.Redis(host='localhost', port=6379)
r.set('key', 'value')
r.get('key')RESTful APIs
GET, POST, PUT, DELETE.200 OK, 404 Not Found, 500 Server Error.Fetch API
Example:
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data));Hoisting
var: Hoisted and initialized with undefined.let/const: Hoisted but not initialized (Temporal Dead Zone).this Binding
this depends on how the function is called.this is lexically scoped (inherits from parent).Example:
const obj = {
value: 42,
regular: function() { return this.value; }, // 42
arrow: () => this.value // undefined (global `this`)
};Prototype Chain
__proto__: Points to the object’s prototype.Example:
class Animal {}
class Dog extends Animal {}
const d = new Dog();
console.log(d.__proto__ === Dog.prototype); // true
console.log(d.__proto__.__proto__ === Animal.prototype); // true(Limited in this exam, but included for completeness)
Time Complexity of Polling
O(n) requests for n updates.O(1) per update (server holds request until data is available).Cache Hit/Miss
(Hits) / (Hits + Misses).timeout=60 → Cache expires after 60 seconds.Asynchronous Task Delay
setTimeout(fn, (i+1)*1500) → Delays of 1.5s, 3s, 4.5s, 6s.https://example.com and https://example.com:8080 are different origins (port matters).var in loops causes all timeouts to log the final value; use let.@cache.memoize caches based on function arguments; @cache.cached caches the entire view..catch handles rejections; .finally runs regardless of success/failure.