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, principles, and equations for the "Diploma Level: Modern Application Development II" exam, along with Mermaid knowledge graphs to visualize relationships.
Cookie Attributes:
secure=True: Ensures cookies are sent only over HTTPS.samesite='Strict'|'Lax'|'None': Restricts cross-site requests (CSRF protection).
Strict: Cookie sent only for same-site requests.Lax: Default; allows top-level navigations.None: Allows cross-site but requires secure=True.httponly: Prevents JavaScript access (mitigates XSS).Content Security Policy (CSP):
default-src 'self': Restricts resource loading to the same origin.<script src="https://otherurl.com/code.js">).Cache-Control Headers:
no-store: Prevents caching entirely.ETag: Validates cache freshness.// Secure cookie example
response.set_cookie('session_id', 'abc123', secure=True, samesite='Strict');
Content-Security-Policy: default-src 'self';
Cache-Control: no-store
Event Loop:
Promises & Async/Await:
.then() chains handle resolved values..catch() handles rejections.async/await: Syntactic sugar for promises; await pauses execution until the promise resolves..catch().// Promise chaining
Promise.resolve(1)
.then(x => x + 1)
.then(x => { throw 'error' })
.catch(e => e + 4) // Output: "error4"
.then(x => console.log(x));
// Async/await
async function test() {
console.log("Start");
const val = await Promise.resolve(5); // Pauses here
console.log(val); // "5"
return "End";
}
test().then(data => console.log(data)); // "End"
Output Order (Event Loop):
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 → beforeUpdate → updated → beforeDestroy → destroyed.Reactivity:
data() properties are reactive.computed properties cache results.watch observes changes (supports deep: true for nested objects).Slots & Scoped Slots:
<slot name="header" :info="data"></slot><template v-slot:header="slotProps">.Vue Router:
/profile/:userId → Access via this.$route.params.userId.*) for 404 routes.Vuex:
commit mutations).<!-- Scoped slot usage -->
<template v-slot:header="slotProps">
{{ slotProps.info.title }}
</template>
<!-- Vue Router dynamic param -->
this.$route.params.id // Access :id
// Vuex action
actions: {
async incrementAsync({ commit }) {
await new Promise(resolve => setTimeout(resolve, 1000));
commit('increment'); // Mutates state
}
}
localStorage| Persists | Per-origin | ~5MB | Sync | | sessionStorage| Session-only | Per-tab | ~5MB | Sync | | Cookies | Configurable | Per-domain | ~4KB | Auto-sent with HTTP | | IndexedDB | Persists | Per-origin | ~50MB+ | Async |Caching Headers:
Cache-Control: max-age=3600 (cache for 1 hour).ETag: Validator for conditional requests.// localStorage usage
localStorage.setItem('cart', JSON.stringify([{ id: 1, name: 'Laptop' }]));
const cart = JSON.parse(localStorage.getItem('cart'));
WebSockets:
ws:// or wss://.Server-Sent Events (SSE):
EventSource API.Long Polling:
| Feature | WebSockets | SSE | Long Polling |
|---|---|---|---|
| Direction | Bi-directional | Server → Client | Client → Server |
| Protocol | WS/WSS | HTTP | HTTP |
| Persistence | Yes | Yes | No (per request) |
| Use Case | Chat, gaming | Live updates | Legacy real-time |
Celery:
Asynchronous Workflow:
### Celery periodic task (every 10 minutes)
from celery.schedules import crontab
app.conf.beat_schedule = {
'send-email-every-10-minutes': {
'task': 'tasks.send_email',
'schedule': 600.0, # 10 minutes in seconds
},
}
Lighthouse:
Caching Strategies:
Vue Error Handling:
errorCaptured lifecycle hook.Vue.config.errorHandler.JavaScript:
try/catch for synchronous errors..catch() for promises.window.onerror for global uncaught errors.secure, samesite, CSP).async/await, Event Loop).Cache-Control, ETag).localStorage, sessionStorage, IndexedDB).| Topic | Code Snippet |
|---|---|
| Secure Cookie | response.set_cookie(..., secure=True, samesite='Strict') |
| Promise Chaining | .then().catch() |
| Vue Scoped Slot | <template v-slot:header="slotProps"> |
| Celery Task | @app.task; celery -A tasks worker --beat |
| localStorage | JSON.parse(localStorage.getItem('key')) |
| CSP Header | Content-Security-Policy: default-src 'self' |
| Vuex Action | async increment({ commit }) { await delay(); commit('mutate') } |
this Binding: Arrow functions vs. regular functions in Vue/JS.Vue.set or spread operator).Cache-Control is misconfigured.