Home / MAD2 / Week 12 / Real questions
34 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
The developer wants to view the app in the browser locally for development. They run the following command: bash:
Which of the following best describes what happens and what the developer should have run instead?```json
{
"name": "my-vue-app",
"version": "0.1.0",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"vue": "^2.6.14"
},
"devDependencies": {
"@vue/cli-service": "^5.0.0",
"babel-eslint": "^10.1.0"
}
}
```
```
npm run build
```
launches the app on
; the developer should have run npm start to compile for production instead.``` npm run build ``` ``` localhost:8080 ```
and
do the same thing — both launch the app at 
``` npm run build ``` ``` npm run serve ``` ``` localhost:8080 ```
is correct for local development;
is only used for deploying to a server.``` npm run build ``` ``` npm run serve ```
compiles and bundles the app for production into a
folder — it does not start a local server. The developer should have run
instead.``` npm run build ``` /dist ``` npm run serve ```
would make the task run faster by giving it more CPU cores.``` .delay() ```
header.``` Authorization: Bearer <token> ```
can read the identity stored in the token.``` get_jwt_identity() ```
What will be logged in the console when this component first loads?```html
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ""
};
},
beforeCreate() {
console.log("A:", this.message);
},
created() {
console.log("B:", this.message);
this.message = "Hello from Vue!";
},
mounted() {
console.log("C:", document.querySelector("p").textContent);
}
};
</script>
```
A: "" → B: Hello from Vue! → C: Hello from Vue!

A: undefined -> B: Hello from Vue! -> C: Hello from Vue!

A: undefined → B: "" → C: Hello from Vue!

A: undefined → B: undefined → C: Hello from Vue!

A: "" -> B: "" -> C: Hello from Vue!
In another file app.js, which of the following import statements will correctly import both strikeRate and playerName ? ( Assume both files are in the same directory )```javascript
export const strikeRate = (runs, balls) => {
return (runs / balls) * 100;
};
export const playerName = "Virat Kohli";
```
```javascript import strikeRate, playerName from "./battingStats.js"; ```

```javascript
import { strikeRate, playerName } from "./battingStats.js";
```
```javascript import * as stats from "./battingStats.js"; ```

```javascript
require("./battingStats.js");
```
``` git checkout -b feature-branch ```

``` git add . ```

``` git commit -m "Initial commit" ```

``` git push origin feature-branch ```

``` git branch feature-branch && git checkout main ```

``` git push feature-branch origin ```
Which of the following statements correctly explain why the Assignments page takes time to load?```javascript
export default {
data() {
return {
assignments: []
}
},
created() {
fetch("/api/assignments")
.then(res => res.json())
.then(data => {
this.assignments = data;
});
}
}
```
Scenario
1. The component is loaded. 2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.

Scenario
1. The component is loaded. 2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.

Consider the following Vue Router configuration in a Vue 2 application:
In a Vue component, you have these navigation methods:
Consider the following Vue Router configuration in a Vue 2 application:
In a Vue component, you have these navigation methods: What URLs will be generated when the user clicks each navigation element?```javascript
const routes = [
{
path: '/',
name: 'Home',
component: HomeView
},
{
path: '/user/:id',
name: 'UserProfile',
component: UserProfile
},
{
path: '/product/:category/:id',
name: 'ProductDetail',
component: ProductDetail
}
];
```
```html
<template>
<div>
<button @click="goToUser">View User</button>
<button @click="goToProduct">View Product</button>
<router-link :to="{ name: 'Home' }">Home</router-link>
</div>
</template>
<script>
export default {
methods: {
goToUser() {
this.$router.push({ name: 'UserProfile', params: { id: 123 } });
},
goToProduct() {
this.$router.push({ name: 'ProductDetail',
params: { category: 'electronics', id: 456}
});
},
navigateOne() {
this.$router.push({ name: 'UserProfile', params: { id: 555 },
query: { tab: 'settings'}
});
},
navigateTwo() {
this.$router.replace({ name: 'Home' });
},
goBack() {
this.$router.go(-1);
}
}
}
</script>
```

