Home / Past papers / MAD2 End Term / this paper
What will be the output of the above program?```javascript let arr = [1, 2, 3]; let sum = arr.reduce((acc, val, idx, array) => acc + val, 0); console.log(sum); ```
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");
```
.In authentication using Flask-JWT-Extended, what does the payload part of the JWT stores?``` "header.payload.signature" ```
What will be the output of the above program?```javascript
const promise = new Promise((resolve, reject) => {
resolve('Success!');
reject('Error!');
});
promise.then(console.log).catch(console.log);
```
If the addItemAsync action is dispatched with the item 'React', what will be the state of items after 2 seconds?```javascript
const store = new Vuex.Store({
state: {
items: ['Angular', 'Vue'],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 500);
},
},
});
```
What happens when the user navigates to an undefined route like "/random"?```html
<div id="app">
<router-link to="/about">Go to About</router-link>
<router-view></router-view>
</div>
<script>
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '*', redirect: '/about' }
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router
});
</script>
```
```javascript console.log(typeof NaN); console.log(typeof null); console.log(NaN == null); console.log(NaN === null); ```
What will be the output of the above program on a browser's console?```javascript
class Animal {
constructor(type) {
this.type = type;
}
speak() {
console.log(`${this.type} makes a sound`);
}
getType() {
return `This is a ${this.type}`;
}
}
class Dog extends Animal {
constructor(type, breed) {
super(type);
this.breed = breed;
}
speak() {
console.log(`${this.type} ${this.breed} barks`);
}
}
const myDog = new Dog('Dog', 'Labrador');
myDog.speak();
console.log(myDog.getType());
console.log(myDog instanceof Dog);
console.log(myDog instanceof Animal);
console.log(Dog.prototype.__proto__ === Animal.prototype);
```
``` Dog Labrador barks This is a Dog true true true ```

``` Dog makes a sound This is a Dog Labrador true false true ```

``` Dog Labrador barks This is a Dog Labrador true true false ```

``` Dog Labrador barks This is a Dog false true true ```
What will be the output of the above program?```javascript
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
city: 'New York'
};
const { firstName, city, ...rest } = person;
const newPerson = { firstName, location: city, ...rest };
console.log(firstName);
console.log(rest);
console.log(newPerson);
```
```
John
{ city: 'New York', lastName: 'Doe', age: 30 }
{ firstName: 'John', location: 'New York', city: 'New York', lastName:
'Doe', age: 30 }
```
```
John
{ 'lastName': 'Doe', 'age': 30 }
{ 'firstName': 'John', 'location': 'New York', 'lastName': 'Doe', 'age': 30 }
```
```
John
{ 'lastName': 'Doe', 'age': 30 }
{ 'firstName': 'John', 'location': 'New York', 'city': 'New York', 'lastName':
'Doe', 'age': 30 }
```
```
undefined
{ firstName: 'John', city: 'New York', lastName: 'Doe', age: 30 }
{ firstName: 'John', location: 'New York' }
```
If requests for user IDs 1, 2, 1 are made within 5 minutes, what's the total response time?```python
from flask import Flask
from flask_caching import Cache
import time
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'SimpleCache'
app.config['CACHE_DEFAULT_TIMEOUT'] = 300
cache = Cache(app)
@cache.memoize(timeout=300)
def compute_data(user_id):
time.sleep(5)
return f"Data for user {user_id}"
@app.route('/api/info/<int:user_id>')
def get_info(user_id):
return compute_data(user_id)
```
What will be printed in the console when the above code is executed?```javascript
const CAPACITY = 75;
const TOTAL_PEOPLE = 213;
function allocatePeople() {
return new Promise((resolve, reject) => {
let slots = [0, 0, 0];
let remaining = TOTAL_PEOPLE;
for (let i = 0; i < slots.length; i++) {
if (remaining >= CAPACITY) {
slots[i] = CAPACITY;
remaining -= CAPACITY;
} else {
slots[i] = remaining;
remaining = 0;
}
}
reject(slots);
});
}
async function startAllocation() {
try {
const result = await allocatePeople();
console.log("Passed " + JSON.stringify(result));
} catch (error) {
console.log("Failed " + JSON.stringify(error));
}
}
startAllocation();
```
| Directive | Description | |---|---| | 1. v-if | A. Two-way data binding between input and data | | 2. v-for | B. Conditionally renders elements in the DOM | | 3. v-bind | C. Binds HTML attributes dynamically | | 4. v-model | D. Renders a list of items |
Suppose the application is running on http://127.0.0.1:8080. What will be rendered by the browser?File: index.html
```html
<div id="app"></div>
<script src="script.js"></script>
```
File: script.js
```javascript
new Vue({
el: '#app',
template: `<div>
Status: {{status}}<br>
Value: {{value}}
</div>`,
data: {
status: "Initial",
value: 10,
},
beforeCreate() {
this.status = this.status + " -> Created"
this.value = this.value + 5
},
beforeMount() {
this.status = this.status + " -> Ready"
this.value = this.value - 2
},
created() {
this.status = this.status + " -> Mounted"
this.value = this.value * 2
},
mounted() {
this.status = this.status + " -> Done"
this.value = this.value / 2
},
})
```
Three requests are made to this application: GET /api/open (no authentication headers)1. GET /api/secure (no authentication headers)2. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser')3. What will be the response status codes for these requests, respectively?```python
@app.route('/api/open')
def open_endpoint():
return jsonify({'message': 'Open access', 'status': 'success'})
@app.route('/api/secure')
@auth_required('token')
def secure_endpoint():
return jsonify({'message': 'Secure access', 'status': 'authenticated'})
@app.route('/api/superuser')
@auth_required('token')
@roles_required('superuser')
def superuser_endpoint():
return jsonify({'message': 'Superuser access', 'status': 'authorized'})
```
```javascript
function inventory() {
const item = { name: "Polycab", stats: { power: 20 } };
const ref1 = item;
const ref2 = { ...item };
const ref3 = { name: item.name, stats: { ...item.stats } };
ref1.name = "Ambrane";
ref2.stats.power = 50;
ref3.stats.power = 30;
console.log(item.name);
console.log(item.stats.power);
console.log(ref2.stats.power);
console.log(ref3.stats.power);
}
inventory();
```
```javascript
const obj = {
value: 100,
outerFunc: function () {
const innerFunc = () => {
console.log(this.value);
};
return innerFunc;
},
otherFunc: function () {
console.log(this.value);
}
};
const func1 = obj.outerFunc();
const func2 = obj.outerFunc;
const func3 = obj.otherFunc;
func1(); // #1
func2()(); // #2
func3(); // #3
```
If a user visit index.html at 10:10:10 AM, what will be logged in the console?

app.py:
```python
from flask import Flask, jsonify
from datetime import datetime
import time
app = Flask(__name__)
@app.route('/')
def home():
time.sleep(10)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
@app.route('/profile')
def profile():
time.sleep(30)
return jsonify(datetime.now().second), 200, \
{'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(debug=True)
```
index.html:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script>
function test() {
const res1 = fetch('http://127.0.0.1:5000')
const res2 = fetch('http://127.0.0.1:5000/profile')
res1
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
res2
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)
})
}
test()
</script>
</body>
</html>
```
Which of the following options correctly fills Line X and Line Y so that the application works as expected?```html
<div id="app">
<h3>Trip Essentials</h3>
<ul>
<li v-for="item in packedItems" :key="item">
{{ item }}
</li>
</ul>
<button @click="packItem('Passport')">Pack Passport</button>
</div>
<script>
const store = new Vuex.Store({
state: {
packed: []
},
mutations: {
ADD_ITEM(state, item) {
state.packed.push(item);
}
}
});
new Vue({
el: "#app",
store,
computed: {
/* Line X */
},
methods: {
packItem(item) {
/* Line Y */
}
}
});
</script>
```
```javascript
// Line X
packedItems() {
return this.store.state.packed;
}
// Line Y
this.store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.state.packed;
}
// Line Y
this.$store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.packed;
}
// Line Y
this.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems: this.$store.state.packed
// Line Y
this.$store.dispatch("ADD_ITEM", item);
```
You are developing an analytics platform using Flask and Flask-JWT-Extended. A user sends a POST request to
with:
. Then tries to access
. Which of the following statements are correct?```python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, \
jwt_required, get_jwt_identity
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "secret"
jwt = JWTManager(app)
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username")
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route("/stats")
@jwt_required()
def stats():
current_user = get_jwt_identity()
return jsonify(message=f"Welcome {current_user}")
```
/login
```json
{ "username": "Jassi" }
```
/stats
route will return "Welcome Jassi" only if a valid JWT token is sent in the Authorization header/stats
will result in an unauthorized error/stats

/stats

``` 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;
});
}
}
```
Based on the above data, answer the given subquestions.
method is modified as follows:
What will happen when the button is clicked?```
calculate()
```
```
calculate() {
this.a = this.a + 1;
}
```
will not run again``` bigNumber() ```
will run again because a dependency changed``` bigNumber() ```
defined as a computed property instead of a method?``` bigNumber() ```
Assume the Vue application is loaded at the url
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
is never called``` updated() ```
is called``` updated() ```
lifecycle hook triggered in this scenario?``` updated() ```