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 the core topics, concepts, principles, and key takeaways from the exam, along with a Mermaid knowledge graph to visualize relationships.
Cookie Attributes:
secure=True: Ensures cookies are sent only over HTTPS.samesite='Strict'|'Lax'|'None':
Strict: Blocks cross-site requests.Lax: Allows top-level navigations (e.g., links).None: Allows cross-site requests (requires secure=True).Content Security Policy (CSP):
default-src 'self': Restricts resources to the same origin.<script src="otherurl.com">).Promises & Async/Await:
.then() chains handle resolved promises.async/await pauses execution until a promise resolves (but runs asynchronously)..catch() or try/catch.Event Loop:
setTimeout).Example output order:
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output: Start → End → Promise → Timeout.
Lifecycle Hooks:
beforeCreate → created → beforeMount → mounted → ... → beforeDestroy.ETA decreases in each hook (Q25).Reactivity:
data() properties are reactive.computed properties cache results until dependencies change.watch can deep-watch nested objects (deep: true).Slots:
<slot name="header">) pass data via v-slot:header="{ info }".<template v-slot:header="{ info }">{{ info.title }}</template>.Vue Router:
/profile/:userId) are accessed via this.$route.params.userId.*) matches unmatched routes (e.g., 404 pages).Vuex:
incrementAsync).increment).Cache-Control Headers:
no-store: Prevents caching entirely.ETag: Validates cache freshness.localStorage | Persists | Per-origin | ~5MB | Strings (only) | | sessionStorage | Cleared on tab close | Per-tab | ~5MB | Strings (only) | | Cookies | Configurable | Per-domain | ~4KB | Strings |Flask-Caching:
@cache.cached(timeout=5) caches responses for 5 seconds (Q23).Celery:
send_email) to workers.Example:
@app.task
def long_task():
time.sleep(10)
return "Task completed"
long_task.delay() runs asynchronously.Asynchronous Workflows:
III. Queue → I. Save → II. Callback).Webhooks:
SSE vs. WebSockets:
Lighthouse:
Caching Strategies:
javascript Promise.resolve(1) .then(x => x + 1) // 2 .then(x => Promise.resolve(x + 1)) // Promise(3) .then(x => { throw 'error' }) // Throws 'error' .catch(e => e + 4) // 'error4' .then(x => console.log(x)); // Logs 'error4' ` **Output**: error4` (Option D).javascript async function test() { console.log("Start"); const val = await Promise.resolve(5); // Pauses here console.log(val); // 5 return "End"; } console.log("Begin"); test().then(data => console.log(data)); // "End" console.log("Finish"); ` **Output Order**: Begin → Start → Finish → 5 → End` (Option B).this Binding: ``javascript const obj = { name: "Abhi", greet: function() { console.log(this.name); } }; const greet = obj.greet; greet(); // undefined (loses this context) ``vue <template v-slot:header="{ info }">{{ info.title }}</template> ``javascript actions: { async incrementAsync({ commit }) { await new Promise(resolve => setTimeout(resolve, 1000)); commit('increment'); // Updates state after 1s } } ``python @app.route('/time') @cache.cached(timeout=5) def get_time(): return str(time.time()) # Cached for 5 seconds ``python @app.task def long_task(): time.sleep(10) return "Task completed" # Runs asynchronously ``| Topic | Key Concepts | Example Questions |
|---|---|---|
| Cookies | secure, samesite, HttpOnly | Q2 |
| Async JS | Promise chaining, async/await, event loop | Q5, Q6, Q9, Q15 |
| Vue.js | Lifecycle hooks, slots, Vuex, reactivity | Q4, Q8, Q11, Q20, Q21, Q26 |
| Caching | Cache-Control, Flask-Caching, Redis | Q14, Q23 |
| Real-Time | Long polling vs. WebSockets vs. SSE | Q3, Q32 |
| Celery | Task queues, Beat, workers | Q17, Q24, Q30 |
| Web Security | CSP, XSS prevention | Q7 |
| Storage | localStorage vs. sessionStorage vs. cookies | Q12, Q18, Q28 |
| Webhooks | Event-driven callbacks | Q31 |
| Performance | Lighthouse, throttling | Q27 |