The following code is using Vue 2 and Vue router 3 running on
http://127.0.0.1:5500.
Filename: index.html
```html
<body>
<div id="app"></div>
<script src="app.js" type="module"></script>
</body>
```
Filename: router.js
```javascript
const Home = { template: "<div>Home Page</div>" };
const Dashboard = {
template: "<div>Dashboard <router-view></router-view></div>",
};
const Stats = { template: "<p>Stats Component</p>" };
const Settings = { template: "<p>Settings Component</p>" };
const NotFound = { template: "<div>404 Not Found</div>" };
const router = new VueRouter({
routes: [
{ path: "/", component: Home },
{
path: "/dashboard",
component: Dashboard,
children: [
{ path: "stats", component: Stats },
{ path: "settings", component: Settings },
],
},
{ path: "**", component: NotFound },
],
});
export default router;
```
Filename: app.js
```javascript
import router from "./router.js";
new Vue({
el: "#app",
router,
template: `<div><router-view></router-view></div>`,
});
```
What will be displayed when the user visits
http://127.0.0.1:5500/#/dashboard/stats?
Consider the following Vue 2 code with Vuex 3 used via CDN, assume the Vuex
store is correctly injected into the Vue instance.
Filename: store.js
```javascript
export default store = new Vuex.Store({
state: {
score: 10,
},
mutations: {
increaseScore(state) {
state.score += 5;
},
},
actions: {
increaseScoreAsync({ commit }) {
setTimeout(() => {
commit("increaseScore");
}, 1000);
},
},
});
```
Filename: score-display.js
```javascript
export default Vue.component('score-display', {
template: `
<div>
<p>Current Score: {{ score }}</p>
<button @click="boostNow">Boost Now</button>
<button @click="boostLater">Boost After 1s</button>
</div>
`,
computed: {
score() {
// CODE 1
}
},
methods: {
boostNow() {
// CODE 2
},
boostLater() {
// CODE 3
}
}
});
```
Which of the following correctly fills in CODE 1, CODE 2, and CODE 3 for the score to be
displayed and for the **boostNow()** and **boostLater()** methods to work correctly?
CODE 1: ``` return this.$store.state.score; ```

CODE 2:
```
this.$store.commit('increaseScore');
```
``` CODE 2: this.increaseScore() ; ```

CODE 3:
```
this.$store.dispatch('increaseScoreAsync');
```
CODE 3: ``` this.$store.increaseScoreAsync(); ```

Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="increment">Increment</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['increment']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Increment" button 3 times?
Consider the following JavaScript code.
```javascript
export default {
data() {
return {
loginToken: '',
};
},
mounted() {
this.loginToken = sessionStorage.getItem('authToken') || '';
},
methods: {
updateToken(newToken) {
this.loginToken = newToken;
sessionStorage.setItem('authToken', newToken);
}
}
};
```
What will happen when a user calls the updateToken method with a new value and then refreshes the page?
The new token will be lost, and the "loginToken" data property will be reset to an empty string.

The new token will be preserved in session storage, and the "LoginToken" data property will be populated with the stored value on page refresh.

The method will throw an error because sessionStorage cannot be modified directly.

The "loginToken" data property will be updated, but the session storage will remain unchanged.

