├── mgit ├── sample.md ├── functions.pdf └── floor_ceil_assignment ├── CMR FDP ├── readme.md ├── ai_agents.md ├── differences.md └── rag.md ├── assignments ├── nodejs │ ├── files │ │ ├── b.txt │ │ ├── a.txt │ │ └── c.html │ ├── solutions │ │ ├── todos.json │ │ ├── fileServer.solution.js │ │ ├── todoServer.solution.simple.js │ │ ├── todoServer.solution.file.js │ │ ├── index.html │ │ └── todoServer.solution.js │ ├── .gitignore │ ├── package.json │ ├── fileServer.js │ ├── readme.md │ ├── authenticationServer.js │ ├── todoServer.js │ └── tests │ │ ├── authenticationServer.test.js │ │ ├── todoServer.test.js │ │ └── fileServer.test.js ├── react │ ├── solutions │ │ ├── courses.json │ │ ├── users.json │ │ └── admins.json │ ├── 01-reconciler │ │ ├── dom-advance.test.js │ │ ├── .gitignore │ │ ├── jest.config.js │ │ ├── dom-simple.test.js │ │ ├── solution │ │ │ └── script.solution.js │ │ ├── index.html │ │ ├── README.md │ │ ├── package.json │ │ ├── script-ugly.js │ │ ├── script-less-ugly.js │ │ ├── script-vdom.js │ │ ├── script-vdom-batch.js │ │ └── script-vdom-comparision.js │ ├── package.json │ ├── README.md │ ├── 02-course-app-easy-2 │ │ ├── package.json │ │ ├── index.js │ │ └── README.md │ ├── 02-course-app-easy │ │ ├── package.json │ │ ├── index.js │ │ └── README.md │ ├── 03-course-app-medium │ │ ├── package.json │ │ ├── index.js │ │ └── README.md │ └── 04-course-app-hard │ │ ├── package.json │ │ ├── index.js │ │ └── README.md ├── full_stack │ ├── 01-easy-todo-app │ │ ├── src │ │ │ ├── App.css │ │ │ ├── index.css │ │ │ ├── main.jsx │ │ │ ├── App.jsx │ │ │ └── assets │ │ │ │ └── react.svg │ │ ├── vite.config.js │ │ ├── .gitignore │ │ ├── index.html │ │ ├── README.md │ │ ├── .eslintrc.cjs │ │ ├── package.json │ │ └── public │ │ │ └── vite.svg │ ├── 02-medium-course-selling-app-admin-dashboard │ │ ├── src │ │ │ ├── App.css │ │ │ ├── index.css │ │ │ ├── main.jsx │ │ │ ├── components │ │ │ │ ├── Register.jsx │ │ │ │ ├── ShowCourses.jsx │ │ │ │ ├── CreateCourse.jsx │ │ │ │ ├── Login.jsx │ │ │ │ └── Landing.jsx │ │ │ ├── App.jsx │ │ │ └── assets │ │ │ │ └── react.svg │ │ ├── vite.config.js │ │ ├── .gitignore │ │ ├── index.html │ │ ├── .eslintrc.cjs │ │ ├── package.json │ │ ├── README.md │ │ └── public │ │ │ └── vite.svg │ ├── 04-hard-use-mui │ │ └── README.md │ └── 03-hard-course-selling-app-user-side │ │ └── README.md ├── fs_typescript │ ├── assignment-2 │ │ ├── src │ │ │ ├── App.css │ │ │ ├── store │ │ │ │ └── authState.js │ │ │ ├── main.jsx │ │ │ ├── index.css │ │ │ ├── Components │ │ │ │ ├── Login.jsx │ │ │ │ ├── Signup.jsx │ │ │ │ └── TodoList.jsx │ │ │ ├── App.jsx │ │ │ └── assets │ │ │ │ └── react.svg │ │ ├── vite.config.js │ │ ├── .gitignore │ │ ├── index.html │ │ ├── .eslintrc.cjs │ │ ├── package.json │ │ ├── public │ │ │ └── vite.svg │ │ └── README.md │ ├── assignment-1 │ │ ├── .gitignore │ │ ├── package.json │ │ ├── db │ │ │ └── index.js │ │ ├── index.js │ │ ├── middleware │ │ │ └── index.js │ │ ├── routes │ │ │ ├── todo.js │ │ │ └── auth.js │ │ └── README.md │ └── README.md ├── async-js │ ├── easy │ │ ├── 4-write-to-file.md │ │ ├── 1-counter.md │ │ ├── 3-read-from-file.md │ │ └── 2-counter.md │ ├── hard (promises) │ │ ├── 1-promisify-setTimeout.js │ │ ├── 2-sleep-completely.js │ │ ├── 3-promise-all.js │ │ └── 4-promise-chain.js │ ├── medium │ │ ├── 2-clock.md │ │ └── 1-file-cleaner.md │ └── README.md └── js │ ├── medium │ ├── times.js │ └── palindrome.js │ ├── hard │ ├── todo-list.js │ └── calculator.js │ ├── easy │ ├── expenditure-analysis.js │ └── anagram.js │ ├── README.md │ ├── package.json │ └── tests │ ├── anagram.test.js │ ├── palindrome.test.js │ ├── todo-list.test.js │ ├── expenditure-analysis.test.js │ └── calculator.test.js ├── attendance_app ├── data.json ├── students.json └── server.js ├── backend ├── .gitignore ├── prompts.md ├── Basic_FSD │ ├── database.json │ ├── package.json │ ├── index.html │ ├── styles.css │ ├── server.js │ └── script.js └── command_notes.md ├── groq_code ├── cognizant.md ├── dsa_resource _ elevatebox.pdf ├── ml_projects └── Heart failure detection through ecg analysis using CNN │ ├── README.md │ └── ECG Testing_GUI.py ├── AppointmentApp ├── style.css ├── index.html ├── script.js └── server.js ├── visaa_oa ├── assignments.md ├── input.md ├── trees.md ├── sample_questions.md └── strings2.md ├── nodejs └── file.js ├── anurag_hackathon └── final_prompt.md ├── MRU_FDP ├── ai_agents.md ├── differences.md └── rag.md ├── crewai_experiments └── README.md ├── mongodb └── server.js ├── nnrg_workshop └── index.html └── Finishing School └── fullstack_app.md /mgit/sample.md: -------------------------------------------------------------------------------- 1 | xys 2 | -------------------------------------------------------------------------------- /CMR FDP/readme.md: -------------------------------------------------------------------------------- 1 | - test 2 | -------------------------------------------------------------------------------- /assignments/nodejs/files/b.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /attendance_app/data.json: -------------------------------------------------------------------------------- 1 | [ 2 | 3 | ] -------------------------------------------------------------------------------- /backend/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/todos.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/react/solutions/courses.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /assignments/react/solutions/users.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /assignments/nodejs/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /assignments/nodejs/files/a.txt: -------------------------------------------------------------------------------- 1 | hello from a.txt -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/src/App.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/src/index.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/dom-advance.test.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/App.css: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | .idea/ 3 | node_modules 4 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/App.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/index.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mgit/functions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elevatebox/opensource/HEAD/mgit/functions.pdf -------------------------------------------------------------------------------- /backend/prompts.md: -------------------------------------------------------------------------------- 1 | Chat : https://chatgpt.com/share/67210311-5120-8001-bba4-170c094550a4 2 | 3 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testEnvironment: 'jsdom', 3 | }; 4 | 5 | -------------------------------------------------------------------------------- /groq_code: -------------------------------------------------------------------------------- 1 | https://colab.research.google.com/drive/10AqZ04Ca0UvXmDKdARnJnnyBIdjKW8ng#scrollTo=VJr52wYeA-dx 2 | -------------------------------------------------------------------------------- /cognizant.md: -------------------------------------------------------------------------------- 1 | ** 2 | https://docs.google.com/document/d/1Yh33rnVy65Hiqxsi0O8LZxsH9OqDbxBSESy5R6L5nGY/edit?tab=t.0** 3 | -------------------------------------------------------------------------------- /dsa_resource _ elevatebox.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/elevatebox/opensource/HEAD/dsa_resource _ elevatebox.pdf -------------------------------------------------------------------------------- /assignments/react/01-reconciler/dom-simple.test.js: -------------------------------------------------------------------------------- 1 | { 2 | "status":200, 3 | "data":{ 4 | "queue_length":"5", 5 | } 6 | } -------------------------------------------------------------------------------- /assignments/react/01-reconciler/solution/script.solution.js: -------------------------------------------------------------------------------- 1 | 2 | // What are u looking for? 3 | // You'll get it on Friday you lazy porson 4 | -------------------------------------------------------------------------------- /assignments/react/solutions/admins.json: -------------------------------------------------------------------------------- 1 | [{"username":"harkirat1@gmail.com","password":"123456"},{"username":"harkirat1@gmail1.com","password":"123456"}] -------------------------------------------------------------------------------- /assignments/react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "express": "^4.18.2", 4 | "jsonwebtoken": "^9.0.0", 5 | "mongoose": "^7.3.1" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /assignments/nodejs/files/c.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | C web page 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /backend/Basic_FSD/database.json: -------------------------------------------------------------------------------- 1 | [{"id":1730216146598,"text":"JBaodfpo[ejrn "},{"id":1730216151818,"text":" ojadpgifean"},{"id":1730216337313,"text":"DQW"},{"id":1730216340360,"text":"wlkae[rwap]ty"}] -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/store/authState.js: -------------------------------------------------------------------------------- 1 | import { atom } from 'recoil'; 2 | 3 | export const authState = atom({ 4 | key: 'authState', 5 | default: { token: null, username: null }, 6 | }); -------------------------------------------------------------------------------- /assignments/async-js/easy/4-write-to-file.md: -------------------------------------------------------------------------------- 1 | ## Write to a file 2 | Using the fs library again, try to write to the contents of a file. 3 | You can use the fs library to as a black box, the goal is to understand async tasks. -------------------------------------------------------------------------------- /assignments/async-js/hard (promises)/1-promisify-setTimeout.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that returns a promise that resolves after n seconds have passed, where n is passed as an argument to the function. 3 | */ 4 | 5 | function wait(n) { 6 | } -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /assignments/react/README.md: -------------------------------------------------------------------------------- 1 | This week we wrapped up most of backend. 2 | We'll also be posting about DBs and auth in a video so the assignment has questions from that as well. 3 | Feel free to do them right now or after the video is posted. 4 | -------------------------------------------------------------------------------- /assignments/async-js/easy/1-counter.md: -------------------------------------------------------------------------------- 1 | ## Create a counter in JavaScript 2 | 3 | We have already covered this in the second lesson, but as an easy recap try to code a counter in Javascript 4 | It should go up as time goes by in intervals of 1 second -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import react from '@vitejs/plugin-react' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [react()], 7 | }) 8 | -------------------------------------------------------------------------------- /assignments/async-js/hard (promises)/2-sleep-completely.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a function that halts the JS thread (make it busy wait) for a given number of milliseconds. 3 | * During this time the thread should not be able to do anything else. 4 | */ 5 | 6 | function sleep (seconds) { 7 | 8 | } -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | import './index.css' 5 | 6 | ReactDOM.createRoot(document.getElementById('root')).render( 7 | 8 | 9 | , 10 | ) 11 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | import './index.css' 5 | 6 | ReactDOM.createRoot(document.getElementById('root')).render( 7 | 8 | 9 | , 10 | ) 11 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | replit 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /assignments/async-js/medium/2-clock.md: -------------------------------------------------------------------------------- 1 | Using `1-counter.md` or `2-counter.md` from the easy section, can you create a 2 | clock that shows you the current machine time? 3 | 4 | Can you make it so that it updates every second, and shows time in the following formats - 5 | 6 | - HH:MM::SS (Eg. 13:45:23) 7 | 8 | - HH:MM::SS AM/PM (Eg 01:45:23 PM) 9 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/README.md: -------------------------------------------------------------------------------- 1 | You have the janky version of a reconciler. It's not very good. It's not very fast. But it's a start. 2 | In the 3.2 video we discuss how we can make it faster. 3 | Can you figure out how to make it faster? 4 | By faster we mean minimizing the number of DOM interactions. 5 | Feel free to look at the tests for a hint 6 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/main.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import ReactDOM from 'react-dom/client' 3 | import App from './App.jsx' 4 | import './index.css' 5 | 6 | ReactDOM.createRoot(document.getElementById('root')).render( 7 | 8 | 9 | , 10 | ) 11 | -------------------------------------------------------------------------------- /assignments/async-js/medium/1-file-cleaner.md: -------------------------------------------------------------------------------- 1 | ## File cleaner 2 | Read a file, remove all the extra spaces and write it back to the same file. 3 | 4 | For example, if the file input was 5 | ``` 6 | hello world my name is raman 7 | ``` 8 | 9 | After the program runs, the output should be 10 | 11 | ``` 12 | hello world my name is raman 13 | ``` -------------------------------------------------------------------------------- /assignments/js/medium/times.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function that calculates the time (in seconds) it takes for the JS code to calculate sum from 1 to n, given n as the input. 3 | Try running it for 4 | 1. Sum from 1-100 5 | 2. Sum from 1-100000 6 | 3. Sum from 1-1000000000 7 | Hint - use Date class exposed in JS 8 | */ 9 | 10 | function calculateTime(n) { 11 | return 0.01; 12 | } -------------------------------------------------------------------------------- /assignments/full_stack/04-hard-use-mui/README.md: -------------------------------------------------------------------------------- 1 | ### Using mui 2 | Go through the docs at https://mui.com 3 | 4 | This is a library that has a lot of pre-defined components that you can use 5 | This is the power of components, you can use them to build your own components. 6 | Try replacing buttons and input boxes with mui's implementation and see how pretty your app looks with 0 effort. 7 | -------------------------------------------------------------------------------- /ml_projects/Heart failure detection through ecg analysis using CNN/README.md: -------------------------------------------------------------------------------- 1 | - First open Arrythmia_AI in Google Colab 2 | - Then run the code 3 | - The model will be saved as ecg_vgg19_model.h5 4 | - Then run the code in the next notebook 5 | - The model will be loaded and used to predict Arrythmia 6 | - The model will be saved as Arrythmia_AI_model.h5 7 | - use ecg testing gui to test the model -------------------------------------------------------------------------------- /AppointmentApp/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, sans-serif; 3 | margin: 0; 4 | padding: 0; 5 | } 6 | 7 | #app { 8 | display: flex; 9 | gap: 20px; 10 | } 11 | 12 | #appointments-view, #booking-view { 13 | width: 50%; 14 | } 15 | 16 | .completed { 17 | color: green; 18 | } 19 | 20 | .upcoming { 21 | color: orange; 22 | } 23 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /assignments/async-js/easy/3-read-from-file.md: -------------------------------------------------------------------------------- 1 | ## Reading the contents of a file 2 | 3 | Write code to read contents of a file and print it to the console. 4 | You can use the fs library to as a black box, the goal is to understand async tasks. 5 | Try to do an expensive operation below the file read and see how it affects the output. 6 | Make the expensive operation more and more expensive and see how it affects the output. 7 | 8 | -------------------------------------------------------------------------------- /backend/Basic_FSD/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eie_vnr", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "body-parser": "^1.20.3", 14 | "cors": "^2.8.5", 15 | "express": "^4.21.1" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/index.css: -------------------------------------------------------------------------------- 1 | :root { 2 | font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; 3 | line-height: 1.5; 4 | font-weight: 400; 5 | 6 | color-scheme: light dark; 7 | color: rgba(255, 255, 255, 0.87); 8 | background-color: #242424; 9 | 10 | font-synthesis: none; 11 | text-rendering: optimizeLegibility; 12 | -webkit-font-smoothing: antialiased; 13 | -moz-osx-font-smoothing: grayscale; 14 | -webkit-text-size-adjust: 100%; 15 | } 16 | -------------------------------------------------------------------------------- /assignments/js/medium/palindrome.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement a function `isPalindrome` which takes a string as argument and returns true/false as its result. 3 | Note: the input string is case-insensitive which means 'Nan' is a palindrom as 'N' and 'n' are considered case-insensitive. 4 | 5 | Once you've implemented the logic, test your code by running 6 | - `npm run test-palindrome` 7 | */ 8 | 9 | function isPalindrome(str) { 10 | return true; 11 | } 12 | 13 | module.exports = isPalindrome; 14 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "assignment-1", 3 | "version": "1.0.0", 4 | "description": "Convert this from JS to typescript.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "cors": "^2.8.5", 14 | "express": "^4.18.2", 15 | "jsonwebtoken": "^9.0.1", 16 | "mongoose": "^7.4.1" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/README.md: -------------------------------------------------------------------------------- 1 | 2 | ### Assignment 1 3 | Create the frontend for a TODO app. 4 | You should be able to 5 | 1. Create a new TODO 6 | 2. List all TODOs 7 | 3. Delete a TODO 8 | 9 | The backend we've already written in 10 | /week2/02-nodejs/solutions/todoServer.solution.js 11 | 12 | Make sure you 13 | 1. Add app.listen so it is running on 3000 14 | 2. Use cors 15 | 16 | Good to do 17 | 1. Break things down into components 18 | 2. Use a library like axios to make the requests 19 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/db/index.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | const userSchema = new mongoose.Schema({ 4 | username: String, 5 | password: String, 6 | }); 7 | 8 | const todoSchema = new mongoose.Schema({ 9 | title: String, 10 | description: String, 11 | done: Boolean, 12 | userId: String, 13 | }); 14 | 15 | const User = mongoose.model('User', userSchema); 16 | const Todo = mongoose.model('Todo', todoSchema); 17 | 18 | module.exports = { 19 | User, 20 | Todo 21 | } -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { browser: true, es2020: true }, 3 | extends: [ 4 | 'eslint:recommended', 5 | 'plugin:react/recommended', 6 | 'plugin:react/jsx-runtime', 7 | 'plugin:react-hooks/recommended', 8 | ], 9 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 10 | settings: { react: { version: '18.2' } }, 11 | plugins: ['react-refresh'], 12 | rules: { 13 | 'react-refresh/only-export-components': 'warn', 14 | }, 15 | } 16 | -------------------------------------------------------------------------------- /attendance_app/students.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": 1735898499107, 4 | "name": "student1", 5 | "rollNumber": "21Rh46t632", 6 | "attendance": 0 7 | }, 8 | { 9 | "id": 1735898521759, 10 | "name": "student2", 11 | "rollNumber": "21Rh46t645" 12 | }, 13 | { 14 | "id": 1735898539303, 15 | "name": "student3", 16 | "rollNumber": "21Rh46t656", 17 | "attendance": 0 18 | }, 19 | { 20 | "id": 1735898551964, 21 | "name": "student4", 22 | "rollNumber": "21Rh46t786" 23 | } 24 | ] -------------------------------------------------------------------------------- /assignments/async-js/hard (promises)/3-promise-all.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Write 3 different functions that return promises that resolve after 1, 2, and 3 seconds respectively. 3 | * Write a function that uses the 3 functions to wait for all 3 promises to resolve using Promise.all, 4 | * Print how long it took for all 3 promises to resolve. 5 | */ 6 | 7 | 8 | function waitOneSecond() { 9 | 10 | } 11 | 12 | function waitTwoSecond() { 13 | 14 | } 15 | 16 | function waitThreeSecond() { 17 | 18 | } 19 | 20 | function calculateTime() { 21 | 22 | } -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { browser: true, es2020: true }, 3 | extends: [ 4 | 'eslint:recommended', 5 | 'plugin:react/recommended', 6 | 'plugin:react/jsx-runtime', 7 | 'plugin:react-hooks/recommended', 8 | ], 9 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 10 | settings: { react: { version: '18.2' } }, 11 | plugins: ['react-refresh'], 12 | rules: { 13 | 'react-refresh/only-export-components': 'warn', 14 | }, 15 | } 16 | -------------------------------------------------------------------------------- /assignments/js/hard/todo-list.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement a class `Todo` having below methods 3 | - add(todo): adds todo to list of todos 4 | - remove(indexOfTodo): remove todo from list of todos 5 | - update(index, updatedTodo): update todo at given index 6 | - getAll: returns all todos 7 | - get(indexOfTodo): returns todo at given index 8 | - clear: deletes all todos 9 | 10 | Once you've implemented the logic, test your code by running 11 | - `npm run test-todo-list` 12 | */ 13 | 14 | class Todo { 15 | 16 | } 17 | 18 | module.exports = Todo; 19 | -------------------------------------------------------------------------------- /assignments/async-js/hard (promises)/4-promise-chain.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Write 3 different functions that return promises that resolve after 1, 2, and 3 seconds respectively. 3 | * Write a function that sequentially calls all 3 of these functions in order. 4 | * Print out the time it takes to complete the entire operation. 5 | * Compare it with the results from 3-promise-all.js 6 | */ 7 | 8 | function waitOneSecond() { 9 | 10 | } 11 | 12 | function waitTwoSecond() { 13 | 14 | } 15 | 16 | function waitThreeSecond() { 17 | 18 | } 19 | 20 | function calculateTime() { 21 | 22 | } -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/components/Register.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | /// File is incomplete. You need to add input boxes to take input for users to register. 4 | function Register() { 5 | const [email, setEmail] = React.useState(""); 6 | 7 | return
8 |

Register to the website

9 |
10 | setEmail(e.target.value)} /> 11 |
12 | Already a user? Login 13 |
14 | } 15 | 16 | export default Register; -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/components/ShowCourses.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | function ShowCourses() { 4 | const [courses, setCourses] = React.useState([]); 5 | 6 | // Add code to fetch courses from the server 7 | // and set it in the courses state variable. 8 | return
9 |

Create Course Page

10 | {courses.map(c => )} 11 |
12 | } 13 | 14 | function Course(props) { 15 | return
16 |

{props.title}

17 |
18 | } 19 | 20 | export default ShowCourses; -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/components/CreateCourse.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | /// You need to add input boxes to take input for users to create a course. 3 | /// I've added one input so you understand the api to do it. 4 | function CreateCourse() { 5 | const [title, setTitle] = React.useState(""); 6 | 7 | return
8 |

