Home / Past papers / MAD2 End Term / this paper

In the following code, which attributes ensure that the cookie will only be sent over HTTPS and restrict it from cross-site requests?
```
response.set_cookie('session_id', 'abc123', secure=option1, samesite=option2)
```
Given this Vue component structure:
```javascript
Vue.component('child', {
template: `
<div>
<slot name="header" :info="info"></slot>
<slot :info="info"></slot>
</div>
`,
data() {
return {
info: { title: 'Hello', desc: 'World' }
}
}
})
```
Which slot usage is correct?
```html
<template v-slot:header="data">{{data.title}}</template>
```
```html
<template v-slot:header>{{info.title}}</template>
```
```html
<template v-slot:header="{ info }">{{info.title}}</template>
```
```html
<template v-slot:header=info>{{info.title}}</template>
```
Consider the following JavaScript code snippet.
```javascript
Promise.resolve(1)
.then(x => x + 1)
.then(x => Promise.resolve(x + 1))
.then(x => { throw 'error' })
.catch(e => e + 4)
.then(x => console.log(x))
```
Consider the following JavaScript code snippet.
```javascript
async function test() {
console.log("Start");
const val = await Promise.resolve(5);
console.log(val);
return "End";
}
console.log("Begin");
test().then(data => console.log(data));
console.log("Finish");
```
What will be the output sequence?
What will happen if a page includes this CSP header and the script attempts to load an external JavaScript file from otherurl.com? **CSP Header:** ``` Content-Security-Policy: default-src 'self'; ``` **HTML :** ```html <script src="https://otherurl.com/code.js"></script> ```

The script from otherurl1.com will load normally.

The browser will display a warning and allow the script to load.

Nothing will happen; the CSP only affects inline scripts.

The script will fail to load, and an error will be logged in the console.

Consider the below Vue component.
```html
<template>
<div>
<p v-if="isVisible">This paragraph is visible</p>
<p v-else>This paragraph is hidden</p>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
}
};
</script>
```
What will happen when “this.isVisible = false” is executed?
Consider the below JavaScript program.
```javascript
console.log("Start");
setTimeout(function() {
console.log("Inside Timeout");
}, 0);
Promise.resolve().then(function() {
console.log("Inside Promise");
});
console.log("End");
```
What will be the output of the above program?
Start Inside Timeout Inside Promise End

Start End Inside Promise Inside Timeout

Start Inside Promise Inside Timeout End

Start End Inside Timeout Inside Promise

Consider the below JavaScript program.
```javascript
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hello, " + this.name);
};
const john = new Person("John");
john.greet();
delete john.greet;
john.greet();
```
What will be the output of the above program?
Hello, John TypeError: john.greet is not a function

Hello, John Hello, undefined

Hello, John Hello, John

TypeError: john.greet is not a function TypeError: john.greet is not a function

Given the following routes configured in Vue Router, assuming that routes have
been correctly configured in vue router.
```javascript
const routes = [
{ path: '/', component: Home },
{ path: '/profile/:userId', component: Profile },
{ path: '/settings', component: Settings },
{ path: '/settings/security', component: Security },
{ path: '/*', component: NotFound },
];
```
Which route will match the path /settings/security?
Consider the below Vue component.
```javascript
export default {
data() {
return {
userName: '',
};
},
mounted() {
this.userName = sessionStorage.getItem('userName') || '';
},
watch: {
userName(newVal) {
sessionStorage.setItem('userName', newVal);
}
}
};
```
What will happen when the user enters a new value for "userName" and refreshes the page?
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

Consider the below JavaScript program.
```javascript
const obj = {
name: "Abhi",
greet: function() {
console.log(this.name);
}
};
const greet = obj.greet;
greet();
```
What will be the output of the above program?
Abhi

null

Reference Error

Garbage Value

undefined

Consider the following JavaScript code.
```javascript
function addItemToCart(item) {
let cart = JSON.parse(localStorage.getItem('cart')) || [];
cart.push(item);
localStorage.setItem('cart', JSON.stringify(cart));
}
function getCartItems() {
return JSON.parse(localStorage.getItem('cart')) || [];
}
addItemToCart({ id: 1, name: 'Laptop' }.name);
console.log(getCartItems());
```
The above code is initially loaded on the browser and then the browser is refreshed two times.
What will be the final output?
The image shows a single vertical bar character.

```
[{ id: 1, name: 'Laptop' }]
```
[undefined]

``` ['Laptop', 'Laptop', 'Laptop'] ```