Consider the below flask SSE implementation.
```python
from flask import Flask, Response
import time
app = Flask(__name__)
def event_stream():
for i in range(5):
yield f"data: Message {i}"
time.sleep(1)
@app.route('/events')
def sse():
return Response(event_stream(), mimetype="text/event-stream")
```
And the Vue.js frontend:
```html
<template>
<div>
<p v-for="msg in messages" :key="msg">{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return { messages: [] };
},
mounted() {
const eventSource = new EventSource("http://localhost:5000/events");
eventSource.onmessage = (event) => {
this.messages.push(event.data);
};
},
};
</script>
```
What will happen when a user opens this page?
Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 5,
},
mutations: {
decrement(state) {
state.count--;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="decrement">Decrement</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['decrement']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Decrement" button 4 times?
Consider the below Vue.js application.
```html
<template>
<div>
<button @click="goToPage('Home')">Go to Home</button>
<button @click="goToPage('About')">Go to About</button>
<button @click="goToPage('Contact')">Go to Contact</button>
<div v-if="visitedPages.length">
<h3>Visited Pages:</h3>
<ul>
<li v-for="(page, index) in visitedPages" :key="index">{{ page }}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
visitedPages: []
};
},
mounted() {
const storedPages = JSON.parse(sessionStorage.getItem('visitedPages')) || [];
this.visitedPages = storedPages;
},
methods: {
goToPage(page) {
this.visitedPages.push(page);
sessionStorage.setItem('visitedPages',
JSON.stringify(this.visitedPages));
this.$router.push(`/${page.toLowerCase()}`);
}
}
};
</script>
```
Consider the below Vue.js application.
```html
<template>
<div>
<input v-model="name" placeholder="Enter name">
<input v-model="email" placeholder="Enter email">
<button @click="submitForm">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
email: ''
};
},
mounted() {
if (localStorage.getItem('formData')) {
const savedData = JSON.parse(localStorage.getItem('formData'));
this.name = savedData.name;
this.email = savedData.email;
}
},
watch: {
name(newVal) {
localStorage.setItem('formData', JSON.stringify({ name: newVal, email: localStorage.email }));
},
email(newVal) {
localStorage.setItem('formData', JSON.stringify({ name: localStorage.name, email: newVal }));
}
},
methods: {
submitForm() {
localStorage.removeItem('formData');
this.name = '';
this.email = '';
}
}
};
</script>
```
What will happen if the user submits the form and reloads the page?
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 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?
Consider the below Vue component.
```html
<template>
<div>
<p>{{ message }}</p>
<button @click="updateMessage">Change Message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello'
};
},
methods: {
updateMessage() {
this.message = this.message === 'Hello' ? 'World' : 'Hello';
}
}
};
</script>
```
What will be displayed in the `<p>` element, after the button with text "Change Message" is clicked?
Consider the below Vue component.
```html
<template>
<div>
<button @click="setDarkMode">Dark Mode</button>
<button @click="setLightMode">Light Mode</button>
</div>
</template>
<script>
export default {
data() {
return {
theme: localStorage.getItem('theme') || 'light'
};
},
methods: {
setDarkMode() {
this.theme = 'dark';
localStorage.setItem('theme', 'dark');
},
setLightMode() {
this.theme = 'light';
localStorage.setItem('theme', 'light');
}
}
};
</script>
```
Which of the following statement(s) is/are correct about the behavior of the above component?
Consider the below Vue component.
```html
<template>
<div>
<p>{{ computedMessage }}</p>
<button @click="update">Update</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Initial'
};
},
computed: {
computedMessage() {
return this.message + ' - Computed';
}
},
methods: {
update() {
this.message = 'Updated';
}
}
};
</script>
```
What will be displayed in the `<p>` element, after the button with text "Update" is clicked?
Consider the below Vue component.
```html
<template>
<div>
<ul>
<li v-for="item in filteredItems" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
],
filterActive: true,
};
},
computed: {
filteredItems() {
return this.filterActive
? this.items.filter((item) => item.id !== 2)
: this.items;
},
},
};
</script>
```
What will be displayed in the `<ul>` when filterActive is true?
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

Suppose you are organizing a felicitation program for the students with exemplary performance in the BS program. You have the scorecard of all the students. The administration has decided to shortlist the students based on the following 2 criteria:
1. The student must have an "S" in their MAD II project
2. The overall CGPA of the student must be greater than 8
Fill in the `code1` & `code2`, which can be used in Vuex Store to update the "awardees" state variable with the objects of those students who satisfy the above-mentioned criteria. The objects to be inserted in the "awardees" state variable must only have the student ID and a random token generated in the "send_task" action function.
```javascript
const store = new Vuex.Store({
state: {
bs_program: [{
student_id: 'stu1001',
mad2_grade: 'S',
cgpa: 8.35
}, {
student_id: 'stu1002',
mad2_grade: 'A',
cgpa: 8.78
}, {
student_id: 'stu1003',
mad2_grade: 'S',
cgpa: 9.1
}, {
student_id: 'stu1004',
mad2_grade: 'S',
cgpa: 7.44
}, ],
awardees: []
},
mutations: {
update_final(state, payload) {
for (student of state.bs_program)
code2
}
},
actions: {
send_task: function(context) {
const token = get_token(); // generates a random token
code1
}
}
})
```
```javascript
code1: this.$store.commit("update_final", {"min" : 8, "token" : token});
code2: if (student.mad2_grade != "S" && student.cgpa > 8) {
const obj = {};
obj.student_id = student.student_id;
obj.token = payload.token
state.awardees.push(student)
}
```
```
code1: context.commit("update_final", 8, token);
code2: if (mad2_grade != "S" && cgpa > 8){
awardees.push(company)
}
```
```javascript
code1: this.$store.commit("update_final", 8, token);
code2: if (mad2_grade != "S" && cgpa > 8){
awardees.push(company)
}
```
```
code1: context.commit("update_final", {"min" : 8, "token" : token});
code2: if (student.mad2_grade != "S" && student.cgpa > 8) {
const obj = {};
obj.student_id = student.student_id;
obj.token = payload.token
state.awardees.push(student)
}
```
Consider the below Vue component template and script definitions that use Vue router.
Vue component template
```html
<template>
<div>
<h1>{{ pageAction }}</h1>
<router-link to="/login" v-if="showLogin">Login</router-link>
<router-link to="/register" v-if="showRegister">Register</router-link>
<router-view></router-view>
</div>
</template>
```
Filename: script.js
```javascript
<script>
export default {
name: 'App',
data() {
return {
pageAction: 'Login or Signup',
showLogin: true,
showRegister: false,
};
},
watch: {
'$route.path'() {
if (this.$route.path === '/login') {
this.showRegister = true;
this.showLogin = false;
this.pageAction = 'Login Page';
} else if (this.$route.path === '/register') {
this.showRegister = false;
this.showLogin = true;
this.pageAction = 'Register Page';
} else {
this.pageAction = 'Login or Signup';
}
},
},
};
</script>
```
Assuming that the corresponding routes are properly configured, what does this component structure accomplish?
Consider the below Vue component template and script definitions that use Vue router. Assuming that the corresponding routes are properly configured, what does this component structure accomplish?Template:
```html
<template>
<div>
<h1>{{ pageTitle }}</h1>
<router-link to="/home" v-if="showHomeLink">Home</router-link>
<router-link to="/about" v-if="showAboutLink">About</router-link>
<router-view></router-view>
</div>
</template>
```
Script:
```html
<script>
export default {
name: 'App',
data() {
return {
pageTitle: 'Vue Router Demo',
showHomeLink: true,
showAboutLink: false,
};
},
watch: {
'$route.path'() {
if (this.$route.path === '/home') {
this.showAboutLink = true;
this.showHomeLink = false;
this.pageTitle = 'Home Page';
} else if (this.$route.path === '/about') {
this.showAboutLink = false;
this.showHomeLink = true;
this.pageTitle = 'About Page';
} else {
this.pageTitle = 'Vue Router Demo';
}
},
},
};
</script>
```
It displays a web page with a heading title "Vue Router Demo" and two navigation links to "Home" and "About."

It dynamically updates the heading title based on the route and conditionally shows navigation links to "Home" and "About."

It has a bug and will throw a runtime error.

The heading title is populated with the value "Vue Router Demo" when the user opens the app for the first time.
Consider the below Vue application with markup file “index.html” and javascript file “app.js”. Suppose the application is deployed under a subdirectory named “/myapp/” of a domain named “https://appdev2-may2023.com”, and you want to navigate to a page that renders “Hello Second Component !!”. What should be the correct URL to get the desired output?index.html:
```html
<div id = "app">
<router-view></router-view>
</div>
<script src = "app.js"></script>
```
app.js:
```javascript
const First = Vue.component("first", {
template: `<div>Hello First Component !!</div>`
})
const Second = Vue.component("second", {
template: `<div>Hello Second Component !!</div>`
})
const router = new VueRouter({
base: '/myapp/',
routes: [
{
path: "/endpoint1",
component: First,
},
{
path: "/endpoint2",
component: Second,
},
]
});
const app = new Vue({
el: '#app',
router,
data: {},
methods: {}
});
```
https://appdev2-may2023.com/mvapp/#/

https://appdev2-may2023.com/myapp/#/endpoint1

https://appdev2-may-2023.com/myapp/#/endpoint2

https://appdev2-may2023.com/#/endpoint1
Consider the given 2 implementations.
Consider the given 2 implementations. Suppose there are currently 1000 users in the database, and the application is supposed to generate 1000 HTML reports. Which of the following statement(s) is/are false (assuming there are more than 1 worker available in the celery system)?Approach 1:
driver code:
```python
import tasks
def generate_reports():
users = User.query.all()
for user in users:
tasks.job_report.delay(user)
```
celery job:
```python
@celery.task
def job_report(user):
"""
This function fetches the statistics of a given user and generates an
HTML report
"""
```
Approach 2:
driver code:
```python
import tasks
def generate_reports():
tasks.job_report.delay()
```
celery job:
```python
@celery.task
def job_report():
users = User.query.all()
for user in users:
...
# This loop fetches the statistics of a given user and generates an HTML
# report
...
```
Suppose an endpoint in your flask application triggers a celery task, which generates a CSV file named “data.csv” and saves it in the static folder of a flask application. The file generator takes anywhere between 20 and 40 seconds to generate and save the CSV file. The below fetch call is used to get the file generated by the above explained celery task. Which of the following is the most efficient way to make the above fetch call so that it doesn’t fail and return the desired response? ```javascript
fetch("/static/data.csv").then(response => response.blob())
.then(data => {
// does something with the response data
})
```

Suppose you own a company where you want to hire candidates for an upcoming project on a deputation basis, and you have received a lot of applications. On discussing with your team members, you decided to shortlist the candidates based on the following 2 criteria:
1. The candidate must have at least 3 years of experience
2. The candidate's age must be less than 30 years
Fill in the `code1` & `code2`, which can be used in Vuex Store to update the "shortlisted" state variable with the objects of those candidates who satisfy the above-mentioned criteria. Also, predict the length of the state variable "shortlisted", after the mutation has completed its execution.
```javascript
const store = new Vuex.Store({
state : {
candidates : [
{
name : 'sample1',
age : 28,
experience : 2.5
},
{
name : 'sample2',
age : 35,
experience : 3.5
},
{
name : 'sample3',
age : 32,
experience : 3
},
{
name : 'sample4',
age : 38,
experience : 2
},
],
shortlisted : []
},
mutations : {
update_final(state, minimum) {
for (candidate of state.candidates)
code2
},
},
actions : {
send_task : function (context) {
code1
}
}
})
```
```
code1: this.$store.commit("update_final", 2);
code2: if (candidate.experience >= minimum && candidate.age < 30)
state.shortlisted.push(company)
Length: 3
```
```
code1: context.commit("update_final", 2);
code2: if (experience >= minimum && candidate.age < 30)
state.shortlisted.push(company)
```
Length: 2
```javascript
code1: this.$store.commit("update_final", 3);
code2: if (experience >= minimum && candidate.age < 30)
state.shortlisted.push(company)
```
Length: 3
```
code1: context.commit("update_final", 3);
code2: if (candidate.experience >= minimum && candidate.age < 30)
state.shortlisted.push(company)
```
Length: 2