Create Course Page

9 | setTitle(e.target.value)} /> 10 | 11 |
12 | } 13 | export default CreateCourse; -------------------------------------------------------------------------------- /backend/Basic_FSD/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | TODO App 7 | 8 | 9 | 10 |
11 |

TODO List

12 | 13 | 14 | 15 |
16 |
17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /assignments/async-js/easy/2-counter.md: -------------------------------------------------------------------------------- 1 | ## Counter without setInterval 2 | 3 | Without using setInterval, try to code a counter in Javascript. There is a hint at the bottom of the file if you get stuck. 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | (Hint: setTimeout) -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/index.js: -------------------------------------------------------------------------------- 1 | 2 | const express = require("express"); 3 | const app = express(); 4 | const mongoose = require("mongoose"); 5 | const port = 3000; 6 | const authRoutes = require("./routes/auth"); 7 | const todoRoutes = require("./routes/todo"); 8 | const cors = require("cors"); 9 | 10 | app.use(cors()); 11 | app.use(express.json()); 12 | app.use("/auth", authRoutes); 13 | app.use("/todo", todoRoutes); 14 | 15 | app.listen(port, () => { 16 | console.log(`Example app listening at http://localhost:${port}`) 17 | }) 18 | 19 | mongoose.connect('mongodb://localhost:27017/courses', { dbName: "courses" }); 20 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/components/Login.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | /// File is incomplete. You need to add input boxes to take input for users to login. 4 | function Login() { 5 | const [email, setEmail] = React.useState(""); 6 | 7 | return
8 |

Login to admin dashboard

9 |
10 | Email - setEmail(e.target.value)} /> 11 |
12 | 13 |
14 | New here? Register 15 |
16 | } 17 | 18 | export default Login; -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/src/App.jsx: -------------------------------------------------------------------------------- 1 | import { useState } from 'react' 2 | import reactLogo from './assets/react.svg' 3 | import viteLogo from '/vite.svg' 4 | import './App.css' 5 | 6 | function App() { 7 | const [todos, setTodos] = useState([]) 8 | // fetch all todos from server 9 | 10 | return ( 11 | <> 12 |
13 |

Easy Todo App

14 | 15 |
16 | 17 | ) 18 | } 19 | 20 | function Todo(props) { 21 | // Add a delete button here so user can delete a TODO. 22 | return
23 | {props.title} 24 |
25 | } 26 | 27 | export default App 28 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/components/Landing.jsx: -------------------------------------------------------------------------------- 1 | 2 | import React from "react"; 3 | 4 | /// This is the landing page. You need to add a link to the login page here. 5 | /// Maybe also check from the backend if the user is already logged in and then show them a logout button 6 | /// Logging a user out is as simple as deleting the token from the local storage. 7 | function Landing() { 8 | return
9 |

Welcome to course selling website!

10 | Register 11 |
12 | Login 13 |
14 | } 15 | 16 | export default Landing; -------------------------------------------------------------------------------- /visaa_oa/assignments.md: -------------------------------------------------------------------------------- 1 | ### Assignments : 18th Novemeber 2 | 3 | - Score should be greater than 2700 4 | - Complete these problems: 5 | - https://leetcode.com/problems/longest-substring-without-repeating-characters/ 6 | - https://leetcode.com/problems/roman-to-integer/ 7 | - https://leetcode.com/problems/valid-palindrome/ 8 | - https://leetcode.com/problems/restore-ip-addresses/ 9 | - https://leetcode.com/problems/valid-anagram/ 10 | - https://leetcode.com/problems/reverse-string/ 11 | - https://leetcode.com/problems/first-unique-character-in-a-string/ 12 | - https://leetcode.com/problems/reverse-vowels-of-a-string/ 13 | 14 | -------------------------------------------------------------------------------- /nodejs/file.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | let charan = "vjkhlkchvjbk"; 3 | 4 | fs.writeFileSync("vnr.txt",charan); 5 | fs.writeFile("something.txt","hello javascript",(err)=>{ 6 | if(err){ 7 | console.log("There is an error",err); 8 | } 9 | else{ 10 | console.log("Write file worked successfully!") 11 | } 12 | }) 13 | 14 | fs.readFile("vnr.txt","utf8",(err,data)=>{ 15 | if(err){ 16 | console.log("There is an error",err); 17 | } 18 | else{ 19 | console.log("Read file worked successfully!") 20 | console.log(data); 21 | } 22 | }) 23 | 24 | let data = fs.readFileSync("something.txt","utf8"); 25 | console.log(data) 26 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "01-reconciler", 3 | "version": "1.0.0", 4 | "description": "You have the janky version of a reconciler. It's not very good. It's not very fast. But it's a start. In the 3.2 video we discuss how we can make it faster. Can you figure out how to make it faster? By faster we mean minimizing the number of DOM interactions. Feel free to look at the tests for a hint", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "jest" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "devDependencies": { 12 | "jest": "^29.5.0", 13 | "jest-environment-jsdom": "^29.5.0", 14 | "jsdom": "^22.1.0" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /assignments/async-js/README.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Assignments 2 | 3 | This folder contains assignments related to asynchronous JavaScript. 4 | 5 | ### Assignments 6 | 7 | Recommended order below but feel free to make a mess in any order you like. 8 | 1. Easy 9 | 1. Counter 10 | 2. Counter (no setInterval) 11 | 3. Read from a file 12 | 4. Write to a file 13 | 2. Medium 14 | 1. File cleaner 15 | 2. Clock 16 | 3. Hard 17 | 1. Promisify setTimeout 18 | 2. Sleep completely 19 | 3. Promise all 20 | 4. Promise chain 21 | 22 | #### Development Setup 23 | 1. If you have Node.js locally, you should run these on your machine 24 | 2. If you don't, you can copy these over to repl.it and run it there. 25 | -------------------------------------------------------------------------------- /assignments/js/easy/expenditure-analysis.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement a function `calculateTotalSpentByCategory` which takes a list of transactions as parameter 3 | and return a list of objects where each object is unique category-wise and has total price spent as its value. 4 | Transaction - an object like { itemName, category, price, timestamp }. 5 | Output - [{ category1 - total_amount_spent_on_category1 }, { category2 - total_amount_spent_on_category2 }] 6 | 7 | Once you've implemented the logic, test your code by running 8 | - `npm run test-expenditure-analysis` 9 | */ 10 | 11 | function calculateTotalSpentByCategory(transactions) { 12 | return []; 13 | } 14 | 15 | module.exports = calculateTotalSpentByCategory; 16 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/middleware/index.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken'); 2 | const { Response } = require('express'); 3 | const SECRET = 'SECr3t'; // This should be in an environment variable in a real application 4 | 5 | const authenticateJwt = (req, res, next) => { 6 | const authHeader = req.headers.authorization; 7 | if (authHeader) { 8 | const token = authHeader.split(' ')[1]; 9 | jwt.verify(token, SECRET, (err, user) => { 10 | if (err) { 11 | return res.sendStatus(403); 12 | } 13 | req.userId = user.id; 14 | next(); 15 | }); 16 | } else { 17 | res.sendStatus(401); 18 | } 19 | }; 20 | 21 | module.exports = { 22 | authenticateJwt, 23 | SECRET 24 | } 25 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy-2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-course-app-easy", 3 | "version": "1.0.0", 4 | "description": "### Description 1. Admins should be able to sign up 2. Admins should be able to create courses 1. Course has a title, description, price, and image link 2. Course should be able to be published or unpublished 3. Admins should be able to edit courses 4. Users should be able to sign up 5. Users should be able to purchase courses 6. Users should be able to view purchased courses 7. Users should be able to view all courses", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-course-app-easy", 3 | "version": "1.0.0", 4 | "description": "### Description 1. Admins should be able to sign up 2. Admins should be able to create courses 1. Course has a title, description, price, and image link 2. Course should be able to be published or unpublished 3. Admins should be able to edit courses 4. Users should be able to sign up 5. Users should be able to purchase courses 6. Users should be able to view purchased courses 7. Users should be able to view all courses", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /assignments/react/03-course-app-medium/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-course-app-easy", 3 | "version": "1.0.0", 4 | "description": "### Description 1. Admins should be able to sign up 2. Admins should be able to create courses 1. Course has a title, description, price, and image link 2. Course should be able to be published or unpublished 3. Admins should be able to edit courses 4. Users should be able to sign up 5. Users should be able to purchase courses 6. Users should be able to view purchased courses 7. Users should be able to view all courses", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /assignments/react/04-course-app-hard/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-course-app-easy", 3 | "version": "1.0.0", 4 | "description": "### Description 1. Admins should be able to sign up 2. Admins should be able to create courses 1. Course has a title, description, price, and image link 2. Course should be able to be published or unpublished 3. Admins should be able to edit courses 4. Users should be able to sign up 5. Users should be able to purchase courses 6. Users should be able to view purchased courses 7. Users should be able to view all courses", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /assignments/fs_typescript/README.md: -------------------------------------------------------------------------------- 1 | We have ~2 medium-ish assignments this week 2 | 1. Convert a JS backend to TS 3 | 2. Convert a JS react app to TS 4 | 5 | First one might feel more difficult than the second one because we're creating a tsconfig file, moving all our files to TS and then fixing all the errors. 6 | The second one might feel easier since we're using vite to simply bootstrap the project, and then moving files over. 7 | 8 | The goal of this week is to get you comfortable with TS, and to show you how to move a JS project to TS. 9 | 10 | If you feel you're getting overwhelmed, you dont have to do the assignment. You can wait for the solution to be released, and then follow along with the solution. 11 | 12 | This weeks assigment is slightly hard, and I would urge you to use TAs support throughout the week. -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "01-easy-todo-app", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0" 15 | }, 16 | "devDependencies": { 17 | "@types/react": "^18.0.37", 18 | "@types/react-dom": "^18.0.11", 19 | "@vitejs/plugin-react": "^4.0.0", 20 | "eslint": "^8.38.0", 21 | "eslint-plugin-react": "^7.32.2", 22 | "eslint-plugin-react-hooks": "^4.6.0", 23 | "eslint-plugin-react-refresh": "^0.3.4", 24 | "vite": "^4.3.9" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /assignments/js/README.md: -------------------------------------------------------------------------------- 1 | ## JavaScript Assignments 2 | 3 | You are provided empty JavaScript files (or having function signatures) in this directory. 4 | You have to follow the instructions given in each file and write the code in the same file to complete the assignment. 5 | 6 | ### Assignments 7 | Feel free to start doing these in any order you like. 8 | 1. Easy 9 | 1. Anagram 10 | 2. Expenditure Analysis 11 | 2. Medium 12 | 1. Palindrome 13 | 2. Times 14 | 3. Hard 15 | 1. Calculator 16 | 2. Todo List 17 | 18 | ## Testing 19 | 1. Follow the comment above each problem to run test for that problem 20 | 3. To tests for all the problems of this week run ```npx jest ./tests/``` 21 | 22 | #### Development Setup 23 | 1. If you have Node.js locally, you should run these on your machine 24 | 2. If you don't, you can copy these over to repl.it and run it there. 25 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "assignment-2", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0", 15 | "react-router-dom": "^6.14.2", 16 | "recoil": "^0.7.7" 17 | }, 18 | "devDependencies": { 19 | "@types/react": "^18.2.15", 20 | "@types/react-dom": "^18.2.7", 21 | "@vitejs/plugin-react": "^4.0.3", 22 | "eslint": "^8.45.0", 23 | "eslint-plugin-react": "^7.32.2", 24 | "eslint-plugin-react-hooks": "^4.6.0", 25 | "eslint-plugin-react-refresh": "^0.4.3", 26 | "vite": "^4.4.5" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /assignments/nodejs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-nodejs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "test-fileServer": "./node_modules/jest/bin/jest.js ./tests/fileServer.test.js", 9 | "test-todoServer": "./node_modules/jest/bin/jest.js ./tests/todoServer.test.js", 10 | "test-authenticationServer": "./node_modules/jest/bin/jest.js ./tests/authenticationServer.test.js", 11 | "test-all": "./node_modules/jest/bin/jest.js ./tests/" 12 | }, 13 | "keywords": [], 14 | "author": "", 15 | "license": "ISC", 16 | "devDependencies": { 17 | "jest": "^29.5.0", 18 | "supertest": "^6.3.3" 19 | }, 20 | "jest": { 21 | "testTimeout": 10000 22 | }, 23 | "dependencies": { 24 | "express": "^4.18.2", 25 | "uuid": "^9.0.0" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "02-medium-course-selling-app", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "react": "^18.2.0", 14 | "react-dom": "^18.2.0", 15 | "react-router-dom": "^6.14.1" 16 | }, 17 | "devDependencies": { 18 | "@types/react": "^18.0.37", 19 | "@types/react-dom": "^18.0.11", 20 | "@vitejs/plugin-react": "^4.0.0", 21 | "eslint": "^8.38.0", 22 | "eslint-plugin-react": "^7.32.2", 23 | "eslint-plugin-react-hooks": "^4.6.0", 24 | "eslint-plugin-react-refresh": "^0.3.4", 25 | "vite": "^4.3.9" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /assignments/full_stack/03-hard-course-selling-app-user-side/README.md: -------------------------------------------------------------------------------- 1 | ### Hard todo 2 | Create the user side of a course selling app. 3 | This means the backend remains the same, but now you have two websites. 4 | Routes should be very similar to the old ones, but now you need to add a new route for the user to see the contents of a single course. 5 | You need to create the boilerplate yourself using vite 6 | 7 | Frontend Routes expected - 8 | 1. /courses - shows all courses 9 | 2. /courses/purchased - Shows all purchased courses 10 | 3. /courses/:id - Shows a single course, allows user to purchase it 11 | 4. /login - login page 12 | 5. /signup - signup page 13 | 6. / - Landing page 14 | 15 | 16 | By the end of this you should have two frontends - 17 | 1. One for the admin dashboard (02-medium-course-selling-app-admin-dashboard) 18 | 2. One for the user side of the app (03-hard-course-selling-app-user-side 19 | -------------------------------------------------------------------------------- /assignments/js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "01", 3 | "version": "1.0.0", 4 | "description": "You are provided empty JavaScript files (or having function signatures) in this directory. You have to follow the instructions given in each file and write the code in the same file to complete the assignment.", 5 | "main": "anagram.js", 6 | "directories": { 7 | "test": "tests" 8 | }, 9 | "scripts": { 10 | "test-anagram": "npx jest ./tests/anagram.test.js", 11 | "test-calculator": "npx jest ./tests/calculator.test.js", 12 | "test-duplicate-transactions": "npx jest ./tests/duplicate-transactions.test.js", 13 | "test-expenditure-analysis": "npx jest ./tests/expenditure-analysis.test.js", 14 | "test-palindrome": "npx jest ./tests/palindrome.test.js", 15 | "test-todo-list": "npx jest ./tests/todo-list.test.js", 16 | "test-all": "npx jest ./tests/" 17 | }, 18 | "keywords": [], 19 | "author": "", 20 | "license": "ISC" 21 | } 22 | -------------------------------------------------------------------------------- /visaa_oa/input.md: -------------------------------------------------------------------------------- 1 | # Taking Integer Input in Python 2 | 3 | ## Single Integer Input 4 | To take a single integer input in Python, you can use the `int()` function with the `input()` function: 5 | 6 | ```python 7 | num = int(input()) 8 | ``` 9 | 10 | This will store the user's input as an integer value in the variable `num`. 11 | 12 | ## Multiple Integer Inputs 13 | If you want to take multiple integer inputs on a single line, you can use the `map()` function along with `input().split()`: 14 | 15 | ```python 16 | n, m = map(int, input().split()) 17 | ``` 18 | 19 | This will store the first input as `n` and the second input as `m`, both as integers. 20 | 21 | ## List of Integers 22 | If you need to take more than 3 integer inputs on a single line, it's generally recommended to store them as a list: 23 | 24 | ```python 25 | nums = list(map(int, input().split())) 26 | ``` 27 | 28 | This will create a list `nums` containing all the integer values entered by the user. 29 | -------------------------------------------------------------------------------- /assignments/js/easy/anagram.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function `isAnagram` which takes 2 parameters and returns true/false if those are anagrams or not. 3 | What's Anagram? 4 | - A word, phrase, or name formed by rearranging the letters of another, such as spar, formed from rasp. 5 | 6 | Once you've implemented the logic, test your code by running 7 | - `npm run test-anagram` 8 | */ 9 | 10 | function isAnagram(str1, str2) { 11 | // Remove spaces and convert to lowercase 12 | const cleanStr1 = str1.replace(/\s+/g, '').toLowerCase(); 13 | const cleanStr2 = str2.replace(/\s+/g, '').toLowerCase(); 14 | 15 | // Check if lengths are the same 16 | if (cleanStr1.length !== cleanStr2.length) { 17 | return false; 18 | } 19 | 20 | // Sort and compare 21 | const sortedStr1 = cleanStr1.split('').sort().join(''); 22 | const sortedStr2 = cleanStr2.split('').sort().join(''); 23 | 24 | return sortedStr1 === sortedStr2; 25 | } 26 | 27 | 28 | module.exports = isAnagram; 29 | -------------------------------------------------------------------------------- /mgit/floor_ceil_assignment: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public int[] getFloorAndCeil(int x, int[] arr) { 4 | int[] result = new int[2]; 5 | Arrays.sort(arr); 6 | int n = arr.length; 7 | int l =0,r=n-1; 8 | 9 | while(l<=r){ 10 | int mid = (l+r)>>1; 11 | if(arr[mid]==x) { 12 | result[0]=mid; 13 | break; 14 | } 15 | else if (arr[mid]>1; 25 | if(arr[mid]==x) { 26 | result[1]=mid; 27 | break; 28 | 29 | } 30 | else if (arr[mid]>x){ 31 | result[1]=mid; 32 | r= mid-1; 33 | } 34 | else l =mid+1; 35 | } 36 | return result; 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /AppointmentApp/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Appointment Booking 7 | 8 | 9 | 10 |

Appointment Booking