Given the following Vuex store setup.
```javascript
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++;
}
},
actions: {
async incrementAsync({
commit
}) {
await new Promise(resolve => setTimeout(resolve, 1000));
commit('increment');
}
}
});
```
Assuming the store is correctly binded with a Vue app, what will be the correct behavior when the following code is executed?
```javascript
this.$store.dispatch('incrementAsync');
```
Consider the below Vue app.
```javascript
new Vue({
el: '#app',
data: {
user: {
name: 'Abhi',
age: 30
}
},
watch: {
user: {
handler(newValue, oldValue) {
console.log('User object changed:', newValue);
},
deep: true
}
}
});
```
What will happen if the following code is executed?
`app.user.name = "Dev"`
Consider the following HTML, with included vue 2 cdn link.
```html
<div id="app">{{doubledItems}}</div>
<script>
new Vue({
el: '#app',
data() {
return {
items: [1, 2, 3],
processed: []
};
},
computed: {
doubledItems() {
return this.items.map(x => x * 2);
}
},
created() {
this.processItems();
},
methods: {
processItems() {
this.items.push(4);
this.processed = this.doubledItems;
setTimeout(() => {
this.processed = this.processed.map(x =>
this.doubledItems.includes(x) ? x : x * 2
);
}, 0);
}
}
});
</script>
```
What will be displayed ?
Consider the following html with appropriate vue 2 cdn link attached.
```html
<div id="app"></div>
<script>
new Vue({
el: '#app',
template: `
<div>
<form @submit.prevent>
<input v-model="email" @input="validateEmail">
<button type="submit">Submit</button>
<p>Errors: {{ displayErrors.join(', ') }}</p>
</form>
</div>
`,
data() {
return {
email: '',
errors: [],
validating: false,
existingEmails: ['test@test.com', 'example@example.com']
};
},
computed: {
displayErrors() {
return this.validating ? ['Validating...'] :
this.errors;
}
},
methods: {
validateEmail() {
this.validating = true;
this.errors = [];
if (!this.email.includes('@')) {
this.errors.push('@ not present');
}
if (!this.email.includes('.')) {
this.errors.push('invalid format');
}
if (this.existingEmails.includes(this.email)) {
this.errors.push('Email exists');
}
this.validating = false;
}
},
watch: {
email(value) {
if (!value) this.errors = ['Required']
}
}
});
</script>
```
When typing "test@test.com" and then deleting it all, what is shown in the "Errors" paragraph at the end?
Consider the following python code snippet. Assuming proper configuration for caching is done, answer the question below.
```python
from flask import Flask, request
from flask_caching import Cache
import time
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'RedisCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 5
cache = Cache(app)
@app.route('/time')
@cache.cached()
def get_time():
return str(time.time())
```
Suppose the following sequence of requests is made:
Request 1: GET /time at 00:00:00
Request 2: GET /time at 00:00:02
Request 3: GET /time at 00:00:06
What will the responses be for each request?
Request 1: 00:00:00 Request 2: 00:00:02 Request 3: 00:00:06

Request 1: 00:00:00 Request 2: 00:00:02 Request 3: 00:00:02

Request 1: 00:00:00 Request 2: 00:00:00 Request 3: 00:00:00

Request 1: 00:00:00 Request 2: 00:00:00 Request 3: 00:00:06

Consider the below Celery setup.
```python
from celery import Celery
import time
app = Celery('tasks', broker='redis://localhost:6379/0')
@app.task
def long_task():
time.sleep(10)
return 'Task completed'
```
What will be the result of calling long_task.delay() (assuming more than 1 worker are available)?
Consider the following Vue application with markup index.html and JavaScript file script.js.
File: index.html
```html
<div id="app"></div>
<script src="script.js"></script>
```
File: script.js
```javascript
new Vue({
el: '#app',
template: `<div>
Status: {{message}}<br>
ETA: {{ETA}}
</div>`,
data: {
message: "",
ETA: 10,
},
beforeCreate() {
this.message += "DOM Creating,"
this.ETA -= 1
},
created() {
this.message += "DOM Created,"
this.ETA -= 1
},
beforeMount() {
this.message += "DOM Mounting,"
this.ETA -= 1
},
mounted() {
this.message += "DOM Mounted"
this.ETA -= 1
},
})
```
Suppose the application is running on http://127.0.0.1:8080. What will be rendered by the browser?
Status: DOM Mounted ETA: 9

Status: DOM Mounting, DOM Mounted ETA: 8

Status: DOM Created, DOM Mounting, DOM Mounted ETA: 7

Status: DOM Creating, DOM Created, DOM Mounting, DOM Mounted ETA: 6

Consider the below Vue router configuration.
```javascript
const routes = [
{
path: '/user/:id',
component: UserProfile
}
];
const router = new VueRouter({
routes
});
```
Which of the following is a valid way to access the "id" parameter inside the UserProfile component?
``` this.$router.params.id ```

``` this.$route.query.id ```