11 |
12 |
13 |
14 | 15 | 16 |
17 |
18 | 19 | 20 | 21 | 22 |
23 |
24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /visaa_oa/trees.md: -------------------------------------------------------------------------------- 1 | 2 | 1. [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) 3 | 2. [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) 4 | 3. [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/) 5 | 4. [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) 6 | 5. [Path Sum II](https://leetcode.com/problems/path-sum-ii-) 7 | 6. [Path Sum III](https://leetcode.com/problems/path-sum-iii/) 8 | 7. [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream) 9 | 8. [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning) 10 | 9. [Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) 11 | 10. [Maximum Level Sum of a Binary Tree](https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree) 12 | 11. [**Number of Good Leaf Nodes Pairs**](https://leetcode.com/problems/number-of-good-leaf-nodes-pairs) (most important) 13 | -------------------------------------------------------------------------------- /backend/command_notes.md: -------------------------------------------------------------------------------- 1 | node --version ( to check whether node is installed properly or not ) 2 | 3 | dir ( to print all the files of the current existing directory / folder ) 4 | 5 | cd ( changing directory ) 6 | 7 | cd .. ( changing one step backward) 8 | 9 | cd folder_name ( changing to one step forward ) 10 | 11 | cntrl + c ( for stopping server ) 12 | 13 | node server.js ( for starting server ) 14 | 15 | cntrl + , ( for settings in vs code ) 16 | 17 | 18 | Steps to open VS code from file explorer 19 | 20 | - click on address 21 | - remove address using backspace 22 | - type cmd 23 | - black box ( Command Prompt ) 24 | - code . ( this open that particular folder inside vs code ) 25 | 26 | 27 | .gitignore ( This is for ignoring files you don't need to push to GitHub ) 28 | 29 | 30 | ![WhatsApp Image 2024-10-29 at 19 54 24_23508e8f](https://github.com/user-attachments/assets/91873ce0-ab5e-42ca-a621-e59b968189de) 31 | 32 | ![WhatsApp Image 2024-10-29 at 20 20 41_6cfd118a](https://github.com/user-attachments/assets/34f27c6b-b723-4c5a-b3cb-4f5ce2b31cd1) 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /assignments/nodejs/fileServer.js: -------------------------------------------------------------------------------- 1 | /** 2 | You need to create an express HTTP server in Node.js which will handle the logic of a file server. 3 | - Use built in Node.js `fs` module 4 | 5 | The expected API endpoints are defined below, 6 | 1. GET /files - Returns a list of files present in `./files/` directory 7 | Response: 200 OK with an array of file names in JSON format. 8 | Example: GET http://localhost:3000/files 9 | 10 | 2. GET /file/:filename - Returns content of given file by name 11 | Description: Use the filename from the request path parameter to read the file from `./files/` directory 12 | Response: 200 OK with the file content as the response body if found, or 404 Not Found if not found. Should return `File not found` as text if file is not found 13 | Example: GET http://localhost:3000/file/example.txt 14 | 15 | - For any other route not defined in the server return 404 16 | 17 | Testing the server - run `npm run test-fileServer` command in terminal 18 | */ 19 | const express = require('express'); 20 | const fs = require('fs'); 21 | const path = require('path'); 22 | const app = express(); 23 | 24 | 25 | module.exports = app; 26 | -------------------------------------------------------------------------------- /backend/Basic_FSD/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, sans-serif; 3 | display: flex; 4 | justify-content: center; 5 | padding: 20px; 6 | background-color: #f4f4f4; 7 | } 8 | 9 | #app { 10 | width: 300px; 11 | background: white; 12 | padding: 20px; 13 | border-radius: 8px; 14 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); 15 | } 16 | 17 | h2 { 18 | text-align: center; 19 | } 20 | 21 | input { 22 | width: calc(100% - 22px); 23 | padding: 10px; 24 | border: 1px solid #ddd; 25 | border-radius: 5px; 26 | } 27 | 28 | button { 29 | padding: 10px; 30 | border: none; 31 | border-radius: 5px; 32 | cursor: pointer; 33 | margin-left: 5px; 34 | } 35 | 36 | .create { 37 | background-color: green; 38 | color: white; 39 | } 40 | 41 | .update { 42 | background-color: yellow; 43 | border: none; 44 | cursor: pointer; 45 | } 46 | 47 | .delete { 48 | background-color: red; 49 | color: white; 50 | border: none; 51 | } 52 | 53 | .task-list { 54 | margin-top: 20px; 55 | } 56 | 57 | .task-item { 58 | display: flex; 59 | align-items: center; 60 | margin-top: 10px; 61 | } 62 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/App.jsx: -------------------------------------------------------------------------------- 1 | import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; 2 | import Login from './components/Login'; 3 | import Landing from "./components/Landing"; 4 | import CreateCourse from './components/CreateCourse'; 5 | import Register from './components/Register'; 6 | import ShowCourses from './components/ShowCourses'; 7 | 8 | // This file shows how you can do routing in React. 9 | // Try going to /login, /register, /about, /courses on the website and see how the html changes 10 | // based on the route. 11 | // You can also try going to /random and see what happens (a route that doesnt exist) 12 | function App() { 13 | return ( 14 | 15 | 16 | } /> 17 | } /> 18 | } /> 19 | } /> 20 | } /> 21 | 22 | 23 | ); 24 | } 25 | 26 | export default App; -------------------------------------------------------------------------------- /assignments/js/hard/calculator.js: -------------------------------------------------------------------------------- 1 | /* 2 | Implement a class `Calculator` having below methods 3 | - initialise a result variable in the constructor and keep updating it after every arithmetic operation 4 | - add: takes a number and adds it to the result 5 | - subtract: takes a number and subtracts it from the result 6 | - multiply: takes a number and multiply it to the result 7 | - divide: takes a number and divide it to the result 8 | - clear: makes the `result` variable to 0 9 | - getResult: returns the value of `result` variable 10 | - calculate: takes a string expression which can take multi-arithmetic operations and give its result 11 | example input: `10 + 2 * ( 6 - (4 + 1) / 2) + 7` 12 | Points to Note: 13 | 1. the input can have multiple continuous spaces, you're supposed to avoid them and parse the expression correctly 14 | 2. the input can have invalid non-numerical characters like `5 + abc`, you're supposed to throw error for such inputs 15 | 16 | Once you've implemented the logic, test your code by running 17 | - `npm run test-calculator` 18 | */ 19 | 20 | class Calculator {} 21 | 22 | module.exports = Calculator; 23 | -------------------------------------------------------------------------------- /assignments/js/tests/anagram.test.js: -------------------------------------------------------------------------------- 1 | const isAnagram = require('../easy/anagram'); 2 | 3 | describe('isAnagram', () => { 4 | test('returns true for anagrams', () => { 5 | expect(isAnagram('listen', 'silent')).toBe(true); 6 | expect(isAnagram('rail safety', 'fairy tales')).toBe( 7 | true 8 | ); 9 | expect(isAnagram('openai', 'aiopen')).toBe(true); 10 | expect(isAnagram('', '')).toBe(true); 11 | }); 12 | 13 | test('returns false for non-anagrams', () => { 14 | expect(isAnagram('hello', 'world')).toBe(false); 15 | expect(isAnagram('openai', 'open')).toBe(false); 16 | expect(isAnagram('hello', 'lhel')).toBe(false); 17 | expect(isAnagram('working', 'non')).toBe(false); 18 | }); 19 | 20 | test('returns true for anagrams with different casing', () => { 21 | expect(isAnagram('Debit Card', 'Bad Credit')).toBe( 22 | true 23 | ); 24 | expect( 25 | isAnagram('School MASTER', 'The ClassROOM') 26 | ).toBe(true); 27 | }); 28 | 29 | test('returns true for anagrams with special characters', () => { 30 | expect(isAnagram('abc!', '!bac')).toBe(true); 31 | }); 32 | 33 | test('returns false for non-anagrams with special characters', () => { 34 | expect(isAnagram('hello', 'hello!')).toBe(false); 35 | expect(isAnagram('openai!', 'open')).toBe(false); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy-2/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | app.use(express.json()); 5 | 6 | let ADMINS = []; 7 | let USERS = []; 8 | let COURSES = []; 9 | 10 | // Admin routes 11 | app.post('/admin/signup', (req, res) => { 12 | // logic to sign up admin 13 | }); 14 | 15 | app.post('/admin/login', (req, res) => { 16 | // logic to log in admin 17 | }); 18 | 19 | app.post('/admin/courses', (req, res) => { 20 | // logic to create a course 21 | }); 22 | 23 | app.put('/admin/courses/:courseId', (req, res) => { 24 | // logic to edit a course 25 | }); 26 | 27 | app.get('/admin/courses', (req, res) => { 28 | // logic to get all courses 29 | }); 30 | 31 | // User routes 32 | app.post('/users/signup', (req, res) => { 33 | // logic to sign up user 34 | }); 35 | 36 | app.post('/users/login', (req, res) => { 37 | // logic to log in user 38 | }); 39 | 40 | app.get('/users/courses', (req, res) => { 41 | // logic to list all courses 42 | }); 43 | 44 | app.post('/users/courses/:courseId', (req, res) => { 45 | // logic to purchase a course 46 | }); 47 | 48 | app.get('/users/purchasedCourses', (req, res) => { 49 | // logic to view purchased courses 50 | }); 51 | 52 | app.listen(3000, () => { 53 | console.log('Server is listening on port 3000'); 54 | }); 55 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | app.use(express.json()); 5 | 6 | let ADMINS = []; 7 | let USERS = []; 8 | let COURSES = []; 9 | 10 | // Admin routes 11 | app.post('/admin/signup', (req, res) => { 12 | // logic to sign up admin 13 | }); 14 | 15 | app.post('/admin/login', (req, res) => { 16 | // logic to log in admin 17 | }); 18 | 19 | app.post('/admin/courses', (req, res) => { 20 | // logic to create a course 21 | }); 22 | 23 | app.put('/admin/courses/:courseId', (req, res) => { 24 | // logic to edit a course 25 | }); 26 | 27 | app.get('/admin/courses', (req, res) => { 28 | // logic to get all courses 29 | }); 30 | 31 | // User routes 32 | app.post('/users/signup', (req, res) => { 33 | // logic to sign up user 34 | }); 35 | 36 | app.post('/users/login', (req, res) => { 37 | // logic to log in user 38 | }); 39 | 40 | app.get('/users/courses', (req, res) => { 41 | // logic to list all courses 42 | }); 43 | 44 | app.post('/users/courses/:courseId', (req, res) => { 45 | // logic to purchase a course 46 | }); 47 | 48 | app.get('/users/purchasedCourses', (req, res) => { 49 | // logic to view purchased courses 50 | }); 51 | 52 | app.listen(3000, () => { 53 | console.log('Server is listening on port 3000'); 54 | }); 55 | -------------------------------------------------------------------------------- /assignments/react/03-course-app-medium/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | app.use(express.json()); 5 | 6 | let ADMINS = []; 7 | let USERS = []; 8 | let COURSES = []; 9 | 10 | // Admin routes 11 | app.post('/admin/signup', (req, res) => { 12 | // logic to sign up admin 13 | }); 14 | 15 | app.post('/admin/login', (req, res) => { 16 | // logic to log in admin 17 | }); 18 | 19 | app.post('/admin/courses', (req, res) => { 20 | // logic to create a course 21 | }); 22 | 23 | app.put('/admin/courses/:courseId', (req, res) => { 24 | // logic to edit a course 25 | }); 26 | 27 | app.get('/admin/courses', (req, res) => { 28 | // logic to get all courses 29 | }); 30 | 31 | // User routes 32 | app.post('/users/signup', (req, res) => { 33 | // logic to sign up user 34 | }); 35 | 36 | app.post('/users/login', (req, res) => { 37 | // logic to log in user 38 | }); 39 | 40 | app.get('/users/courses', (req, res) => { 41 | // logic to list all courses 42 | }); 43 | 44 | app.post('/users/courses/:courseId', (req, res) => { 45 | // logic to purchase a course 46 | }); 47 | 48 | app.get('/users/purchasedCourses', (req, res) => { 49 | // logic to view purchased courses 50 | }); 51 | 52 | app.listen(3000, () => { 53 | console.log('Server is listening on port 3000'); 54 | }); 55 | -------------------------------------------------------------------------------- /assignments/react/04-course-app-hard/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | app.use(express.json()); 5 | 6 | let ADMINS = []; 7 | let USERS = []; 8 | let COURSES = []; 9 | 10 | // Admin routes 11 | app.post('/admin/signup', (req, res) => { 12 | // logic to sign up admin 13 | }); 14 | 15 | app.post('/admin/login', (req, res) => { 16 | // logic to log in admin 17 | }); 18 | 19 | app.post('/admin/courses', (req, res) => { 20 | // logic to create a course 21 | }); 22 | 23 | app.put('/admin/courses/:courseId', (req, res) => { 24 | // logic to edit a course 25 | }); 26 | 27 | app.get('/admin/courses', (req, res) => { 28 | // logic to get all courses 29 | }); 30 | 31 | // User routes 32 | app.post('/users/signup', (req, res) => { 33 | // logic to sign up user 34 | }); 35 | 36 | app.post('/users/login', (req, res) => { 37 | // logic to log in user 38 | }); 39 | 40 | app.get('/users/courses', (req, res) => { 41 | // logic to list all courses 42 | }); 43 | 44 | app.post('/users/courses/:courseId', (req, res) => { 45 | // logic to purchase a course 46 | }); 47 | 48 | app.get('/users/purchasedCourses', (req, res) => { 49 | // logic to view purchased courses 50 | }); 51 | 52 | app.listen(3000, () => { 53 | console.log('Server is listening on port 3000'); 54 | }); 55 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/README.md: -------------------------------------------------------------------------------- 1 | 2 | ### Create the frontend for the ADMIN DASHBOARD for a course selling app 3 | 4 | Please start backend from week-3/solutions/03-course-app-medium.js (add app.listen, cors if its not there already) 5 | 6 | 1. Start the backend from week-3/solutions/02-course-app-medium.js 7 | 2. We will use authentication, which means you need to get back the jwt and store it in localStorage (read https://www.robinwieruch.de/local-storage-react/) 8 | 3. You need to understand routing for this to work, so we've added a basic boilerplate that lets you navigate between 3 routes (check App.jsx) 9 | 4. To test the current app, run `npm run dev` and see the output on localhost:3000 10 | 11 | Things that will confuse you - 12 | 1. Routing. Here is a great blog post explaining it - https://hygraph.com/blog/routing-in-react . If you open App.jsx you should intuitively be able to understand whats happening 13 | 2. Authentication (More specifically , how to store it in localstorage and how to put it in headers when sending the request) 14 | 15 | ### Hard todo - 16 | Add routing to introduce a new route /courses/:id which shows you the contents of a single course 17 | It should also let you edit the course title, description and price 18 | This will be needed in the next assignment -------------------------------------------------------------------------------- /backend/Basic_FSD/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const fs = require('fs'); 3 | const cors = require('cors'); 4 | const app = express(); 5 | const PORT = 5000; 6 | 7 | app.use(cors()); 8 | app.use(express.json()); 9 | 10 | const getTasks = () => JSON.parse(fs.readFileSync('database.json', 'utf-8')); 11 | 12 | // Get all tasks 13 | app.get('/tasks', (req, res) => { 14 | res.json(getTasks()); 15 | }); 16 | 17 | // Add a new task 18 | app.post('/tasks', (req, res) => { 19 | const tasks = getTasks(); 20 | const newTask = { id: Date.now(), text: req.body.text }; 21 | tasks.push(newTask); 22 | fs.writeFileSync('database.json', JSON.stringify(tasks)); 23 | res.json(newTask); 24 | }); 25 | 26 | // Update a task 27 | app.put('/tasks/:id', (req, res) => { 28 | const tasks = getTasks(); 29 | const updatedTasks = tasks.map(task => 30 | task.id === parseInt(req.params.id) ? { ...task, text: req.body.text } : task 31 | ); 32 | fs.writeFileSync('database.json', JSON.stringify(updatedTasks)); 33 | res.json({ message: 'Task updated' }); 34 | }); 35 | 36 | // Delete a task 37 | app.delete('/tasks/:id', (req, res) => { 38 | const tasks = getTasks().filter(task => task.id !== parseInt(req.params.id)); 39 | fs.writeFileSync('database.json', JSON.stringify(tasks)); 40 | res.json({ message: 'Task deleted' }); 41 | }); 42 | 43 | app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 44 | -------------------------------------------------------------------------------- /anurag_hackathon/final_prompt.md: -------------------------------------------------------------------------------- 1 | 2 | "Create a full-stack AI application with the following specifications: 3 | 4 | Frontend Requirements: 5 | - Create a modern, responsive UI using vanilla HTML5, CSS3, and JavaScript (no frameworks) 6 | - Include animated transitions and interactive elements 7 | - Implement a dark/light theme toggle 8 | - Add loading states and error handling 9 | - Make it mobile-friendly with a hamburger menu 10 | - Use CSS Grid/Flexbox for layouts 11 | - Include input validation on the client side 12 | 13 | Backend Requirements: 14 | - Build a Flask REST API with the following features: 15 | - Implement user session management using JSON files 16 | - Create separate routes for different AI functionalities 17 | - Add error handling and logging 18 | - Implement rate limiting 19 | - Add request validation 20 | 21 | Data Storage: 22 | - Use JSON files for all data persistence with the following structure: 23 | - users.json: Store user information 24 | - conversations.json: Store chat history/AI interactions 25 | - settings.json: Store application configurations 26 | - Include file locking mechanism for concurrent access 27 | - Implement backup/recovery system for JSON files 28 | 29 | AI Integration: 30 | - [Specify which AI model/functionality you want to use] 31 | - Include proper error handling for AI responses 32 | - Implement caching for AI responses to reduce API calls 33 | - Add fallback mechanisms for when AI service is unavailable 34 | -------------------------------------------------------------------------------- /assignments/nodejs/readme.md: -------------------------------------------------------------------------------- 1 | ## Node.js Assignments 2 | In this series of assignments, you are going to create native HTTP servers in Node.js which will handle different kinds of application logics. 3 | 4 | You are provided empty JavaScript files (or having function signatures) in this directory. You have to follow the instructions given in each file and then run automated tests (also mentioned in each file) to check if you have successfully completed the assignment or you still have few more things to learn in it 😜 5 | 6 | ### Assignments 7 | Recommended order of attempting the assignments. 8 | 1. Todo List App 9 | 2. File Server 10 | 3. Authentication System 11 | 12 | #### Important Notes 13 | 1. If you are unable to understand the request/response of any assignment file or whatever the way it is being tested, you can take a look at its respective test file present in `tests/` directory. 14 | 2. Don't try to make any changes to the test files present in the `tests/` directory. 15 | 3. To make sure that you have not missed any assignment you can run a final test command in terminal `npm run test-all`. 16 | 4. Don't make any changes to the code already present in files including function/method/class signatures and module exports. 17 | 18 | #### Development Setup 19 | 1. Install the dependencies used by running `npm install` command in your terminal. 20 | 2. We used `18.x.y` Node.js version, if anything doesn't work then please consider upgrading your node installation. 21 | 22 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/Components/Login.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import {Link} from 'react-router-dom'; 3 | 4 | const Login = () => { 5 | const [username, setUsername] = useState(''); 6 | const [password, setPassword] = useState(''); 7 | 8 | const handleLogin = async () => { 9 | const response = await fetch('http://localhost:3000/auth/login', { 10 | method: 'POST', 11 | headers: { 'Content-Type': 'application/json' }, 12 | body: JSON.stringify({ username, password }) 13 | }); 14 | // Todo: Create a type for the response that you get back from the server 15 | const data = await response.json(); 16 | if (data.token) { 17 | localStorage.setItem("token", data.token) 18 | window.location = "/todos"; 19 | } else { 20 | alert("invalid credentials"); 21 | } 22 | }; 23 | 24 | return ( 25 |
26 |
27 |

Login

28 | setUsername(e.target.value)} placeholder='Username' /> 29 | setPassword(e.target.value)} placeholder='Password' /> 30 | New here? Signup 31 | 32 |
33 |
34 | ); 35 | }; 36 | 37 | export default Login; 38 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/routes/todo.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const { authenticateJwt, SECRET } = require("../middleware/index"); 3 | const { Todo } = require("../db"); 4 | const router = express.Router(); 5 | 6 | router.post('/todos', authenticateJwt, (req, res) => { 7 | const { title, description } = req.body; 8 | const done = false; 9 | const userId = req.userId; 10 | 11 | const newTodo = new Todo({ title, description, done, userId }); 12 | 13 | newTodo.save() 14 | .then((savedTodo) => { 15 | res.status(201).json(savedTodo); 16 | }) 17 | .catch((err) => { 18 | res.status(500).json({ error: 'Failed to create a new todo' }); 19 | }); 20 | }); 21 | 22 | 23 | router.get('/todos', authenticateJwt, (req, res) => { 24 | const userId = req.userId; 25 | 26 | Todo.find({ userId }) 27 | .then((todos) => { 28 | res.json(todos); 29 | }) 30 | .catch((err) => { 31 | res.status(500).json({ error: 'Failed to retrieve todos' }); 32 | }); 33 | }); 34 | 35 | router.patch('/todos/:todoId/done', authenticateJwt, (req, res) => { 36 | const { todoId } = req.params; 37 | const userId = req.userId; 38 | 39 | Todo.findOneAndUpdate({ _id: todoId, userId }, { done: true }, { new: true }) 40 | .then((updatedTodo) => { 41 | if (!updatedTodo) { 42 | return res.status(404).json({ error: 'Todo not found' }); 43 | } 44 | res.json(updatedTodo); 45 | }) 46 | .catch((err) => { 47 | res.status(500).json({ error: 'Failed to update todo' }); 48 | }); 49 | }); 50 | 51 | module.exports = router; -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-1/routes/auth.js: -------------------------------------------------------------------------------- 1 | const jwt = require("jsonwebtoken"); 2 | const express = require('express'); 3 | const { authenticateJwt, SECRET } = require("../middleware/"); 4 | const { User } = require("../db"); 5 | const router = express.Router(); 6 | 7 | router.post('/signup', async (req, res) => { 8 | const { username, password } = req.body; 9 | const user = await User.findOne({ username }); 10 | if (user) { 11 | res.status(403).json({ message: 'User already exists' }); 12 | } else { 13 | const newUser = new User({ username, password }); 14 | await newUser.save(); 15 | const token = jwt.sign({ id: newUser._id }, SECRET, { expiresIn: '1h' }); 16 | res.json({ message: 'User created successfully', token }); 17 | } 18 | }); 19 | 20 | router.post('/login', async (req, res) => { 21 | const { username, password } = req.body; 22 | const user = await User.findOne({ username, password }); 23 | if (user) { 24 | const token = jwt.sign({ id: user._id }, SECRET, { expiresIn: '1h' }); 25 | res.json({ message: 'Logged in successfully', token }); 26 | } else { 27 | res.status(403).json({ message: 'Invalid username or password' }); 28 | } 29 | }); 30 | 31 | router.get('/me', authenticateJwt, async (req, res) => { 32 | const user = await User.findOne({ _id: req.userId }); 33 | if (user) { 34 | res.json({ username: user.username }); 35 | } else { 36 | res.status(403).json({ message: 'User not logged in' }); 37 | } 38 | }); 39 | 40 | module.exports = router 41 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/script-ugly.js: -------------------------------------------------------------------------------- 1 | function createDomElements(data) { 2 | var parentElement = document.getElementById("mainArea"); 3 | 4 | // Clear all existing children of the parentElement 5 | parentElement.innerHTML = ''; 6 | 7 | let added = 0; 8 | // Process each item in the data array 9 | data.forEach(function(item) { 10 | added++; 11 | // Create a new element 12 | var childElement = document.createElement("div"); 13 | childElement.dataset.id = item.id; // Store the ID on the element for future lookups 14 | 15 | var grandChildElement1 = document.createElement("span"); 16 | grandChildElement1.innerHTML = item.title 17 | 18 | var grandChildElement2 = document.createElement("span"); 19 | grandChildElement2.innerHTML = item.description 20 | 21 | var grandChildElement3 = document.createElement("button"); 22 | grandChildElement3.innerHTML = "Delete" 23 | grandChildElement3.setAttribute("onclick", "deleteTodo(" + item.id + ")") 24 | 25 | childElement.appendChild(grandChildElement1) 26 | childElement.appendChild(grandChildElement2) 27 | childElement.appendChild(grandChildElement3) 28 | parentElement.appendChild(childElement); 29 | }); 30 | 31 | console.log(added); 32 | } 33 | 34 | window.setInterval(() => { 35 | let todos = []; 36 | for (let i = 0; i ` 10 |
11 |

${appt.name} - ${appt.reason}

12 |

${appt.time} on ${appt.date}

13 |
`) 14 | .join(""); 15 | } 16 | 17 | // Fetch available slots for a date 18 | async function fetchSlots() { 19 | const date = document.getElementById("date-picker").value; 20 | const res = await fetch(`${baseUrl}/availability/${date}`); 21 | const { slots } = await res.json(); 22 | const view = document.getElementById("slots-view"); 23 | view.innerHTML = slots 24 | .map((slot) => `

${slot}

`) 25 | .join(""); 26 | } 27 | 28 | // Book an appointment 29 | async function bookAppointment(e) { 30 | e.preventDefault(); 31 | const name = document.getElementById("name").value; 32 | const reason = document.getElementById("reason").value; 33 | const time = document.getElementById("time").value; 34 | const date = document.getElementById("date-picker").value; 35 | 36 | const res = await fetch(`${baseUrl}/book`, { 37 | method: "POST", 38 | headers: { "Content-Type": "application/json" }, 39 | body: JSON.stringify({ name, reason, time, date }), 40 | }); 41 | const result = await res.json(); 42 | alert(result.message); 43 | fetchAppointments(); 44 | } 45 | 46 | document.addEventListener("DOMContentLoaded", fetchAppointments); 47 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/Components/Signup.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import {Link, useNavigate} from 'react-router-dom'; 3 | import {useSetRecoilState} from "recoil"; 4 | import {authState} from "../store/authState.js"; 5 | 6 | const Signup = () => { 7 | const [username, setUsername] = useState(''); 8 | const [password, setPassword] = useState(''); 9 | 10 | const handleSignup = async () => { 11 | const response = await fetch('http://localhost:3000/auth/signup', { 12 | method: 'POST', 13 | headers: { 'Content-Type': 'application/json' }, 14 | body: JSON.stringify({ username, password }) 15 | }); 16 | // Todo: Create a type for the response that you get back from the server 17 | const data = await response.json(); 18 | if (data.token) { 19 | localStorage.setItem("token", data.token) 20 | window.location = "/todos"; 21 | } else { 22 | alert("Error while signing up"); 23 | } 24 | }; 25 | 26 | return ( 27 |
28 |
29 |

Signup

30 | setUsername(e.target.value)} placeholder='Username' /> 31 | setPassword(e.target.value)} placeholder='Password' /> 32 | Already signed up? Login 33 | 34 |
35 |
36 | ); 37 | }; 38 | 39 | export default Signup; 40 | -------------------------------------------------------------------------------- /CMR FDP/ai_agents.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/user-attachments/assets/76d4d2d3-4325-44c9-ab0d-9b108def153b) 2 | ![image](https://github.com/user-attachments/assets/825f3dc3-2386-418f-a389-3a9acff41312) 3 | 4 | ![image](https://github.com/user-attachments/assets/7e1b42f5-5386-4a87-be73-6fdb5cc7dd07) 5 | 6 | ![image](https://github.com/user-attachments/assets/d59aa1b8-d214-49fa-a217-2938323d5724) 7 | 8 | ![image](https://github.com/user-attachments/assets/3961ef77-84a5-4226-86b5-dc45342a347d) 9 | 10 | 11 | 12 | 13 | ![image](https://github.com/user-attachments/assets/e43d6af3-8698-49c8-8fe8-23ceda5824c7) 14 | 15 | Key Concepts: 16 | 17 | 1. Thinking Systems: 18 | - System 1: Fast, automatic (current LLMs) 19 | - System 2: Slow, deliberate (future goal) 20 | 21 | 2. Crew AI Implementation: 22 | ```python 23 | from crew_ai import Agent, Task, Crew 24 | 25 | # Create agents 26 | researcher = Agent( 27 | role="Market Researcher", 28 | goal="Analyze market demand", 29 | backstory="Expert in market analysis" 30 | ) 31 | 32 | # Define tasks 33 | task = Task( 34 | description="Analyze market potential", 35 | agent=researcher 36 | ) 37 | 38 | # Create crew 39 | crew = Crew( 40 | agents=[researcher], 41 | tasks=[task] 42 | ) 43 | ``` 44 | 45 | ![image](https://github.com/user-attachments/assets/5f761751-cf56-439a-abcc-27c340f612be) 46 | 47 | 48 | 3. Tools Integration: 49 | - Built-in tools: Google Search, Wikipedia 50 | - Custom tools: Reddit scraper, Email parser 51 | - Local models support: Llama, Mistral 52 | 53 | 4. Local Model Performance: 54 | - Best: Llama 13B, OpenChat 55 | - Average: Mistral, OpenHermes 56 | - Poor: Llama 7B, T5 57 | 58 | ![image](https://github.com/user-attachments/assets/9b002174-6148-46bb-a5a6-6e30a6c219dc) 59 | 60 | -------------------------------------------------------------------------------- /MRU_FDP/ai_agents.md: -------------------------------------------------------------------------------- 1 | ![image](https://github.com/user-attachments/assets/76d4d2d3-4325-44c9-ab0d-9b108def153b) 2 | ![image](https://github.com/user-attachments/assets/825f3dc3-2386-418f-a389-3a9acff41312) 3 | 4 | ![image](https://github.com/user-attachments/assets/7e1b42f5-5386-4a87-be73-6fdb5cc7dd07) 5 | 6 | ![image](https://github.com/user-attachments/assets/d59aa1b8-d214-49fa-a217-2938323d5724) 7 | 8 | ![image](https://github.com/user-attachments/assets/3961ef77-84a5-4226-86b5-dc45342a347d) 9 | 10 | 11 | 12 | 13 | ![image](https://github.com/user-attachments/assets/e43d6af3-8698-49c8-8fe8-23ceda5824c7) 14 | 15 | Key Concepts: 16 | 17 | 1. Thinking Systems: 18 | - System 1: Fast, automatic (current LLMs) 19 | - System 2: Slow, deliberate (future goal) 20 | 21 | 2. Crew AI Implementation: 22 | ```python 23 | from crew_ai import Agent, Task, Crew 24 | 25 | # Create agents 26 | researcher = Agent( 27 | role="Market Researcher", 28 | goal="Analyze market demand", 29 | backstory="Expert in market analysis" 30 | ) 31 | 32 | # Define tasks 33 | task = Task( 34 | description="Analyze market potential", 35 | agent=researcher 36 | ) 37 | 38 | # Create crew 39 | crew = Crew( 40 | agents=[researcher], 41 | tasks=[task] 42 | ) 43 | ``` 44 | 45 | ![image](https://github.com/user-attachments/assets/5f761751-cf56-439a-abcc-27c340f612be) 46 | 47 | 48 | 3. Tools Integration: 49 | - Built-in tools: Google Search, Wikipedia 50 | - Custom tools: Reddit scraper, Email parser 51 | - Local models support: Llama, Mistral 52 | 53 | 4. Local Model Performance: 54 | - Best: Llama 13B, OpenChat 55 | - Average: Mistral, OpenHermes 56 | - Poor: Llama 7B, T5 57 | 58 | ![image](https://github.com/user-attachments/assets/9b002174-6148-46bb-a5a6-6e30a6c219dc) 59 | 60 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/fileServer.solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | You need to create an express HTTP server in Node.js which will handle the logic of a file server. 3 | - Use built in Node.js `fs` module 4 | 5 | The expected API endpoints are defined below, 6 | 1. GET /files - Returns a list of files present in `./files/` directory 7 | Response: 200 OK with an array of file names in JSON format. 8 | Example: GET http://localhost:3000/files 9 | 10 | 2. GET /file/:filename - Returns content of given file by name 11 | Description: Use the filename from the request path parameter to read the file from `./files/` directory 12 | Response: 200 OK with the file content as the response body if found, or 404 Not Found if not found. Should return `File not found` as text if file is not found 13 | Example: GET http://localhost:3000/file/example.txt 14 | 15 | - For any other route not defined in the server return 404 16 | 17 | Testing the server - run `npm run test-fileServer` command in terminal 18 | */ 19 | const express = require('express'); 20 | const fs = require('fs'); 21 | const path = require('path'); 22 | const app = express(); 23 | 24 | app.get('/files', (req, res) => { 25 | fs.readdir(path.join(__dirname, './files/'), (err, files) => { 26 | if (err) { 27 | return res.status(500).json({ error: 'Failed to retrieve files' }); 28 | } 29 | res.json(files); 30 | }); 31 | }); 32 | 33 | app.get('/file/:filename', (req, res) => { 34 | const filepath = path.join(__dirname, './files/', req.params.filename); 35 | 36 | fs.readFile(filepath, 'utf8', (err, data) => { 37 | if (err) { 38 | return res.status(404).send('File not found'); 39 | } 40 | res.send(data); 41 | }); 42 | }); 43 | 44 | app.all('*', (req, res) => { 45 | res.status(404).send('Route not found'); 46 | }); 47 | 48 | module.exports = app; 49 | -------------------------------------------------------------------------------- /CMR FDP/differences.md: -------------------------------------------------------------------------------- 1 | 2 | ![image](https://github.com/user-attachments/assets/b0ae5b52-c84a-49e3-9b26-f396f653e6fe) 3 | 4 | 5 | 6 | Key Distinctions: 7 | 8 | 1. Artificial Intelligence (Outermost Layer) 9 | - Definition: Systems that can perform tasks without human intervention 10 | - Real-world examples: 11 | - Netflix recommendation system 12 | - Self-driving cars 13 | - Smart home systems 14 | - Virtual assistants (Siri, Alexa) 15 | 16 | 2. Machine Learning (Second Layer) 17 | - Definition: Statistical tools for data analysis and prediction 18 | - Characteristics: Uses statistical methods to learn from data 19 | - Examples: 20 | - Spam email detection 21 | - Credit card fraud detection 22 | - Weather forecasting 23 | - Product recommendations 24 | 25 | 3. Deep Learning (Third Layer) 26 | - Definition: Neural networks mimicking human brain function 27 | - Key components: 28 | - ANN (Artificial Neural Networks) 29 | - CNN (Convolutional Neural Networks) for images 30 | - RNN (Recurrent Neural Networks) for sequences 31 | - Examples: 32 | - Face recognition 33 | - Voice assistants 34 | - Language translation 35 | - Medical image analysis 36 | 37 | 4. Generative AI (Innermost Layer) 38 | - Definition: Creates new content based on training data 39 | - Two main types: 40 | - Large Language Models (text): GPT, Claude, Llama 41 | - Large Image Models: DALL-E, Stable Diffusion 42 | - Examples: 43 | - ChatGPT generating text 44 | - DALL-E creating images 45 | - GitHub Copilot writing code 46 | - Midjourney generating art 47 | 48 | Key Distinctions: 49 | - AI vs ML: AI is the broader goal of machine autonomy; ML is the statistical approach to achieve it 50 | - ML vs DL: ML uses predefined features; DL automatically learns features through layers 51 | - DL vs Gen AI: DL focuses on recognition/classification; Gen AI creates new content 52 | 53 | -------------------------------------------------------------------------------- /MRU_FDP/differences.md: -------------------------------------------------------------------------------- 1 | 2 | ![image](https://github.com/user-attachments/assets/b0ae5b52-c84a-49e3-9b26-f396f653e6fe) 3 | 4 | 5 | 6 | Key Distinctions: 7 | 8 | 1. Artificial Intelligence (Outermost Layer) 9 | - Definition: Systems that can perform tasks without human intervention 10 | - Real-world examples: 11 | - Netflix recommendation system 12 | - Self-driving cars 13 | - Smart home systems 14 | - Virtual assistants (Siri, Alexa) 15 | 16 | 2. Machine Learning (Second Layer) 17 | - Definition: Statistical tools for data analysis and prediction 18 | - Characteristics: Uses statistical methods to learn from data 19 | - Examples: 20 | - Spam email detection 21 | - Credit card fraud detection 22 | - Weather forecasting 23 | - Product recommendations 24 | 25 | 3. Deep Learning (Third Layer) 26 | - Definition: Neural networks mimicking human brain function 27 | - Key components: 28 | - ANN (Artificial Neural Networks) 29 | - CNN (Convolutional Neural Networks) for images 30 | - RNN (Recurrent Neural Networks) for sequences 31 | - Examples: 32 | - Face recognition 33 | - Voice assistants 34 | - Language translation 35 | - Medical image analysis 36 | 37 | 4. Generative AI (Innermost Layer) 38 | - Definition: Creates new content based on training data 39 | - Two main types: 40 | - Large Language Models (text): GPT, Claude, Llama 41 | - Large Image Models: DALL-E, Stable Diffusion 42 | - Examples: 43 | - ChatGPT generating text 44 | - DALL-E creating images 45 | - GitHub Copilot writing code 46 | - Midjourney generating art 47 | 48 | Key Distinctions: 49 | - AI vs ML: AI is the broader goal of machine autonomy; ML is the statistical approach to achieve it 50 | - ML vs DL: ML uses predefined features; DL automatically learns features through layers 51 | - DL vs Gen AI: DL focuses on recognition/classification; Gen AI creates new content 52 | 53 | -------------------------------------------------------------------------------- /backend/Basic_FSD/script.js: -------------------------------------------------------------------------------- 1 | const taskInput = document.getElementById("taskInput"); 2 | const addButton = document.getElementById("addButton"); 3 | const taskList = document.getElementById("taskList"); 4 | 5 | const fetchTasks = async () => { 6 | const res = await fetch('http://localhost:5000/tasks'); 7 | const tasks = await res.json(); 8 | renderTasks(tasks); 9 | }; 10 | 11 | const renderTasks = (tasks) => { 12 | taskList.innerHTML = ""; 13 | tasks.forEach(task => { 14 | const taskItem = document.createElement("div"); 15 | taskItem.className = "task-item"; 16 | taskItem.innerHTML = ` 17 | ${task.text} 18 | 19 | 20 | `; 21 | taskList.appendChild(taskItem); 22 | }); 23 | }; 24 | 25 | const addTask = async () => { 26 | if (!taskInput.value) return; 27 | 28 | await fetch('http://localhost:5000/tasks', { 29 | method: 'POST', 30 | headers: { 'Content-Type': 'application/json' }, 31 | body: JSON.stringify({ text: taskInput.value }), 32 | }); 33 | 34 | taskInput.value = ""; 35 | fetchTasks(); 36 | }; 37 | 38 | const updateTask = async (id) => { 39 | const newTaskText = prompt("Edit your task:"); 40 | if (!newTaskText) return; 41 | 42 | await fetch(`http://localhost:5000/tasks/${id}`, { 43 | method: 'PUT', 44 | headers: { 'Content-Type': 'application/json' }, 45 | body: JSON.stringify({ text: newTaskText }), 46 | }); 47 | 48 | fetchTasks(); 49 | }; 50 | 51 | const deleteTask = async (id) => { 52 | await fetch(`http://localhost:5000/tasks/${id}`, { method: 'DELETE' }); 53 | fetchTasks(); 54 | }; 55 | 56 | addButton.addEventListener("click", addTask); 57 | fetchTasks(); 58 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React, {useEffect} from 'react'; 2 | import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'; 3 | import {RecoilRoot} from 'recoil'; 4 | import Login from './Components/Login'; 5 | import Signup from './Components/Signup'; 6 | import TodoList from './Components/TodoList'; 7 | import { useNavigate } from 'react-router-dom'; 8 | import { useSetRecoilState } from 'recoil'; 9 | import { authState } from './store/authState.js'; 10 | 11 | function App() { 12 | return ( 13 | 14 | 15 | 16 | 17 | } /> 18 | } /> 19 | } /> 20 | } /> 21 | 22 | 23 | 24 | ); 25 | } 26 | 27 | function InitState() { 28 | const setAuth = useSetRecoilState(authState); 29 | const navigate = useNavigate(); 30 | 31 | const init = async () => { 32 | const token = localStorage.getItem("token"); 33 | try { 34 | const response = await fetch('http://localhost:3000/auth/me', { 35 | headers: { Authorization: `Bearer ${token}` } 36 | }); 37 | const data = await response.json(); 38 | if (data.username) { 39 | setAuth({ token: data.token, username: data.username }); 40 | navigate("/todos"); 41 | } else { 42 | navigate("/login"); 43 | } 44 | } catch (e) { 45 | navigate("/login"); 46 | } 47 | } 48 | useEffect(() => { 49 | init(); 50 | }, []) 51 | return <> 52 | } 53 | 54 | export default App; 55 | 56 | -------------------------------------------------------------------------------- /assignments/js/tests/palindrome.test.js: -------------------------------------------------------------------------------- 1 | const isPalindrome = require('../medium/palindrome'); 2 | 3 | describe('isPalindrome', () => { 4 | test('returns true for palindromes', () => { 5 | expect(isPalindrome('level')).toBe(true); 6 | expect(isPalindrome('racecar')).toBe(true); 7 | }); 8 | 9 | test('returns false for non-palindromes', () => { 10 | expect(isPalindrome('hello')).toBe(false); 11 | expect(isPalindrome('openai')).toBe(false); 12 | expect(isPalindrome('abcde')).toBe(false); 13 | }); 14 | 15 | test('returns true for an empty string', () => { 16 | expect(isPalindrome('')).toBe(true); 17 | }); 18 | 19 | test('handles case-insensitivity correctly', () => { 20 | expect(isPalindrome('Anna')).toBe(true); 21 | expect(isPalindrome('aNnA')).toBe(true); 22 | expect(isPalindrome('Madam')).toBe(true); 23 | expect(isPalindrome('MaDaM')).toBe(true); 24 | expect(isPalindrome('RaCeCaR')).toBe(true); 25 | expect(isPalindrome('rAcEcAr')).toBe(true); 26 | }); 27 | 28 | test('returns true for single-character strings', () => { 29 | expect(isPalindrome('a')).toBe(true); 30 | expect(isPalindrome('z')).toBe(true); 31 | expect(isPalindrome('5')).toBe(true); 32 | expect(isPalindrome('@')).toBe(true); 33 | }); 34 | 35 | test('returns true for strings with spaces', () => { 36 | expect(isPalindrome('race car')).toBe(true); 37 | expect( 38 | isPalindrome('A man a plan a canal Panama') 39 | ).toBe(true); 40 | expect( 41 | isPalindrome('Was it a car or a cat I saw') 42 | ).toBe(true); 43 | }); 44 | 45 | test('returns true for strings with punctuation marks', () => { 46 | expect( 47 | isPalindrome('Able, was I ere I saw Elba!') 48 | ).toBe(true); 49 | expect( 50 | isPalindrome('Eva, can I see bees in a cave?') 51 | ).toBe(true); 52 | expect(isPalindrome('Mr. Owl ate my metal worm.')).toBe( 53 | true 54 | ); 55 | expect( 56 | isPalindrome('A man, a plan, a canal. Panama') 57 | ).toBe(true); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/todoServer.solution.simple.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const bodyParser = require('body-parser'); 3 | 4 | const app = express(); 5 | 6 | app.use(bodyParser.json()); 7 | 8 | let todos = []; 9 | 10 | function findIndex(arr, id) { 11 | for (let i = 0; i < arr.length; i++) { 12 | if (arr[i].id === id) return i; 13 | } 14 | return -1; 15 | } 16 | 17 | function removeAtIndex(arr, index) { 18 | let newArray = []; 19 | for (let i = 0; i < arr.length; i++) { 20 | if (i !== index) newArray.push(arr[i]); 21 | } 22 | return newArray; 23 | } 24 | 25 | app.get('/todos', (req, res) => { 26 | res.json(todos); 27 | }); 28 | 29 | app.get('/todos/:id', (req, res) => { 30 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 31 | if (todoIndex === -1) { 32 | res.status(404).send(); 33 | } else { 34 | res.json(todos[todoIndex]); 35 | } 36 | }); 37 | 38 | app.post('/todos', (req, res) => { 39 | const newTodo = { 40 | id: Math.floor(Math.random() * 1000000), // unique random id 41 | title: req.body.title, 42 | description: req.body.description 43 | }; 44 | todos.push(newTodo); 45 | res.status(201).json(newTodo); 46 | }); 47 | 48 | app.put('/todos/:id', (req, res) => { 49 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 50 | if (todoIndex === -1) { 51 | res.status(404).send(); 52 | } else { 53 | todos[todoIndex].title = req.body.title; 54 | todos[todoIndex].description = req.body.description; 55 | res.json(todos[todoIndex]); 56 | } 57 | }); 58 | 59 | app.delete('/todos/:id', (req, res) => { 60 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 61 | if (todoIndex === -1) { 62 | res.status(404).send(); 63 | } else { 64 | todos = removeAtIndex(todos, todoIndex); 65 | res.status(200).send(); 66 | } 67 | }); 68 | 69 | // for all other routes, return 404 70 | app.use((req, res, next) => { 71 | res.status(404).send(); 72 | }); 73 | 74 | module.exports = app; 75 | -------------------------------------------------------------------------------- /crewai_experiments/README.md: -------------------------------------------------------------------------------- 1 | # CREWAI experiments 2 | 3 | ------ 4 | 5 | For my experiments with CrewAI, I decided to try 3 different projects, starting from the easiest to the most complex. The aim of the experiments was to have a team of AI agents do following work for me: 6 | 1. Examine my Startup idea 7 | 2. Build AI newsletter with Google SERP 8 | 3. Build AI newsletter with Reddit Scraper 9 | 4. Email classifier [WIP] 10 | 11 | ## For my experiements I've tried following LLMs: 12 | --- 13 | 14 | ### Available through API calls: 15 | 16 | 1. OpenAI -> GPT-4 17 | 2. Gemini Pro 18 | 19 | ### Local Models through Ollama + rating of how they performed: 20 | 21 | 1. **Mistral 7B** 22 | - Nice, coherent results 23 | - Didn't understand that it should use scraping tool for the output 24 | - Result is a bunch of generic text from training data 25 | 2. **Mistral 7B instruct** 26 | - Nice, coherent results, a lot of emojis 27 | - Didn't use any scraping tool for the output 28 | - Result is a bunch of generic text from training data. 29 | 3. **Open Chat 3.5 7B** 30 | - The best and most "newsletter-y" results 31 | - But again, didn't use any tool, so generic content 32 | 4. **Nous Hermes 7B** 33 | - Ok results 34 | - didn't use any tool 35 | - generic content 36 | 5. **Open Hermes 2.5 7B** 37 | - The tone and style of writing is great 38 | - but generic content 39 | - didn't understand that it needs to use tools 40 | 6. **Starling 7B** 41 | - Ok results 42 | - didn't use any tool 43 | - generic content 44 | 7. **Llama 2 13B** 45 | - The only model that "understood" what the task is 46 | - but the text wasn't coherent enough, didn's sound like a newsletter 47 | 8. **Llama 2 13B chat** 48 | - Didn't understand the task or produce any output 49 | 9. **Llama 2 13B text** 50 | - Didn't understand the task or produce any output 51 | 10. **Llama 2 7B** 52 | - not coherent 53 | - didn't use any tool 54 | - no output 55 | 11. **Llama 2 7B text** 56 | - No actual output 57 | - didn't use any tool 58 | - generic content 59 | 12. **Llama 2 7B chat** 60 | - Didn't use any tool 61 | - generic content 62 | 13. **Phi-2** 63 | - The smallest model ran into biggest problems 64 | - Lost track of what it's suppose to do, no output -------------------------------------------------------------------------------- /assignments/nodejs/authenticationServer.js: -------------------------------------------------------------------------------- 1 | /** 2 | You need to create a HTTP server in Node.js which will handle the logic of an authentication server. 3 | - Don't need to use any database to store the data. 4 | 5 | - Save the users and their signup/login data in an array in a variable 6 | - You can store the passwords in plain text (as is) in the variable for now 7 | 8 | The expected API endpoints are defined below, 9 | 1. POST /signup - User Signup 10 | Description: Allows users to create an account. This should be stored in an array on the server, and a unique id should be generated for every new user that is added. 11 | Request Body: JSON object with username, password, firstName and lastName fields. 12 | Response: 201 Created if successful, or 400 Bad Request if the username already exists. 13 | Example: POST http://localhost:3000/signup 14 | 15 | 2. POST /login - User Login 16 | Description: Gets user back their details like firstname, lastname and id 17 | Request Body: JSON object with username and password fields. 18 | Response: 200 OK with an authentication token in JSON format if successful, or 401 Unauthorized if the credentials are invalid. 19 | Example: POST http://localhost:3000/login 20 | 21 | 3. GET /data - Fetch all user's names and ids from the server (Protected route) 22 | Description: Gets details of all users like firstname, lastname and id in an array format. Returned object should have a key called users which contains the list of all users with their email/firstname/lastname. 23 | The users username and password should be fetched from the headers and checked before the array is returned 24 | Response: 200 OK with the protected data in JSON format if the username and password in headers are valid, or 401 Unauthorized if the username and password are missing or invalid. 25 | Example: GET http://localhost:3000/data 26 | 27 | - For any other route not defined in the server return 404 28 | 29 | Testing the server - run `npm run test-authenticationServer` command in terminal 30 | */ 31 | 32 | const express = require("express") 33 | const PORT = 3000; 34 | const app = express(); 35 | // write your logic here, DONT WRITE app.listen(3000) when you're running tests, the tests will automatically start the server 36 | 37 | module.exports = app; 38 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/README.md: -------------------------------------------------------------------------------- 1 | ## Assignment 2 2 | Move this JS project to typescript. 3 | 4 | - It's harder to move a react project to TS, although totally possible with the naive approach of moving files from jsx => tsx, and then fixing all the errors. 5 | - It's easier to re-bootstrap the initial configuration using vite, and then move the files over. 6 | - This is because the initial configuration is a lot of work, and it's easier to just re-bootstrap it. 7 | - Go one folder below this folder (go to week-7) 8 | - Run npm create vite@latest 9 | - Select react 10 | - Select typescript 11 | - Name the new folder `assignment-2-solution` 12 | - Notice how the tsconfig.json has a bunch of things we haven't seen before. This is why bootstraping the new app is much easier than incrementally creating a new tsconfig.json. 13 | - Bring dependencies to the new project - 14 | - npm install recoil 15 | - npm install react-router-dom 16 | - Now start moving components over. Make sure you're replacing 17 | - .jsx => .tsx 18 | - .js => .ts 19 | - After you've moved all the files over, things should just work 20 | - At this point a good question to ask is what benefit did we get after moving from JS to TS in react? It seems like we just changed the file names, didn't add any types. 21 | - The answer is that we can now add types incrementally. We can start by adding types to the components. 22 | - Also create a type for all the requests you are making to the backend. This should be the same as the one you created for your backend app. 23 | - For example, a type called SignupRequest which looks like this - 24 | - ```ts 25 | export type SignupRequest = { 26 | username: string; 27 | password: string; 28 | }; 29 | ``` 30 | - Create a type for Todo which the backend returns to you. Use the type in all the places where you get back a todo from the backend. 31 | 32 | A good question to ask in this assignment is what benefit does TS give us in react? It seems like we just changed the file names, and forcefully added some types 33 | The answer is that as your app gets more complex, and you send down props through your app, you will start to see the benefit of TS. You will be able to catch bugs at compile time, and your react app wont crash at runtime. This is a huge benefit, and it's worth the effort of moving to TS. -------------------------------------------------------------------------------- /assignments/js/tests/todo-list.test.js: -------------------------------------------------------------------------------- 1 | const Todo = require('../hard/todo-list'); 2 | 3 | describe('Todo', () => { 4 | let todoList; 5 | 6 | beforeEach(() => { 7 | todoList = new Todo(); 8 | }); 9 | 10 | test('add and getAll', () => { 11 | todoList.add('Task 1'); 12 | todoList.add('Task 2'); 13 | todoList.add('Task 3'); 14 | 15 | expect(todoList.getAll()).toEqual([ 16 | 'Task 1', 17 | 'Task 2', 18 | 'Task 3', 19 | ]); 20 | }); 21 | 22 | test('remove', () => { 23 | todoList.add('Task 1'); 24 | todoList.add('Task 2'); 25 | todoList.add('Task 3'); 26 | 27 | todoList.remove(1); 28 | expect(todoList.getAll()).toEqual(['Task 1', 'Task 3']); 29 | 30 | todoList.remove(0); 31 | expect(todoList.getAll()).toEqual(['Task 3']); 32 | 33 | todoList.remove(2); 34 | expect(todoList.getAll()).toEqual(['Task 3']); 35 | }); 36 | 37 | test('update', () => { 38 | todoList.add('Task 1'); 39 | todoList.add('Task 2'); 40 | todoList.add('Task 3'); 41 | 42 | todoList.update(1, 'Updated Task 2'); 43 | expect(todoList.get(1)).toBe('Updated Task 2'); 44 | 45 | todoList.update(3, 'Invalid Task'); 46 | expect(todoList.getAll()).toEqual([ 47 | 'Task 1', 48 | 'Updated Task 2', 49 | 'Task 3', 50 | ]); 51 | }); 52 | 53 | test('get', () => { 54 | todoList.add('Task 1'); 55 | todoList.add('Task 2'); 56 | todoList.add('Task 3'); 57 | 58 | expect(todoList.get(0)).toBe('Task 1'); 59 | expect(todoList.get(2)).toBe('Task 3'); 60 | expect(todoList.get(3)).toBeNull(); 61 | }); 62 | 63 | test('clear', () => { 64 | todoList.add('Task 1'); 65 | todoList.add('Task 2'); 66 | todoList.add('Task 3'); 67 | 68 | todoList.clear(); 69 | expect(todoList.getAll()).toEqual([]); 70 | }); 71 | 72 | test('remove and update with invalid indexes', () => { 73 | todoList.add('Task 1'); 74 | todoList.add('Task 2'); 75 | 76 | todoList.remove(5); 77 | expect(todoList.getAll()).toEqual(['Task 1', 'Task 2']); 78 | 79 | todoList.update(3, 'Updated Task'); 80 | expect(todoList.getAll()).toEqual(['Task 1', 'Task 2']); 81 | }); 82 | 83 | test('add duplicate tasks', () => { 84 | todoList.add('Task 1'); 85 | todoList.add('Task 2'); 86 | todoList.add('Task 1'); 87 | todoList.add('Task 3'); 88 | 89 | expect(todoList.getAll()).toEqual([ 90 | 'Task 1', 91 | 'Task 2', 92 | 'Task 1', 93 | 'Task 3', 94 | ]); 95 | }); 96 | }); 97 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/script-less-ugly.js: -------------------------------------------------------------------------------- 1 | 2 | function createDomElements(data) { 3 | var parentElement = document.getElementById("mainArea"); 4 | 5 | // Get the current children of the parent element and convert it to an array 6 | var currentChildren = Array.from(parentElement.children); 7 | 8 | let added = 0, deleted = 0, updated = 0; 9 | // Process each item in the data array 10 | data.forEach(function(item) { 11 | // Check if a child with this ID already exists 12 | var existingChild = currentChildren.find(function(child) { 13 | return child.dataset.id === String(item.id); 14 | }); 15 | 16 | if (existingChild) { 17 | updated++; 18 | // If it exists, update it 19 | existingChild.children[0].innerHTML = item.title; 20 | existingChild.children[1].innerHTML = item.description; 21 | // Remove it from the currentChildren array 22 | currentChildren = currentChildren.filter(function(child) { 23 | return child !== existingChild; 24 | }); 25 | } else { 26 | added++; 27 | // If it doesn't exist, create it 28 | var childElement = document.createElement("div"); 29 | childElement.dataset.id = item.id; // Store the ID on the element for future lookups 30 | 31 | var grandChildElement1 = document.createElement("span"); 32 | grandChildElement1.innerHTML = item.title 33 | 34 | var grandChildElement2 = document.createElement("span"); 35 | grandChildElement2.innerHTML = item.description 36 | 37 | var grandChildElement3 = document.createElement("button"); 38 | grandChildElement3.innerHTML = "Delete" 39 | grandChildElement3.setAttribute("onclick", "deleteTodo(" + item.id + ")") 40 | 41 | childElement.appendChild(grandChildElement1) 42 | childElement.appendChild(grandChildElement2) 43 | childElement.appendChild(grandChildElement3) 44 | parentElement.appendChild(childElement); 45 | } 46 | }); 47 | 48 | // Any children left in the currentChildren array no longer exist in the data, so remove them 49 | currentChildren.forEach(function(child) { 50 | deleted++; 51 | parentElement.removeChild(child); 52 | }); 53 | 54 | console.log(added); 55 | console.log(updated); 56 | console.log(deleted); 57 | } 58 | 59 | 60 | window.setInterval(() => { 61 | let todos = []; 62 | for (let i = 0; i imports to fix these errors. This is related to a bug bug in TS (https://stackoverflow.com/questions/35758584/cannot-redeclare-block-scoped-variable) 17 | - For example, convert 18 | - `const mongoose = require('mongoose');` to 19 | - `import mongoose from 'mongoose';` 20 | - Same thing for exports, export using the modern ES6 syntax 21 | - `module.exports = mongoose.model('Todo', todoSchema);` to 22 | - `export default mongoose.model('Todo', todoSchema);` 23 | - Now typescript shouldnt complain, but this isn't the end. We still have to flip on strict to actually see errors. 24 | - Check out the errors that you see 25 | - Next, run `npm install -D @types/node` to install the types for node. 26 | - Next, run `npm install -D @types/express` to install the types for express. 27 | - Next, run `npm install -D @types/mongoose` to install the types for mongoose. 28 | - You will see a bunch of `Parameter 'req' implicitly has an 'any' type.` errors. Fix these by adding types to all the functions. 29 | - Express exports the Request and Response types, use them to type the req and res params. 30 | - If you ever get stuck, initially you can use the any type 31 | - You can also just flip noImplicitAny to false in tsconfig, but that's cheating. 32 | - You will see req.userId complains everywhere, and rightfully so. We've added userId key to an object that doesn't expect it. Fix this by sending over the id via the headers. 33 | - Create types for the inputs to all routes (for eg User, Todo) and use them when u decode the body. 34 | - Try running tsc now, you should see no errors. 35 | -------------------------------------------------------------------------------- /AppointmentApp/server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const mongoose = require("mongoose"); 3 | const bodyParser = require("body-parser"); 4 | const cors = require("cors"); 5 | 6 | const app = express(); 7 | app.use(bodyParser.json()); 8 | app.use(cors()); 9 | 10 | // MongoDB connection 11 | mongoose.connect("mongodb://localhost:27017/appointments", { 12 | useNewUrlParser: true, 13 | useUnifiedTopology: true, 14 | }); 15 | 16 | // Models 17 | const Appointment = mongoose.model("Appointment", { 18 | name: String, 19 | reason: String, 20 | time: String, 21 | date: String, 22 | status: { type: String, default: "upcoming" }, 23 | }); 24 | 25 | const Availability = mongoose.model("Availability", { 26 | date: String, 27 | slots: [String], 28 | }); 29 | 30 | // Routes 31 | // 1. Get all appointments 32 | app.get("/appointments", async (req, res) => { 33 | const appointments = await Appointment.find(); 34 | res.json(appointments); 35 | }); 36 | 37 | // 2. Get appointments for a particular day 38 | app.get("/appointments/day/:date", async (req, res) => { 39 | const { date } = req.params; 40 | const appointments = await Appointment.find({ date }); 41 | res.json(appointments); 42 | }); 43 | 44 | // 3. Add available time slots 45 | app.post("/availability", async (req, res) => { 46 | const { date, slots } = req.body; 47 | const availability = new Availability({ date, slots }); 48 | await availability.save(); 49 | res.json({ message: "Availability added!" }); 50 | }); 51 | 52 | // 4. Book an appointment 53 | app.post("/book", async (req, res) => { 54 | const { name, reason, time, date } = req.body; 55 | const appointment = new Appointment({ name, reason, time, date }); 56 | await appointment.save(); 57 | res.json({ message: "Appointment booked!" }); 58 | }); 59 | 60 | // 5. Get available slots for a date 61 | app.get("/availability/:date", async (req, res) => { 62 | const { date } = req.params; 63 | const availability = await Availability.findOne({ date }); 64 | res.json(availability || { slots: [] }); 65 | }); 66 | 67 | // 6. Cancel an appointment 68 | app.delete("/appointments/:id", async (req, res) => { 69 | const { id } = req.params; 70 | await Appointment.findByIdAndDelete(id); 71 | res.json({ message: "Appointment canceled!" }); 72 | }); 73 | 74 | // 7. Reschedule an appointment 75 | app.put("/appointments/:id", async (req, res) => { 76 | const { id } = req.params; 77 | const { time, date } = req.body; 78 | await Appointment.findByIdAndUpdate(id, { time, date }); 79 | res.json({ message: "Appointment rescheduled!" }); 80 | }); 81 | 82 | // Start server 83 | const PORT = 5000; 84 | app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); 85 | -------------------------------------------------------------------------------- /attendance_app/server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const fs = require("fs"); 3 | const path = require("path"); 4 | const cors = require("cors"); 5 | const mongoose = require("mongoose") 6 | 7 | const app = express(); 8 | const PORT = 3000; 9 | // const dataFile = path.join(__dirname, "students.json"); 10 | 11 | mongoose.connect("mongodb://localhost:27017/attendance", { useNewUrlParser: true, useUnifiedTopology: true}) 12 | console.log("Connected to MongoDB"); 13 | app.use(express.json()); 14 | app.use(cors()); 15 | 16 | function readData() { 17 | // if (!fs.existsSync(dataFile)) return []; 18 | // return JSON.parse(fs.readFileSync(dataFile)); 19 | // mongodb read 20 | return mongoose.connection.collection("students").find({}).toArray([]); 21 | } 22 | 23 | function writeData(data) { 24 | // fs.writeFileSync(dataFile, JSON.stringify(data, null, 2)); 25 | // mongodb write 26 | mongoose.connection.collection("students").insertMany(data); 27 | 28 | } 29 | 30 | app.get("/students", (req, res) => { 31 | res.json(readData()); 32 | }); 33 | 34 | app.post("/students", async (req, res) => { 35 | const newStudent = { id: Date.now(), ...req.body }; 36 | 37 | delete newStudent._id; 38 | 39 | await mongoose.connection.collection("students").insertOne(newStudent); // ✅ Avoids duplicate key error 40 | 41 | res.status(201).json(newStudent); 42 | 43 | }); 44 | 45 | app.put("/students/:id", async(req, res) => { 46 | const studentId = req.params.id; 47 | const updatedStudent = { ...req.body }; 48 | mongoose.connection.collection("students").findOneAndUpdate( 49 | 50 | { _id: new ObjectId(studentId) }, // Find by MongoDB _id 51 | { $set: updatedStudent }, // Update only the fields provided 52 | { returnDocument: "after" } // Return updated document 53 | 54 | ); 55 | res.json(updatedStudent); 56 | 57 | }); 58 | 59 | app.delete("/students/:id", (req, res) => { 60 | const students = readData(); 61 | const updatedStudents = students.filter(s => s.id != req.params.id); 62 | writeData(updatedStudents); 63 | res.status(204).send(); 64 | }); 65 | 66 | app.get("/download", (req, res) => { 67 | const students = readData(); 68 | const csvData = "Roll Number,Name,Attendance\n" + students.map(s => `${s.rollNumber},${s.name},${s.attendance}`).join("\n"); 69 | 70 | const filePath = path.join(__dirname, `attendance_${Date.now()}.csv`); 71 | fs.writeFileSync(filePath, csvData); 72 | res.download(filePath, err => { 73 | if (err) console.error(err); 74 | fs.unlinkSync(filePath); // Delete the file after sending 75 | //mongo delete 76 | mongoose.connection.collection("students").deleteMany({}); 77 | }); 78 | }); 79 | 80 | app.listen(PORT, () => { 81 | console.log(`Server running on http://localhost:${PORT}`); 82 | }); 83 | -------------------------------------------------------------------------------- /assignments/js/tests/expenditure-analysis.test.js: -------------------------------------------------------------------------------- 1 | const calculateTotalSpentByCategory = require('../easy/expenditure-analysis'); 2 | 3 | describe('calculateTotalSpentByCategory', () => { 4 | test('returns the correct total spent for a single transaction', () => { 5 | const transactions = [ 6 | { 7 | id: 1, 8 | timestamp: 1656076800000, 9 | price: 10, 10 | category: 'Food', 11 | itemName: 'Pizza', 12 | }, 13 | ]; 14 | 15 | const result = 16 | calculateTotalSpentByCategory(transactions); 17 | 18 | expect(result).toEqual([ 19 | { category: 'Food', totalSpent: 10 }, 20 | ]); 21 | }); 22 | 23 | test('returns the correct total spent for each category', () => { 24 | const transactions = [ 25 | { 26 | id: 1, 27 | timestamp: 1656076800000, 28 | price: 10, 29 | category: 'Food', 30 | itemName: 'Pizza', 31 | }, 32 | { 33 | id: 2, 34 | timestamp: 1656259600000, 35 | price: 20, 36 | category: 'Food', 37 | itemName: 'Burger', 38 | }, 39 | { 40 | id: 3, 41 | timestamp: 1656019200000, 42 | price: 15, 43 | category: 'Clothing', 44 | itemName: 'T-Shirt', 45 | }, 46 | { 47 | id: 4, 48 | timestamp: 1656364800000, 49 | price: 30, 50 | category: 'Electronics', 51 | itemName: 'Headphones', 52 | }, 53 | { 54 | id: 5, 55 | timestamp: 1656105600000, 56 | price: 25, 57 | category: 'Clothing', 58 | itemName: 'Jeans', 59 | }, 60 | ]; 61 | 62 | const result = 63 | calculateTotalSpentByCategory(transactions); 64 | 65 | expect(result).toEqual([ 66 | { category: 'Food', totalSpent: 30 }, 67 | { category: 'Clothing', totalSpent: 40 }, 68 | { category: 'Electronics', totalSpent: 30 }, 69 | ]); 70 | }); 71 | 72 | test('returns an empty array when given an empty input', () => { 73 | const transactions = []; 74 | const result = 75 | calculateTotalSpentByCategory(transactions); 76 | expect(result).toEqual([]); 77 | }); 78 | 79 | test('returns the correct total spent when multiple transactions have the same category', () => { 80 | const transactions = [ 81 | { 82 | id: 1, 83 | timestamp: 1656076800000, 84 | price: 10, 85 | category: 'Food', 86 | itemName: 'Pizza', 87 | }, 88 | { 89 | id: 2, 90 | timestamp: 1656105600000, 91 | price: 20, 92 | category: 'Food', 93 | itemName: 'Burger', 94 | }, 95 | { 96 | id: 3, 97 | timestamp: 1656134400000, 98 | price: 30, 99 | category: 'Food', 100 | itemName: 'Sushi', 101 | }, 102 | ]; 103 | 104 | const result = 105 | calculateTotalSpentByCategory(transactions); 106 | 107 | expect(result).toEqual([ 108 | { category: 'Food', totalSpent: 60 }, 109 | ]); 110 | }); 111 | }); 112 | -------------------------------------------------------------------------------- /mongodb/server.js: -------------------------------------------------------------------------------- 1 | //imports 2 | const express = require("express"); 3 | const mongoose = require("mongoose"); 4 | const cors = require("cors"); 5 | const bodyParser = require("body-parser"); 6 | 7 | const app = express(); 8 | const PORT = 3000; 9 | 10 | // Middleware 11 | app.use(cors()); 12 | app.use(bodyParser.json()); 13 | 14 | // MongoDB Connection 15 | // mongoose 16 | // .connect( , ) 17 | // .then(() => console.log("MongoDB Connected")) 18 | // .catch((err) => console.error("MongoDB Connection Error:", err)); 19 | 20 | 21 | // 22 | mongoose.connect("mongodb://localhost:27017/3feb", { 23 | useNewUrlParser: true, 24 | useUnifiedTopology: true, 25 | }).then(() => console.log("MongoDB Connected")) 26 | .catch((err) => console.error("MongoDB Connection Error:", err)); 27 | 28 | 29 | // Define a Mongoose Schema & Model 30 | const ItemSchema = new mongoose.Schema({ 31 | name: String, 32 | price: Number, 33 | }); 34 | 35 | const Item = mongoose.model("Item", ItemSchema); 36 | 37 | // CRUD Routes 38 | 39 | // Create - Add New Item 40 | app.post("/items", async (req, res) => { 41 | try { 42 | const newItem = new Item(req.body); 43 | const savedItem = await newItem.save(); 44 | res.status(201).json(savedItem); 45 | } catch (err) { 46 | res.status(400).json({ error: err.message }); 47 | } 48 | }); 49 | 50 | // Read - Get All Items 51 | app.get("/items", async (req, res) => { 52 | try { 53 | const items = await Item.find(); 54 | res.json(items); 55 | } catch (err) { 56 | res.status(500).json({ error: err.message }); 57 | } 58 | }); 59 | 60 | // Read - Get Single Item by ID 61 | app.get("/items/:id", async (req, res) => { 62 | try { 63 | const item = await Item.findById(req.params.id); 64 | if (!item) return res.status(404).json({ message: "Item not found" }); 65 | res.json(item); 66 | } catch (err) { 67 | res.status(500).json({ error: err.message }); 68 | } 69 | }); 70 | 71 | // Update - Modify Item by ID 72 | app.put("/items/:id", async (req, res) => { 73 | try { 74 | const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); 75 | if (!updatedItem) return res.status(404).json({ message: "Item not found" }); 76 | res.json(updatedItem); 77 | } catch (err) { 78 | res.status(500).json({ error: err.message }); 79 | } 80 | }); 81 | 82 | // Delete - Remove Item by ID 83 | app.delete("/items/:id", async (req, res) => { 84 | try { 85 | const deletedItem = await Item.findByIdAndDelete(req.params.id); 86 | if (!deletedItem) return res.status(404).json({ message: "Item not found" }); 87 | res.json({ message: "Item deleted successfully" }); 88 | } catch (err) { 89 | res.status(500).json({ error: err.message }); 90 | } 91 | }); 92 | 93 | // Start Server 94 | app.listen(PORT, () => { 95 | console.log(`Server running on port ${PORT}`); 96 | }); 97 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/script-vdom.js: -------------------------------------------------------------------------------- 1 | let vDOM = []; // Our initial vDOM is an empty array 2 | 3 | function createDomElements() { 4 | var parentElement = document.getElementById("mainArea"); 5 | 6 | var currentChildren = Array.from(parentElement.children); 7 | 8 | let added = 0, deleted = 0, updated = 0; 9 | // Now, we'll compare our new vDOM to our actual DOM 10 | vDOM.forEach(function(item) { 11 | // Check if a child with this ID already exists in the DOM 12 | var existingChild = currentChildren.find(function(child) { 13 | return child.dataset.id === String(item.id); 14 | }); 15 | 16 | if (existingChild) { 17 | updated++; 18 | // If it exists, update it 19 | existingChild.children[0].innerHTML = item.title; 20 | existingChild.children[1].innerHTML = item.description; 21 | // Remove it from the currentChildren array 22 | currentChildren = currentChildren.filter(function(child) { 23 | return child !== existingChild; 24 | }); 25 | } else { 26 | added++; 27 | // If it doesn't exist in the DOM, create it 28 | var childElement = document.createElement("div"); 29 | childElement.dataset.id = item.id; // Store the ID on the element for future lookups 30 | 31 | var grandChildElement1 = document.createElement("span"); 32 | grandChildElement1.innerHTML = item.title; 33 | 34 | var grandChildElement2 = document.createElement("span"); 35 | grandChildElement2.innerHTML = item.description; 36 | 37 | var grandChildElement3 = document.createElement("button"); 38 | grandChildElement3.innerHTML = "Delete"; 39 | grandChildElement3.setAttribute("onclick", "deleteTodo(" + item.id + ")"); 40 | 41 | childElement.appendChild(grandChildElement1); 42 | childElement.appendChild(grandChildElement2); 43 | childElement.appendChild(grandChildElement3); 44 | parentElement.appendChild(childElement); 45 | } 46 | }); 47 | 48 | // Any children left in the currentChildren array no longer exist in the data, so remove them 49 | currentChildren.forEach(function(child) { 50 | deleted++; 51 | parentElement.removeChild(child); 52 | }); 53 | 54 | console.log(added); 55 | console.log(updated); 56 | console.log(deleted); 57 | } 58 | 59 | 60 | function updateVirtualDom(data) { 61 | vDOM = data.map(item => { 62 | return { 63 | id: item.id, 64 | title: item.title, 65 | description: item.description 66 | }; 67 | }); 68 | createDomElements(vDOM); 69 | } 70 | window.setInterval(() => { 71 | let todos = []; 72 | for (let i = 0; i { 62 | return { 63 | id: item.id, 64 | title: item.title, 65 | description: item.description 66 | }; 67 | }); 68 | } 69 | window.setInterval(() => { 70 | let todos = []; 71 | for (let i = 0; i { 83 | createDomElements(); 84 | }, 1000); 85 | 86 | 87 | -------------------------------------------------------------------------------- /assignments/react/01-reconciler/script-vdom-comparision.js: -------------------------------------------------------------------------------- 1 | let vDOM = []; // Our initial vDOM is an empty array 2 | 3 | function createDomElements(existingDOM, currentDOM) { 4 | var parentElement = document.getElementById("mainArea"); 5 | 6 | let added = 0, deleted = 0, updated = 0; 7 | 8 | // Now, we'll compare our new vDOM to our old vDOM 9 | currentDOM.forEach(function(item) { 10 | // Check if an element with this ID already exists in the old vDOM 11 | var existingItem = existingDOM.find(function(oldItem) { 12 | return oldItem.id === item.id; 13 | }); 14 | 15 | if (existingItem) { 16 | updated++; 17 | // If it exists, update it 18 | var existingChild = document.querySelector(`[data-id='${item.id}']`); 19 | existingChild.children[0].innerHTML = item.title; 20 | existingChild.children[1].innerHTML = item.description; 21 | } else { 22 | added++; 23 | // If it doesn't exist in the DOM, create it 24 | var childElement = document.createElement("div"); 25 | childElement.dataset.id = item.id; // Store the ID on the element for future lookups 26 | 27 | var grandChildElement1 = document.createElement("span"); 28 | grandChildElement1.innerHTML = item.title; 29 | 30 | var grandChildElement2 = document.createElement("span"); 31 | grandChildElement2.innerHTML = item.description; 32 | 33 | var grandChildElement3 = document.createElement("button"); 34 | grandChildElement3.innerHTML = "Delete"; 35 | grandChildElement3.setAttribute("onclick", "deleteTodo(" + item.id + ")"); 36 | 37 | childElement.appendChild(grandChildElement1); 38 | childElement.appendChild(grandChildElement2); 39 | childElement.appendChild(grandChildElement3); 40 | parentElement.appendChild(childElement); 41 | } 42 | }); 43 | 44 | // Any item left in the existingDOM array no longer exist in the data, so remove them 45 | existingDOM.forEach(function(oldItem) { 46 | if (!currentDOM.some(item => item.id === oldItem.id)) { 47 | deleted++; 48 | var childToRemove = document.querySelector(`[data-id='${oldItem.id}']`); 49 | parentElement.removeChild(childToRemove); 50 | } 51 | }); 52 | 53 | console.log(added); 54 | console.log(updated); 55 | console.log(deleted); 56 | } 57 | 58 | function updateVirtualDom(data) { 59 | let existingDOM = [...vDOM]; // Save the existing state of vDOM 60 | vDOM = data.map(item => { 61 | return { 62 | id: item.id, 63 | title: item.title, 64 | description: item.description 65 | }; 66 | }); 67 | createDomElements(existingDOM, vDOM); // Pass the old and new vDOM to createDomElements 68 | } 69 | 70 | window.setInterval(() => { 71 | let todos = []; 72 | for (let i = 0; i { 6 | const [todos, setTodos] = useState([]); 7 | const [title, setTitle] = useState(''); 8 | const [description, setDescription] = useState(''); 9 | const authStateValue = useRecoilValue(authState); 10 | 11 | useEffect(() => { 12 | const getTodos = async () => { 13 | const response = await fetch('http://localhost:3000/todo/todos', { 14 | headers: { Authorization: `Bearer ${localStorage.getItem("token")}` } 15 | }); 16 | // Todo: Create a type for the response that you get back from the server 17 | const data = await response.json(); 18 | setTodos(data); 19 | }; 20 | getTodos(); 21 | }, [authState.token]); 22 | 23 | const addTodo = async () => { 24 | const response = await fetch('http://localhost:3000/todo/todos', { 25 | method: 'POST', 26 | headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem("token")}` }, 27 | body: JSON.stringify({ title, description }) 28 | }); 29 | const data = await response.json(); 30 | setTodos([...todos, data]); 31 | }; 32 | 33 | const markDone = async (id) => { 34 | const response = await fetch(`http://localhost:3000/todo/todos/${id}/done`, { 35 | method: 'PATCH', 36 | headers: { Authorization: `Bearer ${localStorage.getItem("token")}` } 37 | }); 38 | const updatedTodo = await response.json(); 39 | setTodos(todos.map((todo) => (todo._id === updatedTodo._id ? updatedTodo : todo))); 40 | }; 41 | 42 | return ( 43 |
44 |
45 |

Welcome {authStateValue.username}

46 |
47 | 51 |
52 |
53 |

Todo List

54 | setTitle(e.target.value)} placeholder='Title' /> 55 | setDescription(e.target.value)} placeholder='Description' /> 56 | 57 | {todos.map((todo) => ( 58 |
59 |

{todo.title}

60 |

{todo.description}

61 | 62 |
63 | ))} 64 |
65 | ); 66 | }; 67 | 68 | export default TodoList; 69 | -------------------------------------------------------------------------------- /visaa_oa/sample_questions.md: -------------------------------------------------------------------------------- 1 | Let me help you understand this problem and provide a detailed solution. 2 | 3 | # Running Sum with Adjacent Elements 4 | 5 | ## Problem Understanding 6 | - Input: Array of integers (let's call it `a`) 7 | - Task: For each position i, calculate sum of (previous + current + next) elements 8 | - For first and last elements, we only take two elements since there's no previous/next element respectively 9 | 10 | ## Example 11 | ``` 12 | Input array a: [0, 3, 4, 67, 2] 13 | Output array b: [3, 7, 74, 73, 69] 14 | ``` 15 | 16 | Let's solve this step by step: 17 | 18 | ## Solution Code 19 | ```python 20 | def calculate_running_sum(arr): 21 | n = len(arr) 22 | # Initialize result array with zeros 23 | result = [0] * n 24 | 25 | # Handle first element (no previous element) 26 | # b[0] = a[0] + a[1] 27 | result[0] = arr[0] + arr[1] 28 | 29 | # Handle middle elements 30 | # b[i] = a[i-1] + a[i] + a[i+1] 31 | for i in range(1, n-1): 32 | result[i] = arr[i-1] + arr[i] + arr[i+1] 33 | 34 | # Handle last element (no next element) 35 | # b[n-1] = a[n-2] + a[n-1] 36 | result[n-1] = arr[n-2] + arr[n-1] 37 | 38 | return result 39 | 40 | # Handle multiple test cases 41 | t = int(input()) # Number of test cases 42 | for _ in range(t): 43 | # Convert input string to list of integers 44 | arr = list(map(int, input().split())) # Note: Changed from input() to input().split() 45 | result = calculate_running_sum(arr) 46 | print(result) 47 | ``` 48 | 49 | ## Detailed Explanation 50 | 51 | 1. **Function Definition**: 52 | - We create a function `calculate_running_sum` that takes an array as input 53 | 54 | 2. **Array Initialization**: 55 | - Create result array (`result`) with same length as input array, filled with zeros 56 | 57 | 3. **Special Cases**: 58 | - First element (index 0): 59 | - Only sum current and next element 60 | - `result[0] = arr[0] + arr[1]` 61 | - Last element (index n-1): 62 | - Only sum current and previous element 63 | - `result[n-1] = arr[n-2] + arr[n-1]` 64 | 65 | 4. **Middle Elements**: 66 | - For each element from index 1 to n-2: 67 | - Sum previous, current, and next elements 68 | - `result[i] = arr[i-1] + arr[i] + arr[i+1]` 69 | 70 | 5. **Example Walkthrough**: 71 | For array `[0, 3, 4, 67, 2]`: 72 | ``` 73 | Index 0: b[0] = 0 + 3 = 3 74 | Index 1: b[1] = 0 + 3 + 4 = 7 75 | Index 2: b[2] = 3 + 4 + 67 = 74 76 | Index 3: b[3] = 4 + 67 + 2 = 73 77 | Index 4: b[4] = 67 + 2 = 69 78 | ``` 79 | 80 | ## Important Fixes from Original Code 81 | 1. Changed `input()` to `input().split()` in array input to properly handle space-separated integers 82 | 2. Separated the logic into a function for better organization 83 | 3. Made the code more readable with clear comments 84 | 85 | ## Edge Cases to Consider 86 | - Array must have at least 2 elements 87 | - Input validation could be added 88 | - Could handle single-element array as a special case if needed 89 | 90 | Would you like me to explain any particular part in more detail? 91 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/todoServer.solution.file.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const bodyParser = require('body-parser'); 3 | const fs = require("fs"); 4 | 5 | const app = express(); 6 | 7 | app.use(bodyParser.json()); 8 | 9 | function findIndex(arr, id) { 10 | for (let i = 0; i < arr.length; i++) { 11 | if (arr[i].id === id) return i; 12 | } 13 | return -1; 14 | } 15 | 16 | function removeAtIndex(arr, index) { 17 | let newArray = []; 18 | for (let i = 0; i < arr.length; i++) { 19 | if (i !== index) newArray.push(arr[i]); 20 | } 21 | return newArray; 22 | } 23 | 24 | app.get('/todos', (req, res) => { 25 | fs.readFile("todos.json", "utf8", (err, data) => { 26 | if (err) throw err; 27 | res.json(JSON.parse(data)); 28 | }); 29 | }); 30 | 31 | app.get('/todos/:id', (req, res) => { 32 | fs.readFile("todos.json", "utf8", (err, data) => { 33 | if (err) throw err; 34 | const todos = JSON.parse(data); 35 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 36 | if (todoIndex === -1) { 37 | res.status(404).send(); 38 | } else { 39 | res.json(todos[todoIndex]); 40 | } 41 | }); 42 | }); 43 | 44 | app.post('/todos', (req, res) => { 45 | const newTodo = { 46 | id: Math.floor(Math.random() * 1000000), // unique random id 47 | title: req.body.title, 48 | description: req.body.description 49 | }; 50 | fs.readFile("todos.json", "utf8", (err, data) => { 51 | if (err) throw err; 52 | const todos = JSON.parse(data); 53 | todos.push(newTodo); 54 | fs.writeFile("todos.json", JSON.stringify(todos), (err) => { 55 | if (err) throw err; 56 | res.status(201).json(newTodo); 57 | }); 58 | }); 59 | }); 60 | 61 | app.put('/todos/:id', (req, res) => { 62 | fs.readFile("todos.json", "utf8", (err, data) => { 63 | if (err) throw err; 64 | const todos = JSON.parse(data); 65 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 66 | if (todoIndex === -1) { 67 | res.status(404).send(); 68 | } else { 69 | const updatedTodo = { 70 | id: todos[todoIndex].id, 71 | title: req.body.title, 72 | description: req.body.description 73 | }; 74 | todos[todoIndex] = updatedTodo; 75 | fs.writeFile("todos.json", JSON.stringify(todos), (err) => { 76 | if (err) throw err; 77 | res.status(200).json(updatedTodo); 78 | }); 79 | } 80 | }); 81 | }); 82 | 83 | app.delete('/todos/:id', (req, res) => { 84 | 85 | fs.readFile("todos.json", "utf8", (err, data) => { 86 | if (err) throw err; 87 | const todos = JSON.parse(data); 88 | const todoIndex = findIndex(todos, parseInt(req.params.id)); 89 | if (todoIndex === -1) { 90 | res.status(404).send(); 91 | } else { 92 | todos = removeAtIndex(todos, todoIndex); 93 | fs.writeFile("todos.json", JSON.stringify(todos), (err) => { 94 | if (err) throw err; 95 | res.status(200).send(); 96 | }); 97 | } 98 | }); 99 | }); 100 | 101 | // for all other routes, return 404 102 | app.use((req, res, next) => { 103 | res.status(404).send(); 104 | }); 105 | 106 | module.exports = app; 107 | -------------------------------------------------------------------------------- /assignments/react/03-course-app-medium/README.md: -------------------------------------------------------------------------------- 1 | ## Create a course selling website 2 | 3 | ### Description 4 | Functionally the same as 02-course-app-easy. Routes are the same as well. 5 | But now you need to store data in files vs in memory. 6 | Create separate files for each entity (admin, user, course, purchase). 7 | 8 | ## Routes 9 | ### Admin Routes: 10 | - POST /admin/signup 11 | Description: Creates a new admin account. 12 | Input: { username: 'admin', password: 'pass' } 13 | Output: { message: 'Admin created successfully', token: 'jwt_token_here' } 14 | - POST /admin/login 15 | Description: Authenticates an admin. It requires the admin to send username and password in the headers. 16 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 17 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 18 | - POST /admin/courses 19 | Description: Creates a new course. 20 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true } 21 | Output: { message: 'Course created successfully', courseId: 1 } 22 | - PUT /admin/courses/:courseId 23 | Description: Edits an existing course. courseId in the URL path should be replaced with the ID of the course to be edited. 24 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'updated course title', description: 'updated course description', price: 100, imageLink: 'https://updatedlinktoimage.com', published: false } 25 | Output: { message: 'Course updated successfully' } 26 | - GET /admin/courses 27 | Description: Returns all the courses. 28 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 29 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 30 | User Routes: 31 | 32 | ### User routes 33 | - POST /users/signup 34 | Description: Creates a new user account. 35 | Input: { username: 'user', password: 'pass' } 36 | Output: { message: 'User created successfully', token: 'jwt_token_here' } 37 | - POST /users/login 38 | Description: Authenticates a user. It requires the user to send username and password in the headers. 39 | Input: Headers: { 'username': 'user', 'password': 'pass' } 40 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 41 | - GET /users/courses 42 | Description: Lists all the courses. 43 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 44 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 45 | - POST /users/courses/:courseId 46 | Description: Purchases a course. courseId in the URL path should be replaced with the ID of the course to be purchased. 47 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 48 | Output: { message: 'Course purchased successfully' } 49 | - GET /users/purchasedCourses 50 | Description: Lists all the courses purchased by the user. 51 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 52 | Output: { purchasedCourses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 53 | -------------------------------------------------------------------------------- /assignments/js/tests/calculator.test.js: -------------------------------------------------------------------------------- 1 | const Calculator = require('../hard/calculator'); 2 | 3 | describe('Calculator', () => { 4 | let calc; 5 | 6 | beforeEach(() => { 7 | calc = new Calculator(); 8 | }); 9 | 10 | afterEach(() => { 11 | calc.clear(); 12 | }); 13 | 14 | test('addition', () => { 15 | calc.add(5); 16 | expect(calc.getResult()).toBe(5); 17 | 18 | calc.add(3); 19 | expect(calc.getResult()).toBe(8); 20 | }); 21 | 22 | test('subtraction', () => { 23 | calc.subtract(5); 24 | expect(calc.getResult()).toBe(-5); 25 | 26 | calc.subtract(3); 27 | expect(calc.getResult()).toBe(-8); 28 | }); 29 | 30 | test('multiplication', () => { 31 | calc.add(4); 32 | calc.multiply(3); 33 | expect(calc.getResult()).toBe(12); 34 | 35 | calc.multiply(0); 36 | expect(calc.getResult()).toBe(0); 37 | }); 38 | 39 | test('division', () => { 40 | calc.add(12); 41 | 42 | calc.divide(4); 43 | expect(calc.getResult()).toBe(3); 44 | 45 | expect(() => calc.divide(0)).toThrow(Error); 46 | expect(calc.getResult()).toBe(3); 47 | }); 48 | 49 | test('clear', () => { 50 | calc.add(5); 51 | calc.clear(); 52 | expect(calc.getResult()).toBe(0); 53 | }); 54 | 55 | test('calculate addition and multiplication', () => { 56 | calc.calculate('2 + 3 * 4'); 57 | expect(calc.getResult()).toBe(14); 58 | }); 59 | 60 | test('calculate division in expression', () => { 61 | calc.calculate('( 15 + 3) / 6 '); 62 | expect(calc.getResult()).toBe(3); 63 | }); 64 | 65 | test('calculate subtraction in expression', () => { 66 | calc.calculate('10 - (4 + 2)'); 67 | expect(calc.getResult()).toBe(4); 68 | }); 69 | 70 | test('calculate complex expression', () => { 71 | calc.calculate('(2 + 3) * (6 - (4 + 1) / 2) + 7'); 72 | expect(calc.getResult()).toBe(24.5); 73 | }); 74 | test('calculate complex expression with spaces', () => { 75 | calc.calculate( 76 | '10 + 2 * ( 6 - (4 + 1) / 2) + 7' 77 | ); 78 | expect(calc.getResult()).toBe(24); 79 | }); 80 | 81 | test('calculate expression with decimals', () => { 82 | calc.calculate('(2.5 + 1.5) * 3'); 83 | expect(calc.getResult()).toBe(12); 84 | }); 85 | 86 | test('calculate expression with invalid characters', () => { 87 | expect(() => calc.calculate('5 + abc')).toThrow(Error); 88 | expect(() => 89 | calc.calculate('10 * (2 + 3) + xyz') 90 | ).toThrow(Error); 91 | }); 92 | 93 | test('calculate division by zero', () => { 94 | expect(() => calc.calculate('10 / 0')).toThrow(Error); 95 | }); 96 | 97 | test('multiplication with negative numbers', () => { 98 | calc.add(-5); 99 | calc.multiply(-3); 100 | expect(calc.getResult()).toBe(15); 101 | 102 | calc.multiply(0); 103 | expect(calc.getResult()).toBe(0); 104 | }); 105 | 106 | test('division with decimal numbers', () => { 107 | calc.add(10); 108 | calc.divide(3); 109 | expect(calc.getResult()).toBeCloseTo(3.333333, 2); 110 | 111 | calc.divide(2); 112 | expect(calc.getResult()).toBeCloseTo(1.666666, 2); 113 | }); 114 | 115 | test('expression with invalid parentheses', () => { 116 | expect(() => calc.calculate('10 + (2 + 3')).toThrow( 117 | Error 118 | ); 119 | expect(() => calc.calculate('10 + 2) + 3')).toThrow( 120 | Error 121 | ); 122 | expect(() => calc.calculate(')10 + 2(')).toThrow(Error); 123 | }); 124 | }); 125 | -------------------------------------------------------------------------------- /nnrg_workshop/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | My Diary Application 7 | 8 | 9 | 10 | 11 |
12 |
13 |

My Diary

14 |
15 | 16 | 17 |
18 |
19 | 20 |
21 |
22 |
23 | 24 |

25 | 26 |
27 |
28 |
Sun
29 |
Mon
30 |
Tue
31 |
Wed
32 |
Thu
33 |
Fri
34 |
Sat
35 |
36 |
37 |
38 | 39 |
40 |
41 |

Diary Entry

42 | 43 |
44 |
45 |

46 |
47 |
48 | 49 |
50 | 51 | 52 |
53 |
54 |
55 |
56 | 57 | 58 | 76 |
77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /assignments/react/04-course-app-hard/README.md: -------------------------------------------------------------------------------- 1 | ## Create a course selling website 2 | 3 | ### Description 4 | Functionally the same as 03-course-app-medium. Routes are the same as well. 5 | Rather than storing data in files, store them in MongoDB. 6 | We will be covering this in the extra class next week but would be good for you to run ahead. 7 | 8 | ## Routes 9 | ### Admin Routes: 10 | - POST /admin/signup 11 | Description: Creates a new admin account. 12 | Input: { username: 'admin', password: 'pass' } 13 | Output: { message: 'Admin created successfully', token: 'jwt_token_here' } 14 | - POST /admin/login 15 | Description: Authenticates an admin. It requires the admin to send username and password in the headers. 16 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 17 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 18 | - POST /admin/courses 19 | Description: Creates a new course. 20 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true } 21 | Output: { message: 'Course created successfully', courseId: 1 } 22 | - PUT /admin/courses/:courseId 23 | Description: Edits an existing course. courseId in the URL path should be replaced with the ID of the course to be edited. 24 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'updated course title', description: 'updated course description', price: 100, imageLink: 'https://updatedlinktoimage.com', published: false } 25 | Output: { message: 'Course updated successfully' } 26 | - GET /admin/courses 27 | Description: Returns all the courses. 28 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 29 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 30 | User Routes: 31 | 32 | ### User routes 33 | - POST /users/signup 34 | Description: Creates a new user account. 35 | Input: { username: 'user', password: 'pass' } 36 | Output: { message: 'User created successfully', token: 'jwt_token_here' } 37 | - POST /users/login 38 | Description: Authenticates a user. It requires the user to send username and password in the headers. 39 | Input: Headers: { 'username': 'user', 'password': 'pass' } 40 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 41 | - GET /users/courses 42 | Description: Lists all the courses. 43 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 44 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 45 | - POST /users/courses/:courseId 46 | Description: Purchases a course. courseId in the URL path should be replaced with the ID of the course to be purchased. 47 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 48 | Output: { message: 'Course purchased successfully' } 49 | - GET /users/purchasedCourses 50 | Description: Lists all the courses purchased by the user. 51 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 52 | Output: { purchasedCourses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 53 | -------------------------------------------------------------------------------- /visaa_oa/strings2.md: -------------------------------------------------------------------------------- 1 | # Understanding the Problem and Concepts 2 | 3 | ## What is a Substring? 4 | A substring is a contiguous sequence of characters within a string. 5 | - Example: For the string "hello" 6 | - Substrings include: "h", "he", "hel", "hell", "hello" 7 | - Note that substrings must be continuous characters 8 | 9 | ## What is a Palindrome? 10 | A palindrome is a string that reads the same backward as forward. 11 | - Example: 12 | - "radar" is a palindrome 13 | - "hello" is NOT a palindrome 14 | 15 | ## Key Concepts in the Code 16 | 17 | ### 1. Reversing a String (Without Built-in Functions) 18 | ```python 19 | def reverse(s): 20 | r_s = "" 21 | for char in s: 22 | r_s = char + r_s # Add each character to the beginning 23 | return r_s 24 | ``` 25 | - This function manually reverses a string 26 | - How it works: 27 | - Start with an empty string 28 | - Take each character from the original string 29 | - Add it to the front of the new string 30 | - Example: 31 | - Input: "hello" 32 | - Process: "" → "h" → "he" → "hel" → "hell" → "hello" 33 | 34 | ### 2. Palindrome Checking 35 | ```python 36 | if s == reverse(s): 37 | print("This string is a palindrome") 38 | else: 39 | print("It's not a palindrome") 40 | ``` 41 | - Compares the original string with its reverse 42 | - If they're identical, it's a palindrome 43 | 44 | ### 3. Finding Palindromic Substrings 45 | ```python 46 | count = 0 47 | for i in range(0, len(s)): 48 | for j in range(i+1, len(s)): 49 | # Check if substring is a palindrome 50 | if s[i:j] == reverse(s[i:j]): 51 | count += 1 52 | print(s[i:j]) 53 | ``` 54 | - Uses nested loops to generate all possible substrings 55 | - Outer loop (i): starting point of substring 56 | - Inner loop (j): ending point of substring 57 | - Checks each substring to see if it's a palindrome 58 | 59 | ## Important Notes 60 | - Strings are immutable in Python (cannot be changed in-place) 61 | - Time complexity of substring check is O(n²) 62 | - Total number of substrings for a string of length n is n*(n+1)/2 63 | 64 | ## Complete Code Explanation 65 | ```python 66 | # Number of test cases 67 | t = int(input()) 68 | 69 | # Loop through each test case 70 | for i in range(0, t): 71 | # Input the string 72 | s = input() 73 | 74 | # Reverse the string function 75 | def reverse(s): 76 | r_s = "" 77 | for char in s: 78 | r_s = char + r_s 79 | return r_s 80 | 81 | # Check if whole string is a palindrome 82 | if s == reverse(s): 83 | print("This string is a palindrome") 84 | else: 85 | print("It's not a palindrome") 86 | 87 | # Find palindromic substrings 88 | count = 0 89 | for i in range(0, len(s)): 90 | for j in range(i+1, len(s)): 91 | # Check if substring is a palindrome 92 | if s[i:j] == reverse(s[i:j]): 93 | count += 1 94 | print(s[i:j]) 95 | 96 | # Print total count of palindromic substrings 97 | print(f"The number of palindromic substrings is {count}") 98 | ``` 99 | 100 | ## Example Walkthrough 101 | - Input: "ytuy" 102 | - Palindromic Substrings: 103 | 1. "y" 104 | 2. "t" 105 | 3. "u" 106 | 4. "tuy" 107 | 108 | ## Potential Improvements 109 | - Optimize substring checking 110 | - Handle edge cases 111 | - Improve time complexity 112 | 113 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy/README.md: -------------------------------------------------------------------------------- 1 | ## Create a course selling website 2 | 3 | ### Description 4 | 1. Admins should be able to sign up 5 | 2. Admins should be able to create courses 6 | 1. Course has a title, description, price, and image link 7 | 2. Course should be able to be published 8 | 3. Admins should be able to edit courses 9 | 4. Users should be able to sign up 10 | 5. Users should be able to purchase courses 11 | 6. Users should be able to view purchased courses 12 | 7. Users should be able to view all courses 13 | 14 | ## Routes 15 | ### Admin Routes: 16 | - POST /admin/signup 17 | Description: Creates a new admin account. 18 | Input: { username: 'admin', password: 'pass' } 19 | Output: { message: 'Admin created successfully' } 20 | - POST /admin/login 21 | Description: Authenticates an admin. It requires the admin to send username and password in the headers. 22 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 23 | Output: { message: 'Logged in successfully' } 24 | - POST /admin/courses 25 | Description: Creates a new course. 26 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 27 | Input: Body: { title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true } 28 | Output: { message: 'Course created successfully', courseId: 1 } 29 | - PUT /admin/courses/:courseId 30 | Description: Edits an existing course. courseId in the URL path should be replaced with the ID of the course to be edited. 31 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 32 | Input: Body { title: 'updated course title', description: 'updated course description', price: 100, imageLink: 'https://updatedlinktoimage.com', published: false } 33 | Output: { message: 'Course updated successfully' } 34 | - GET /admin/courses 35 | Description: Returns all the courses. 36 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 37 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 38 | User Routes: 39 | 40 | ### User routes 41 | - POST /users/signup 42 | Description: Creates a new user account. 43 | Input: { username: 'user', password: 'pass' } 44 | Output: { message: 'User created successfully' } 45 | - POST /users/login 46 | Description: Authenticates a user. It requires the user to send username and password in the headers. 47 | Input: Headers: { 'username': 'user', 'password': 'pass' } 48 | Output: { message: 'Logged in successfully' } 49 | - GET /users/courses 50 | Description: Lists all the courses. 51 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 52 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 53 | - POST /users/courses/:courseId 54 | Description: Purchases a course. courseId in the URL path should be replaced with the ID of the course to be purchased. 55 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 56 | Output: { message: 'Course purchased successfully' } 57 | - GET /users/purchasedCourses 58 | Description: Lists all the courses purchased by the user. 59 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 60 | Output: { purchasedCourses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 61 | -------------------------------------------------------------------------------- /ml_projects/Heart failure detection through ecg analysis using CNN/ECG Testing_GUI.py: -------------------------------------------------------------------------------- 1 | 2 | import tkinter as tk 3 | from tkinter import filedialog 4 | from tkinter import * 5 | from PIL import Image, ImageTk 6 | import numpy as np 7 | from keras.models import load_model 8 | 9 | # Initialising GUI 10 | top = tk.Tk() 11 | top.geometry('800x600') 12 | top.title('Heart Disease Detection') 13 | top.configure(background='#F0E68C') # Set background color to a soothing yellow 14 | 15 | # Loading the model 16 | model = load_model('model_vgg19.h5') 17 | 18 | # Function to detect heart disease 19 | def detect(file_path): 20 | try: 21 | img = Image.open(file_path) 22 | img = img.resize((224, 224)) # Resize the image to the required size 23 | img_array = np.array(img) # Convert image to numpy array 24 | 25 | # Ensure image has 3 channels (RGB) 26 | if img_array.shape[-1] == 4: 27 | img_array = img_array[..., :3] # Keep only the first 3 channels 28 | 29 | # Preprocess the image data (normalize pixel values) 30 | img_array = img_array.astype('float32') / 255.0 31 | 32 | # Expand the dimensions of the image array to match the model input shape 33 | img_array = np.expand_dims(img_array, axis=0) 34 | 35 | # Predict using the model 36 | prediction = model.predict(img_array) 37 | predicted_class = np.argmax(prediction) + 1 # Adjust index to start from 1 38 | 39 | 40 | if predicted_class == 1: 41 | label1.configure(foreground='#011638', text="Uninfected") 42 | else: 43 | predicted_class = np.where(prediction ==np.max(prediction)) 44 | reverse_mapping = ['F','M','N','Q','S','V'] 45 | prediction_name = reverse_mapping[predicted_class[1][0]] 46 | label1.configure(foreground='#011638', text="Infected" + " " + "Final Diagnosis-" + prediction_name) 47 | except Exception as e: 48 | print("Error:", e) 49 | label1.configure(foreground='#011638', text="Error occurred!") 50 | 51 | # Function to show detect image button 52 | def show_detect_buttons(file_path): 53 | Detect_b = Button(top, text="Detect Image", command=lambda: detect(file_path), padx=10, pady=5) 54 | Detect_b.configure(background="#008080", foreground='white', font=('Arial', 10, 'bold')) # Set button color to teal 55 | Detect_b.place(relx=0.76, rely=0.49) 56 | 57 | # Function to upload image 58 | def upload_image(): 59 | try: 60 | file_path = filedialog.askopenfilename() 61 | uploaded = Image.open(file_path) 62 | uploaded.thumbnail(((top.winfo_width() / 2.25), (top.winfo_height() / 2.25))) 63 | im = ImageTk.PhotoImage(uploaded) 64 | sign_image.configure(image=im) 65 | sign_image.image = im 66 | label1.configure(text='') 67 | show_detect_buttons(file_path) 68 | except Exception as e: 69 | print("Error:", e) 70 | 71 | # GUI components 72 | sign_image = Label(top) 73 | upload = Button(top, text="Upload Image", command=upload_image, padx=10, pady=5) 74 | upload.configure(background="#008080", foreground='white', font=('Arial', 10, 'bold')) # Set button color to teal 75 | upload.pack(side='bottom', pady=20) 76 | sign_image.pack(side='bottom', expand=True) 77 | label1 = Label(top, background='#F0E68C', font=('Arial', 15, 'bold')) # Set label background to the same yellow color 78 | label1.pack(side='bottom', expand=True) 79 | heading = Label(top, text="Heart Disease Detection", font=('Arial', 20, 'bold'), bg='#F0E68C', pady=10) # Set heading background to the same yellow color 80 | heading.pack() 81 | 82 | top.mainloop() 83 | 84 | -------------------------------------------------------------------------------- /assignments/react/02-course-app-easy-2/README.md: -------------------------------------------------------------------------------- 1 | ## Create a course selling website 2 | 3 | ### Description 4 | Functionally the same as 02-course-app-easy. Routes are different though. 5 | We now need to implement actual authentication here. 6 | We're going to use Json Web Tokens (JWT) for the same. 7 | When the user signs up, they should get back a jwt that is valid for 1 hour. 8 | They should then send just that jwt vs sending username and password to the authenticated routes. 9 | 10 | You need to understand the API of jwt. We will be covering this in the extra recorded session this week. 11 | 12 | ## Routes 13 | ### Admin Routes: 14 | - POST /admin/signup 15 | Description: Creates a new admin account. 16 | Input: { username: 'admin', password: 'pass' } 17 | Output: { message: 'Admin created successfully', token: 'jwt_token_here' } 18 | - POST /admin/login 19 | Description: Authenticates an admin. It requires the admin to send username and password in the headers. 20 | Input: Headers: { 'username': 'admin', 'password': 'pass' } 21 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 22 | - POST /admin/courses 23 | Description: Creates a new course. 24 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true } 25 | Output: { message: 'Course created successfully', courseId: 1 } 26 | - PUT /admin/courses/:courseId 27 | Description: Edits an existing course. courseId in the URL path should be replaced with the ID of the course to be edited. 28 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' }, Body: { title: 'updated course title', description: 'updated course description', price: 100, imageLink: 'https://updatedlinktoimage.com', published: false } 29 | Output: { message: 'Course updated successfully' } 30 | - GET /admin/courses 31 | Description: Returns all the courses. 32 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 33 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 34 | User Routes: 35 | 36 | ### User routes 37 | - POST /users/signup 38 | Description: Creates a new user account. 39 | Input: { username: 'user', password: 'pass' } 40 | Output: { message: 'User created successfully', token: 'jwt_token_here' } 41 | - POST /users/login 42 | Description: Authenticates a user. It requires the user to send username and password in the headers. 43 | Input: Headers: { 'username': 'user', 'password': 'pass' } 44 | Output: { message: 'Logged in successfully', token: 'jwt_token_here' } 45 | - GET /users/courses 46 | Description: Lists all the courses. 47 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 48 | Output: { courses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 49 | - POST /users/courses/:courseId 50 | Description: Purchases a course. courseId in the URL path should be replaced with the ID of the course to be purchased. 51 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 52 | Output: { message: 'Course purchased successfully' } 53 | - GET /users/purchasedCourses 54 | Description: Lists all the courses purchased by the user. 55 | Input: Headers: { 'Authorization': 'Bearer jwt_token_here' } 56 | Output: { purchasedCourses: [ { id: 1, title: 'course title', description: 'course description', price: 100, imageLink: 'https://linktoimage.com', published: true }, ... ] } 57 | -------------------------------------------------------------------------------- /CMR FDP/rag.md: -------------------------------------------------------------------------------- 1 | ## RAG (Retrieval Augmented Generation) architecture and its components. 2 | ## RAG System Overview 3 | ![image](https://github.com/user-attachments/assets/3ab86d23-3509-437c-918b-d1813a94763d) 4 | 5 | ## Content Vectorization Process 6 | ![image](https://github.com/user-attachments/assets/507cc161-21f4-424a-a984-b09408e0c667) 7 | 8 | ## Vector Similarity Search 9 | ![image](https://github.com/user-attachments/assets/b484fea8-7572-484c-be8d-87c1d0c8dee2) 10 | 11 | ## Prompt Construction 12 | ![image](https://github.com/user-attachments/assets/c64679ce-f1a6-467f-8553-2579e3261319) 13 | 14 | ## Complete RAG Workflow 15 | 16 | ![image](https://github.com/user-attachments/assets/eb24198e-9173-46a8-babc-13a464219477) 17 | 18 | 19 | 20 | 21 | ## Key Components and Process: 22 | 23 | 1. Content Processing: 24 | - Document chunking into manageable pieces 25 | - Vector embedding creation for each chunk 26 | - Storage in vector database for efficient retrieval 27 | 28 | 2. Query Handling: 29 | - User query vectorization 30 | - Similarity search against stored vectors 31 | - Retrieval of most relevant content chunks 32 | 33 | 3. Prompt Construction: 34 | - System instructions (context and role) 35 | - Retrieved relevant content 36 | - Original user query 37 | 38 | 4. LLM Integration: 39 | - Combined prompt processing 40 | - Context-aware response generation 41 | - Natural language output 42 | 43 | 5. End-to-End Workflow: 44 | - Input: User question 45 | - Processing: Vector similarity search 46 | - Enhancement: Content retrieval 47 | - Output: Contextualized response 48 | 49 | This architecture enables organizations to create ChatGPT-like experiences with their own content while maintaining accuracy and relevance. 50 | 51 | 52 | 53 | Here's a detailed look at RAG implementations across industries with real-world examples: 54 | ![image](https://github.com/user-attachments/assets/eed9ea73-f69c-4d0f-bd31-6ac70ba8bcea) 55 | 56 | 57 | ## Real-World Applications: 58 | 59 | 1. Healthcare 60 | - Mayo Clinic: Patient portal chatbot accessing specific medical records and treatment protocols 61 | - Insurance providers: Claim processing assistants using policy documentation 62 | - Medical research: Literature review assistance for clinical trials 63 | 64 | 2. Enterprise 65 | - Microsoft: Internal documentation search for developers 66 | - Salesforce: Customer case resolution using historical support tickets 67 | - IBM: Employee handbook and policy navigation 68 | 69 | 3. Customer Service 70 | - Zendesk: Automated response system using company-specific knowledge bases 71 | - Apple: Product support using device-specific documentation 72 | - Amazon: Order assistance with real-time inventory and shipping data 73 | 74 | 4. Legal 75 | - LexisNexis: Case law research assistant 76 | - Law firms: Contract analysis using firm precedents 77 | - Compliance: Regulation interpretation using internal policies 78 | 79 | 5. Education 80 | - Coursera: Personalized tutoring using course materials 81 | - Universities: Research assistance using institutional papers 82 | - Khan Academy: Custom curriculum development 83 | 84 | 6. E-commerce 85 | - Shopify: Product recommendation engine using merchant catalogs 86 | - eBay: Shopping assistant with listing-specific knowledge 87 | - Wayfair: Interior design advice using product database 88 | 89 | Implementation Benefits: 90 | 1. Accuracy: 95%+ improvement in response accuracy vs. generic LLMs 91 | 2. Speed: 60% reduction in query resolution time 92 | 3. Cost: 40% decrease in customer support costs 93 | 4. Satisfaction: 80% increase in user engagement 94 | 95 | Key Success Factors: 96 | - Quality content preparation 97 | - Effective chunking strategies 98 | - Regular vector database updates 99 | - Prompt engineering optimization 100 | - Performance monitoring 101 | 102 | -------------------------------------------------------------------------------- /MRU_FDP/rag.md: -------------------------------------------------------------------------------- 1 | ## RAG (Retrieval Augmented Generation) architecture and its components. 2 | ## RAG System Overview 3 | ![image](https://github.com/user-attachments/assets/3ab86d23-3509-437c-918b-d1813a94763d) 4 | 5 | ## Content Vectorization Process 6 | ![image](https://github.com/user-attachments/assets/507cc161-21f4-424a-a984-b09408e0c667) 7 | 8 | ## Vector Similarity Search 9 | ![image](https://github.com/user-attachments/assets/b484fea8-7572-484c-be8d-87c1d0c8dee2) 10 | 11 | ## Prompt Construction 12 | ![image](https://github.com/user-attachments/assets/c64679ce-f1a6-467f-8553-2579e3261319) 13 | 14 | ## Complete RAG Workflow 15 | 16 | ![image](https://github.com/user-attachments/assets/eb24198e-9173-46a8-babc-13a464219477) 17 | 18 | 19 | 20 | 21 | ## Key Components and Process: 22 | 23 | 1. Content Processing: 24 | - Document chunking into manageable pieces 25 | - Vector embedding creation for each chunk 26 | - Storage in vector database for efficient retrieval 27 | 28 | 2. Query Handling: 29 | - User query vectorization 30 | - Similarity search against stored vectors 31 | - Retrieval of most relevant content chunks 32 | 33 | 3. Prompt Construction: 34 | - System instructions (context and role) 35 | - Retrieved relevant content 36 | - Original user query 37 | 38 | 4. LLM Integration: 39 | - Combined prompt processing 40 | - Context-aware response generation 41 | - Natural language output 42 | 43 | 5. End-to-End Workflow: 44 | - Input: User question 45 | - Processing: Vector similarity search 46 | - Enhancement: Content retrieval 47 | - Output: Contextualized response 48 | 49 | This architecture enables organizations to create ChatGPT-like experiences with their own content while maintaining accuracy and relevance. 50 | 51 | 52 | 53 | Here's a detailed look at RAG implementations across industries with real-world examples: 54 | ![image](https://github.com/user-attachments/assets/eed9ea73-f69c-4d0f-bd31-6ac70ba8bcea) 55 | 56 | 57 | ## Real-World Applications: 58 | 59 | 1. Healthcare 60 | - Mayo Clinic: Patient portal chatbot accessing specific medical records and treatment protocols 61 | - Insurance providers: Claim processing assistants using policy documentation 62 | - Medical research: Literature review assistance for clinical trials 63 | 64 | 2. Enterprise 65 | - Microsoft: Internal documentation search for developers 66 | - Salesforce: Customer case resolution using historical support tickets 67 | - IBM: Employee handbook and policy navigation 68 | 69 | 3. Customer Service 70 | - Zendesk: Automated response system using company-specific knowledge bases 71 | - Apple: Product support using device-specific documentation 72 | - Amazon: Order assistance with real-time inventory and shipping data 73 | 74 | 4. Legal 75 | - LexisNexis: Case law research assistant 76 | - Law firms: Contract analysis using firm precedents 77 | - Compliance: Regulation interpretation using internal policies 78 | 79 | 5. Education 80 | - Coursera: Personalized tutoring using course materials 81 | - Universities: Research assistance using institutional papers 82 | - Khan Academy: Custom curriculum development 83 | 84 | 6. E-commerce 85 | - Shopify: Product recommendation engine using merchant catalogs 86 | - eBay: Shopping assistant with listing-specific knowledge 87 | - Wayfair: Interior design advice using product database 88 | 89 | Implementation Benefits: 90 | 1. Accuracy: 95%+ improvement in response accuracy vs. generic LLMs 91 | 2. Speed: 60% reduction in query resolution time 92 | 3. Cost: 40% decrease in customer support costs 93 | 4. Satisfaction: 80% increase in user engagement 94 | 95 | Key Success Factors: 96 | - Quality content preparation 97 | - Effective chunking strategies 98 | - Regular vector database updates 99 | - Prompt engineering optimization 100 | - Performance monitoring 101 | 102 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | TODO app 4 | 5 | 6 | 100 | 101 | Todo title 102 | 103 |