``` this.$route.params.id ```

``` this.$route.params['id'] ```

Consider the below Vue class binding and select the most appropriate option(s). ```html <div v-bind:class="[isClassA ? classA : '', classB]"></div> ```
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 a Mermaid knowledge graph to visualize relationships.
Cookie Attributes:
Secure: Ensures cookies are sent only over HTTPS.SameSite: Controls cross-site cookie sending (Strict, Lax, None).Example:
response.set_cookie('session_id', 'abc123', secure=True, samesite='Strict')Content Security Policy (CSP):
default-src 'self': Restricts resources to the same origin.<script src="https://otherurl.com/code.js">).Caching Headers:
Cache-Control: no-store: Prevents caching.ETag: Validates cache freshness.localStorage (5–10 MB) > cookies (~4 KB).Promises & Async/Await:
Promise.resolve().then() executes microtasks (higher priority than setTimeout).async functions always return a promise, even for non-promise values.await pauses execution until the promise resolves.Example:
async function test() {
const val = await Promise.resolve(5); // Pauses here
console.log(val); // 5
}Event Loop:
setTimeout, I/O).Example Output:
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output:
Start
End
Promise
TimeoutError Handling:
.catch() handles rejected promises.Example:
Promise.resolve(1)
.then(x => { throw 'error' })
.catch(e => e + 4) // "error4"
.then(x => console.log(x));Lifecycle Hooks:
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeDestroy → destroyed.Example:
beforeCreate() { this.message = "Initializing"; }
mounted() { this.message = "Ready"; }Reactivity:
data() properties are reactive; changes trigger DOM updates.Deep Watchers: Use deep: true to watch nested objects.
watch: {
user: {
handler(newVal) { /* ... */ },
deep: true
}
}Slots & Scoped Slots:
<slot name="header">) and scoped slots (<template v-slot:header="{ info }">).Example:
<child>
<template v-slot:header="{ info }">{{ info.title }}</template>
</child>Vuex:
state, mutations (synchronous), actions (asynchronous).Example:
actions: {
async incrementAsync({ commit }) {
await new Promise(resolve => setTimeout(resolve, 1000));
commit('increment');
}
}Vue Router:
/profile/:userId → Access params via this.$route.params.id.{ path: '*', component: NotFound }.Long Polling:
Server-Sent Events (SSE):
Example:
const eventSource = new EventSource('/updates');
eventSource.onmessage = (e) => console.log(e.data);WebSockets:
Example:
const socket = new WebSocket('ws://example.com');
socket.onmessage = (e) => console.log(e.data);Celery:
Example:
@app.task
def send_email():
time.sleep(10)
return "Sent"
Schedule with Celery Beat:
app.conf.beat_schedule = {
'send-email-every-10-minutes': {
'task': 'send_email',
'schedule': 600.0
}
}Message Brokers:
Lighthouse:
Caching Strategies:
Flask-Caching with Redis:
@cache.cached(timeout=5)
def get_time():
return str(time.time())Event-Driven Architecture:
Example:
// Webhook endpoint
app.post('/webhook', (req, res) => {
console.log('Data received:', req.body);
res.status(200).end();
});localStorage vs. sessionStorage: | Feature | localStorage | sessionStorage | |-----------------------|----------------------|----------------------| | Persistence | Across sessions | Tab-specific | | Storage Limit | ~5–10 MB | ~5 MB | | Data Type | Strings (manual JSON)| Strings |Example:
localStorage.setItem('cart', JSON.stringify([{ id: 1, name: 'Laptop' }]));
const cart = JSON.parse(localStorage.getItem('cart'));javascript Promise.resolve(1) .then(x => x + 1) // 2 .then(x => Promise.resolve(x + 1)) // Promise(3) .then(x => { throw 'error' }) // Throws .catch(e => e + 4) // "error4" ``javascript async function test() { console.log("Start"); const val = await Promise.resolve(5); // Pauses console.log(val); // 5 return "End"; } console.log("Begin"); test().then(data => console.log(data)); console.log("Finish"); ` Output: ` Begin Start Finish 5 End ``javascript data() { return { counter: 0 }; } mutations: { increment(state) { state.counter++; } } ``python @app.task def long_task(): time.sleep(10) return "Done" ` Call: long_task.delay()` (asynchronous).Prioritize:
Common Pitfalls:
this Binding: Arrow functions vs. regular functions in Vue/JS.
const obj = { name: "Abhi", greet: function() { console.log(this.name); } };
const greet = obj.greet;
greet(); // undefined (lost context)this.items[0] = 2) won’t trigger updates. Use Vue.set or splice.task.delay() is asynchronous; task() is synchronous.Debugging:
console.log to trace execution order in async code.