104 | Todo description 105 | 106 |

107 | 108 |
109 | 110 |
111 | -------------------------------------------------------------------------------- /assignments/nodejs/tests/authenticationServer.test.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const server = require('../authenticationServer'); 3 | 4 | const email = 'testuser@gmail.com'; 5 | const password = 'testpassword'; 6 | const firstName = "kirat" 7 | const lastName = "kirat" 8 | 9 | 10 | describe('API Tests', () => { 11 | let globalServer; 12 | beforeAll((done) => { 13 | if (globalServer) { 14 | globalServer.close(); 15 | } 16 | globalServer = server.listen(3000); 17 | done() 18 | }); 19 | 20 | afterAll((done) => { 21 | globalServer.close(done); 22 | }); 23 | 24 | it('should allow a user to sign up', async () => { 25 | const requestBody = JSON.stringify({ email, password, firstName, lastName }); 26 | 27 | const options = { 28 | method: 'POST', 29 | path: '/signup', 30 | headers: { 31 | 'Content-Type': 'application/json', 32 | 'Content-Length': requestBody.length, 33 | }, 34 | }; 35 | 36 | const response = await sendRequest(options, requestBody); 37 | 38 | expect(response.statusCode).toBe(201); 39 | expect(response.body).toBe('Signup successful'); 40 | }); 41 | 42 | it('should allow a user to login', async () => { 43 | const requestBody = JSON.stringify({ email, password }); 44 | 45 | const options = { 46 | method: 'POST', 47 | path: '/login', 48 | headers: { 49 | 'Content-Type': 'application/json', 50 | 'Content-Length': requestBody.length, 51 | }, 52 | }; 53 | 54 | const response = await sendRequest(options, requestBody); 55 | 56 | expect(response.statusCode).toBe(200); 57 | expect(response.body).toBeDefined(); 58 | 59 | const responseBody = JSON.parse(response.body); 60 | expect(responseBody.email).toBe(email); 61 | expect(responseBody.firstName).toBe(firstName); 62 | expect(responseBody.lastName).toBe(lastName); 63 | 64 | authToken = responseBody.authToken; 65 | }); 66 | 67 | it('should return unauthorized for accessing protected data without authentication', async () => { 68 | const options = { 69 | method: 'GET', 70 | path: '/data', 71 | headers: { 72 | email, 73 | password: "", 74 | }, 75 | }; 76 | 77 | const response = await sendRequest(options); 78 | 79 | expect(response.statusCode).toBe(401); 80 | expect(response.body).toBe('Unauthorized'); 81 | }); 82 | 83 | it('should return the users for accessing protected data with authentication', async () => { 84 | const options = { 85 | method: 'GET', 86 | path: '/data', 87 | headers: { 88 | email, 89 | password 90 | }, 91 | }; 92 | 93 | const response = await sendRequest(options); 94 | 95 | expect(response.statusCode).toBe(200); 96 | 97 | const responseBody = JSON.parse(response.body); 98 | console.log(responseBody); 99 | expect(responseBody.users.length).toBe(1); 100 | }); 101 | }); 102 | 103 | function sendRequest(options, requestBody) { 104 | return new Promise((resolve, reject) => { 105 | const req = http.request( 106 | { 107 | ...options, 108 | host: 'localhost', 109 | port: 3000, 110 | }, 111 | (res) => { 112 | let body = ''; 113 | 114 | res.on('data', (chunk) => { 115 | body += chunk; 116 | }); 117 | 118 | res.on('end', () => { 119 | resolve({ 120 | statusCode: res.statusCode, 121 | headers: res.headers, 122 | body, 123 | }); 124 | }); 125 | } 126 | ); 127 | 128 | req.on('error', (err) => { 129 | reject(err); 130 | }); 131 | 132 | if (requestBody) { 133 | req.write(requestBody); 134 | } 135 | 136 | req.end(); 137 | }); 138 | } 139 | -------------------------------------------------------------------------------- /assignments/nodejs/tests/todoServer.test.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const { v4: uuidv4 } = require('uuid'); 3 | 4 | const server = require('../todoServer'); 5 | const port = 3000; 6 | const baseUrl = `http://localhost:${port}`; 7 | 8 | describe('Todo API', () => { 9 | let createdTodoId; 10 | let globalServer; 11 | 12 | beforeAll((done) => { 13 | if (globalServer) { 14 | globalServer.close(); 15 | } 16 | globalServer = server.listen(3000); 17 | done() 18 | }); 19 | 20 | afterAll((done) => { 21 | globalServer.close(done); 22 | }); 23 | 24 | const todo = { 25 | title: 'New Todo', 26 | description: 'A new todo item', 27 | }; 28 | 29 | test('should create a new todo item', (done) => { 30 | const options = { 31 | method: 'POST', 32 | headers: { 33 | 'Content-Type': 'application/json', 34 | }, 35 | }; 36 | 37 | const req = http.request(`${baseUrl}/todos`, options, (res) => { 38 | expect(res.statusCode).toBe(201); 39 | let data = ''; 40 | 41 | res.on('data', (chunk) => { 42 | data += chunk; 43 | }); 44 | 45 | res.on('end', () => { 46 | const response = JSON.parse(data); 47 | expect(response.id).toBeTruthy(); 48 | createdTodoId = response.id; 49 | done(); 50 | }); 51 | }); 52 | 53 | req.write(JSON.stringify(todo)); 54 | req.end(); 55 | }); 56 | 57 | test('should retrieve all todo items', (done) => { 58 | http.get(`${baseUrl}/todos`, (res) => { 59 | expect(res.statusCode).toBe(200); 60 | let data = ''; 61 | 62 | res.on('data', (chunk) => { 63 | data += chunk; 64 | }); 65 | 66 | res.on('end', () => { 67 | const todos = JSON.parse(data); 68 | expect(Array.isArray(todos)).toBe(true); 69 | expect(todos.length).toBe(1); 70 | expect(todos[0].title).toBe(todo.title); 71 | expect(todos[0].description).toBe(todo.description); 72 | done(); 73 | }); 74 | }); 75 | }); 76 | 77 | test('should retrieve a specific todo item by ID', (done) => { 78 | http.get(`${baseUrl}/todos/${createdTodoId}`, (res) => { 79 | expect(res.statusCode).toBe(200); 80 | let data = ''; 81 | 82 | res.on('data', (chunk) => { 83 | data += chunk; 84 | }); 85 | 86 | res.on('end', () => { 87 | const todo = JSON.parse(data); 88 | expect(todo.id).toBe(createdTodoId); 89 | done(); 90 | }); 91 | }); 92 | }); 93 | 94 | test('should update a specific todo item', (done) => { 95 | const updatedTodo = { 96 | title: 'Updated Todo', 97 | description: 'An updated todo item', 98 | }; 99 | 100 | const options = { 101 | method: 'PUT', 102 | headers: { 103 | 'Content-Type': 'application/json', 104 | }, 105 | }; 106 | 107 | const req = http.request( 108 | `${baseUrl}/todos/${createdTodoId}`, 109 | options, 110 | (res) => { 111 | expect(res.statusCode).toBe(200); 112 | done(); 113 | } 114 | ); 115 | 116 | req.write(JSON.stringify(updatedTodo)); 117 | req.end(); 118 | }); 119 | 120 | test('should delete a specific todo item', (done) => { 121 | const options = { 122 | method: 'DELETE', 123 | }; 124 | 125 | const req = http.request( 126 | `${baseUrl}/todos/${createdTodoId}`, 127 | options, 128 | (res) => { 129 | expect(res.statusCode).toBe(200); 130 | done(); 131 | } 132 | ); 133 | 134 | req.end(); 135 | }); 136 | 137 | test('should return 404 for a non-existent todo item', (done) => { 138 | http.get(`${baseUrl}/todos/${uuidv4()}`, (res) => { 139 | expect(res.statusCode).toBe(404); 140 | done(); 141 | }); 142 | }); 143 | }); 144 | -------------------------------------------------------------------------------- /assignments/nodejs/tests/fileServer.test.js: -------------------------------------------------------------------------------- 1 | const http = require('http'); 2 | const path = require('path'); 3 | const fs = require('fs'); 4 | const server = require('../fileServer'); 5 | describe('API Endpoints', () => { 6 | let globalServer; 7 | 8 | beforeAll((done) => { 9 | if (globalServer) { 10 | globalServer.close(); 11 | } 12 | globalServer = server.listen(3000); 13 | done() 14 | }); 15 | 16 | afterAll((done) => { 17 | globalServer.close(done); 18 | }); 19 | 20 | describe('GET /files', () => { 21 | test('should return a list of files', async () => { 22 | const options = { 23 | method: 'GET', 24 | path: '/files' 25 | }; 26 | const response = await sendRequest(options); 27 | 28 | expect(response.statusCode).toBe(200); 29 | expect(response.body.length).toBeGreaterThan(2); 30 | }); 31 | 32 | test('should handle internal server error', async () => { 33 | const options = { 34 | method: 'GET', 35 | path: '/files' 36 | }; 37 | 38 | const directoryPath = path.resolve(__dirname, '../files/'); 39 | jest 40 | .spyOn(fs, 'readdir') 41 | .mockImplementation((directoryPath, callback) => { 42 | callback(new Error('Mocked Internal Server Error'), null); 43 | }); 44 | 45 | const response = await sendRequest(options); 46 | 47 | expect(response.statusCode).toBe(500); 48 | 49 | fs.readdir.mockRestore(); 50 | }); 51 | }); 52 | 53 | describe('GET /file/:filename', () => { 54 | const testFilePath = path.join(__dirname, '../files', 'test-file.txt'); 55 | 56 | beforeAll(() => { 57 | fs.writeFileSync(testFilePath, 'Test file content'); 58 | }); 59 | 60 | afterAll(() => { 61 | fs.unlinkSync(testFilePath); 62 | }); 63 | 64 | test('should serve the requested file', async () => { 65 | const options = { 66 | method: 'GET', 67 | path: '/file/test-file.txt' 68 | }; 69 | const response = await sendRequest(options); 70 | 71 | expect(response.statusCode).toBe(200); 72 | expect(response.body).toBe('Test file content'); 73 | }); 74 | 75 | test('should handle file not found', async () => { 76 | const options = { 77 | method: 'GET', 78 | path: '/file/non-existing-file.txt' 79 | }; 80 | const response = await sendRequest(options); 81 | 82 | expect(response.statusCode).toBe(404); 83 | expect(response.body).toBe('File not found'); 84 | }); 85 | 86 | }); 87 | 88 | describe('Invalid Routes', () => { 89 | test('should return 404 for invalid routes', async () => { 90 | const options = { 91 | method: 'GET', 92 | path: '/invalid' 93 | }; 94 | const response = await sendRequest(options); 95 | 96 | expect(response.statusCode).toBe(404); 97 | expect(response.body).toBe("Route not found"); 98 | }); 99 | }); 100 | }); 101 | 102 | 103 | 104 | function sendRequest(options, requestBody) { 105 | return new Promise((resolve, reject) => { 106 | const req = http.request( 107 | { 108 | ...options, 109 | host: 'localhost', 110 | port: 3000, 111 | }, 112 | (res) => { 113 | let body = ''; 114 | 115 | res.on('data', (chunk) => { 116 | body += chunk; 117 | }); 118 | 119 | res.on('end', () => { 120 | resolve({ 121 | statusCode: res.statusCode, 122 | headers: res.headers, 123 | body, 124 | }); 125 | }); 126 | } 127 | ); 128 | 129 | req.on('error', (err) => { 130 | reject(err); 131 | }); 132 | 133 | if (requestBody) { 134 | req.write(requestBody); 135 | } 136 | 137 | req.end(); 138 | }); 139 | } 140 | -------------------------------------------------------------------------------- /Finishing School/fullstack_app.md: -------------------------------------------------------------------------------- 1 | # Full-Stack Development Projects for College Students 2 | 3 | These projects are designed to help college students learn full-stack development using **HTML, CSS, JavaScript**, and **Node.js**. Each project should be uploaded to GitHub with proper documentation and setup instructions. 4 | 5 | --- 6 | 7 | ## Date: 3rd January 8 | 9 | ### Solve the issue in the attendance app: [Attendance App GitHub Link](https://github.com/elevatebox/opensource/tree/main/attendance_app) 10 | 11 | --- 12 | 13 | ## 1. Assignment Tracker 14 | 15 | ### Frontend Components 16 | - Responsive UI built with HTML, CSS, and JavaScript 17 | - Features: 18 | - Assignment management (add, view, edit, delete) 19 | - Interactive date picker for deadlines 20 | - Color-coded calendar visualization 21 | 22 | ### Backend Implementation 23 | - Node.js RESTful APIs for CRUD operations 24 | - Data Structure (`database.json`): 25 | ```json 26 | { 27 | "assignments": [ 28 | { 29 | "id": "unique-id", 30 | "title": "string", 31 | "description": "string", 32 | "deadline": "date", 33 | "status": "string" 34 | } 35 | ] 36 | } 37 | ``` 38 | 39 | ### Key Features 40 | - CORS implementation for frontend-backend communication 41 | - Static file serving through Node.js 42 | - Error handling and input validation 43 | 44 | ## 2. College Event Portal 45 | 46 | ### Frontend Components 47 | - Event listing and detail views 48 | - Registration form interface 49 | - Personal dashboard for registered events 50 | 51 | ### Backend Implementation 52 | - Node.js APIs for event management and registrations 53 | - Data Structure (`database.json`): 54 | ```json 55 | { 56 | "events": [ 57 | { 58 | "id": "unique-id", 59 | "name": "string", 60 | "date": "date", 61 | "location": "string", 62 | "description": "string" 63 | } 64 | ], 65 | "registrations": [ 66 | { 67 | "eventId": "string", 68 | "studentName": "string", 69 | "studentEmail": "string" 70 | } 71 | ] 72 | } 73 | ``` 74 | 75 | ### Key Features 76 | - Secure CORS configuration 77 | - Frontend and backend form validation 78 | - Response status handling 79 | 80 | ## 3. Study Buddy Finder 81 | 82 | ### Frontend Components 83 | - Profile creation and editing interface 84 | - Search functionality by courses/interests 85 | - Matched profiles display 86 | 87 | ### Backend Implementation 88 | - User profile and search APIs 89 | - Data Structure (`database.json`): 90 | ```json 91 | { 92 | "profiles": [ 93 | { 94 | "id": "unique-id", 95 | "name": "string", 96 | "email": "string", 97 | "courses": ["array"], 98 | "interests": ["array"] 99 | } 100 | ] 101 | } 102 | ``` 103 | 104 | ### Key Features 105 | - Basic authentication system 106 | - CORS security implementation 107 | - Profile data validation 108 | 109 | ## 4. Expense Splitter 110 | 111 | ### Frontend Components 112 | - Group creation and management interface 113 | - Expense entry and splitting functionality 114 | - Balance dashboard 115 | 116 | ### Backend Implementation 117 | - Group and expense management APIs 118 | - Data Structure (`database.json`): 119 | ```json 120 | { 121 | "groups": [ 122 | { 123 | "id": "unique-id", 124 | "name": "string", 125 | "members": ["array"] 126 | } 127 | ], 128 | "expenses": [ 129 | { 130 | "groupId": "string", 131 | "description": "string", 132 | "amount": "number", 133 | "paidBy": "string" 134 | } 135 | ] 136 | } 137 | ``` 138 | 139 | ### Key Features 140 | - Expense calculation logic 141 | - CORS configuration 142 | - Data validation and error handling 143 | 144 | ## GitHub Submission Requirements 145 | 146 | 1. **Repository Structure** 147 | - Separate folders for frontend and backend 148 | - Clear README.md with setup instructions 149 | - .gitignore file for node_modules and environment files 150 | -------------------------------------------------------------------------------- /assignments/fs_typescript/assignment-2/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/01-easy-todo-app/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/full_stack/02-medium-course-selling-app-admin-dashboard/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assignments/nodejs/solutions/todoServer.solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | You need to create an express HTTP server in Node.js which will handle the logic of a todo list app. 3 | - Don't use any database, just store all the data in an array to store the todo list data (in-memory) 4 | - Hard todo: Try to save responses in files, so that even if u exit the app and run it again, the data remains (similar to databases) 5 | 6 | Each todo has a title and a description. The title is a string and the description is a string. 7 | Each todo should also get an unique autogenerated id every time it is created 8 | The expected API endpoints are defined below, 9 | 1.GET /todos - Retrieve all todo items 10 | Description: Returns a list of all todo items. 11 | Response: 200 OK with an array of todo items in JSON format. 12 | Example: GET http://localhost:3000/todos 13 | 14 | 2.GET /todos/:id - Retrieve a specific todo item by ID 15 | Description: Returns a specific todo item identified by its ID. 16 | Response: 200 OK with the todo item in JSON format if found, or 404 Not Found if not found. 17 | Example: GET http://localhost:3000/todos/123 18 | 19 | 3. POST /todos - Create a new todo item 20 | Description: Creates a new todo item. 21 | Request Body: JSON object representing the todo item. 22 | Response: 201 Created with the ID of the created todo item in JSON format. eg: {id: 1} 23 | Example: POST http://localhost:3000/todos 24 | Request Body: { "title": "Buy groceries", "completed": false, description: "I should buy groceries" } 25 | 26 | 4. PUT /todos/:id - Update an existing todo item by ID 27 | Description: Updates an existing todo item identified by its ID. 28 | Request Body: JSON object representing the updated todo item. 29 | Response: 200 OK if the todo item was found and updated, or 404 Not Found if not found. 30 | Example: PUT http://localhost:3000/todos/123 31 | Request Body: { "title": "Buy groceries", "completed": true } 32 | 33 | 5. DELETE /todos/:id - Delete a todo item by ID 34 | Description: Deletes a todo item identified by its ID. 35 | Response: 200 OK if the todo item was found and deleted, or 404 Not Found if not found. 36 | Example: DELETE http://localhost:3000/todos/123 37 | 38 | - For any other route not defined in the server return 404 39 | 40 | Testing the server - run `npm run test-todoServer` command in terminal 41 | */ 42 | const express = require('express'); 43 | const bodyParser = require('body-parser'); 44 | 45 | const app = express(); 46 | 47 | app.use(bodyParser.json()); 48 | 49 | let todos = []; 50 | 51 | app.get('/todos', (req, res) => { 52 | res.json(todos); 53 | }); 54 | 55 | app.get('/todos/:id', (req, res) => { 56 | const todo = todos.find(t => t.id === parseInt(req.params.id)); 57 | if (!todo) { 58 | res.status(404).send(); 59 | } else { 60 | res.json(todo); 61 | } 62 | }); 63 | 64 | app.post('/todos', (req, res) => { 65 | const newTodo = { 66 | id: Math.floor(Math.random() * 1000000), // unique random id 67 | title: req.body.title, 68 | description: req.body.description 69 | }; 70 | todos.push(newTodo); 71 | res.status(201).json(newTodo); 72 | }); 73 | 74 | app.put('/todos/:id', (req, res) => { 75 | const todoIndex = todos.findIndex(t => t.id === parseInt(req.params.id)); 76 | if (todoIndex === -1) { 77 | res.status(404).send(); 78 | } else { 79 | todos[todoIndex].title = req.body.title; 80 | todos[todoIndex].description = req.body.description; 81 | res.json(todos[todoIndex]); 82 | } 83 | }); 84 | 85 | app.delete('/todos/:id', (req, res) => { 86 | const todoIndex = todos.findIndex(t => t.id === parseInt(req.params.id)); 87 | if (todoIndex === -1) { 88 | res.status(404).send(); 89 | } else { 90 | todos.splice(todoIndex, 1); 91 | res.status(200).send(); 92 | } 93 | }); 94 | 95 | // for all other routes, return 404 96 | app.use((req, res, next) => { 97 | res.status(404).send(); 98 | }); 99 | 100 | module.exports = app; 101 | --------------------------------------------------------------------------------