multiple awaits are running in parallel

I’m trying to learn async/await and promises and unable to make run multiple async functions in serial.

function firstFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('first'), 2000)
    resolve()
  })
}

function secondFunction () {
  return new Promise((resolve, reject) => {
    setTimeout(() => console.log('second'), 1000)
    resolve()
  })
}

async function main() {
  await firstFunction()
  await secondFunction()
}

main()

Output I am getting is

second
first

Since there’s an await for firstFunction(), I’d expect the promise of firstFunction() to finish before going to secondFunction().

Can someone point out why they ran in parallel and how to make them run one after the other? (ran in node v18.3.0)

Why the container height inside the react-virtualized is not fitting according to the text length?

I am building a chat application with react-virtualized. I am facing a problem, the container is not taking up the required height for the text to properly fit, rather it is somewhat bigger than necessary.

As it is a chat-app so the length of the text varies.

Here is the code sandbox link

Here is the code for it.

const MessageComponent = () => {

  const cache = new CellMeasurerCache({
    defaultHeight: 10,
    minHeight: 20,
    defaultWidth: 100,
  });

  function giveMargin(index: number) {
    const item: any = messageData[index];

    if (index === messageData.length - 1 || item?.type === "date")
      return "large-margin";
    const nextItem: any = messageData[index + 1];
    if (item?.sender?._id === nextItem?.sender?._id) {
      return "small-margin";
    }
    return "large-margin";
  }


  useEffect(() => {
    if (!messageData.length) return;

    scroll?.current?.scrollToRow(messageData.length);
  }, [messageData.length]);

  const renderRow = ({ index, key, style, parent }: any) => {
    const item: any = messageData[index];
    const isUserChat = item?.sender?._id === user._id;
    const className =
      item.type == "date"
        ? "date"
        : isUserChat
        ? "user-message"
        : "sender-message";

    const margin = giveMargin(index);

    return (
      <CellMeasurer
        key={key}
        cache={cache}
        parent={parent}
        columnIndex={0}
        rowIndex={index}
      >
        {({ registerChild, measure }) => (
           <div ref={registerChild} style={style} className={className}>
           <div className={
          isUserChat
            ? `text-container user ${margin}`
            : `text-container sender ${margin}`
        }
      >
        <span className="content">
          {item.content} {item.content.length}
        </span>
      </div>
    </div>
        )}
      </CellMeasurer>
    );
  };

  return (
    <>
      <div style={{ height: "calc(100vh - 92px)" }} className="virtual-list">
        <AutoSizer>
          {({ width, height }) => {
            return (
              <VirtualList
                width={width}
                height={height}
                rowHeight={cache.rowHeight}
                deferredMeasurementCache={cache}
                rowRenderer={renderRow}
                rowCount={messageData.length}
                ref={scroll}
              />
            );
          }}
        </AutoSizer>
      </div>
    </>
  );
};

export default MessageComponent;

enter image description here

app.use(bRoutes.routes()); ReferenceError: bRoutes is not defined Node.js v18.4.0 [nodemon] app crashed – waiting for file changes before starting

Backend
package.json

 {
  "name": "af-koa-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@koa/cors": "^3.3.0",
    "dotenv": "^16.0.1",
    "koa": "^2.13.4",
    "koa-bodyparser": "^4.3.0",
    "koa-json": "^2.0.2",
    "koa-router": "^10.1.1",
    "mongoose": "^6.4.0",
    "nodemon": "^2.0.18"
  }
}

.env

MONGODB_URL=mongodb://localhost:27017/managementdb

index.js

require("dotenv").config(); 
const Koa = require("koa");
const KoaRouter = require("koa-router");
const cors = require("@koa/cors");
const bodyParser = require("koa-bodyparser");
const json = require("koa-bodyparser");

const { dbConnect } = require("./utils/dbConnect");        //connect all the routes
const courseRoutes = require("./routes/course.routes");
const studentRoutes = require("./routes/student.routes");
const calculationRoutes = require("./routes/calculation.routes");
const registerRoutes = require("./routes/register.routes");

const app = new Koa();
const router = new KoaRouter();

app.use(cors());
app.use(bodyParser());
app.use(json());
app.use(router.routes()).use(router.allowedMethods());

app.use(courseRoutes.routes()); //connect routes
app.use(studentRoutes.routes());
app.use(calculationRoutes.routes());
app.use(registerRoutes.routes());


router.get("/", (ctx) => {
  ctx.body = { message: "Student Management API" };
});

app.listen(9000, () => {
  dbConnect();
  console.log(`Server is up and running on http://localhost:9000`);
});

utils/dbConnect.js

   const mongoose = require("mongoose"); 
    
     const dbConnect = () => {
      const dbConStr = process.env.MONGODB_URL;
    
     mongoose.connect(dbConStr, () => {
        console.log("Database connected");
      });
    };
    
    module.exports = { dbConnect };

models/calculation.model.js

 const mongoose = require("mongoose");
    
    const CalculationSchema = new mongoose.Schema({
       
        Paymentid: {type : String,required: true},
        Basicsalary: {type : Number, required: true},
        OT:{type : Number,required: true},
        Vehicleallowance: {type: Number, required: true},
        Netsalary: { type: Number,}
    });
    
    const Calculation = mongoose.model("calculations", CalculationSchema);
    
    module.exports = Calculation;

models/course.model.js

const mongoose = require("mongoose");

const CourseSchema = new mongoose.Schema({
  courseName: { type: String, required: true },
  courseFee: { type: Number, required: true },
  students: [{ type: mongoose.Schema.Types.ObjectId, required: false, ref: "students" }], //student list in relavant group,//use [] because it is a array,it is a id
});

const Course = mongoose.model("courses", CourseSchema);

module.exports = Course;

models/register.model.js

const mongoose = require("mongoose");

   const RegisterSchema = new mongoose.Schema({
    Name: {type : String,required: true},
    Password :{type : String,required: true},
 
   });

   const Register = mongoose.model("register", RegisterSchema);

   module.exports = Register;

models/student.model.js

const mongoose = require("mongoose");

 const StudentSchema = new mongoose.Schema({
  name: { type: String, required: true },
  nic: { type: String, required: true },
  age: { type: Number, required: true },
  courseId: { type: mongoose.Schema.Types.ObjectId, required: false, ref: "courses" }, //store a id
});

 const Student = mongoose.model("students", StudentSchema);

 module.exports = Student;

controller/calculation.controller.js

const Calculation= require("../models/calculation.model");

const addCalculation= async (ctx) => {
  try {
    const {Paymentid, Basicsalary, OT ,Vehicleallowance,Netsalary} = ctx.request.body; 

    const calculation = await Calculation.create({
        
       
        Paymentid: Paymentid,    
        Basicsalary: Basicsalary,
        OT: OT,
        Vehicleallowance:Vehicleallowance,
        Netsalary:Netsalary,
    });

    return (ctx.body = calculation);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};



const getCalculations = async (ctx) => {
  try {
    const calculations = await Calculation.find({})
    return (ctx.body = calculations);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};



const updateCalculation= async (ctx) => {
  try {
    const calculationId = ctx.params.calculationId;

    const {Paymentid, Basicsalary, OT ,Vehicleallowance,Netsalary } = ctx.request.body;
    const calculation = await Calculation.findByIdAndUpdate(calculationId, { //calculationId should be same as the id in url(in routes url)
       
        Paymentid: Paymentid,   
        Basicsalary: Basicsalary,
        OT: OT,
        Vehicleallowance:Vehicleallowance,
        Netsalary:Netsalary,
    });

    return (ctx.body = calculation);

  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};


const deleteCalculation= async (ctx) => {
  try {
    const calculationId = ctx.params.calculationId;
    const calculation = await Calculation.findByIdAndDelete(calculationId);
    return (ctx.body = calculation);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};


module.exports = {
  addCalculation,
  getCalculations,
  updateCalculation,
  deleteCalculation,
};

controller/course.controller.js

const Course = require("../models/course.model");

const addCourse = async (ctx) => {
  try {
    const { courseName, courseFee, students } = ctx.request.body; //data in the model

    const course = await Course.create({
      courseName: courseName,    //data in the model
      courseFee: courseFee,
      students: students,
    });

    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getCourses = async (ctx) => {
  try {
    const courses = await Course.find({}).populate({ path: "students", select: "name nic age" });//path ekata dila tynne mekata adala model eke ref tag eka thiyana eke attribute eka(ref""athule tyna eka newi)
    return (ctx.body = courses);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const updateCourse = async (ctx) => {
  try {
    const courseId = ctx.params.courseId;

    const { courseName, courseFee, students } = ctx.request.body;
    const course = await Course.findByIdAndUpdate(courseId, { //courseId should be same as the id in url(in routes url)
      courseName: courseName,
      courseFee: courseFee,
      students: students,
    });
    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const deleteCourse = async (ctx) => {
  try {
    const courseId = ctx.params.courseId;
    const course = await Course.findByIdAndDelete(courseId);
    return (ctx.body = course);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

module.exports = {
  addCourse,
  getCourses,
  updateCourse,
  deleteCourse,
};

controller/register.controller.js

const Register= require("../models/register.model");

const addRegister= async (ctx) => {
  try {
    const {  Name,Password} = ctx.request.body; //data in the model

    const register= await Register.create({
       Name:Name,
        Password:Password,



    });

    return (ctx.body = register);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};



module.exports = {
  addRegister,
  
};

controller/student.controller.js

const Student = require("../models/student.model");
const Course = require("../models/course.model"); //need for 14th statement

const addStudent = async (ctx) => {
  try {
    const { name, nic, age, courseId } = ctx.request.body;
    const student = await Student.create({
      name,
      nic,
      age,
      courseId,
    });

    await Course.findByIdAndUpdate(courseId, { $push: { students: student._id } });//course is also update after insert a student,students is attribute in model,student._id push to the cource
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const getStudents = async (ctx) => {
  try {
    const students = await Student.find().populate({ path: "courseId",select: "courseName courseFee", });
    return (ctx.body = students);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const updateStudent = async (ctx) => {
  try {
    const studentId = ctx.params.studentId;
    const { name, nic, age, courseId } = ctx.request.body;

    const student = await Student.findByIdAndUpdate(studentId, {
      name,
      nic,
      age,
      courseId,
    });

    await Course.findByIdAndUpdate(student.courseId, {
      $pull: { students: studentId },
    });

    await Course.findByIdAndUpdate(courseId, {
      $push: { students: studentId },
    });

    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

const deleteStudent = async (ctx) => {
  try {
    const studentId = ctx.params.studentId;

    const student = await Student.findById(studentId);

    await Course.findByIdAndUpdate(student.courseId, { $pull: { students: studentId } });
    await Student.findByIdAndDelete(studentId);
    return (ctx.body = student);
  } catch (error) {
    return (ctx.body = { message: error.message });
  }
};

module.exports = {
  addStudent,
  getStudents,
  updateStudent,
  deleteStudent,
};

routes/calculation.routes.js

const KoaRouter = require("koa-router");
const router = new KoaRouter({ prefix: "/calculation" }); //will add cource word to all methods
const {
  addCalculation,
 
  getCalculations,
  updateCalculation,
  deleteCalculation,
} = require("../controller/calculation.controller");

router.post("/add", addCalculation);
router.delete("/:calculationId", deleteCalculation);
router.put("/:calculationId", updateCalculation);
router.get("/", getCalculations);


module.exports = router;

routes/course.routes.js

const KoaRouter = require("koa-router");
const router = new KoaRouter({ prefix: "/course" }); //will add cource word to all methods
const {
  addCourse,
  getCourses,
  updateCourse,
  deleteCourse,
} = require("../controller/course.controller");

router.post("/add", addCourse);
router.delete("/:courseId", deleteCourse);
router.put("/:courseId", updateCourse);
router.get("/", getCourses);

module.exports = router;

routes/register.routes.js

const KoaRouter = require("koa-router");
const router = new KoaRouter({ prefix: "/register" }); //will add cource word to all methods
const {
  addRegister,
 
} = require("../controller/register.controller");

router.post("/add", addRegister);


module.exports = router;

routes/student.routes.js

const KoaRouter = require("koa-router");
const {
  addStudent,
  getStudents,
  updateStudent,
  deleteStudent,
} = require("../controller/student.controller");
const router = new KoaRouter({ prefix: "/student" });

router.post("/add", addStudent);
router.delete("/:studentId", deleteStudent);
router.put("/:studentId", updateStudent);
router.get("/", getStudents);

module.exports = router;

Reference of array inside another array (not an item of the other array)

This is probably a dumb question but whatever.

If have two arrays like this:

let a = [0,1,2];
let b = [0,1,2,3,4,5];

Is it possible that I can make changes in one happen in the other array as if they are the same place in memory but different lengths like you could in C? (in javascript)

What i want:

a[0] = 1;
console.log(b);
//[1,1,2,3,4,5];
console.log(a);
//[1,1,2];

Playwright use Page within the context of exposed function

I’m having trouble with Playwright’s expose_function API. I want to be able to also pass Page into exposed functions to be able to navigate, use locators etc. withing the context of exposed function.

The problem is Page instance in exposed function becomes somehow “disconnected” from it’s original, and doesn’t do navigations, locators etc. Any calls to Page methods appear to block indefinitely.

Consider this simplified example:

from playwright.sync_api import sync_playwright, Page
from functools import partial


def search_title(page: Page, title: str):
    print(title)
    page.goto(f"https://bing.com?q={title}")


def main():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(viewport={ 'width': 1920, 'height': 1024 })
        page = context.new_page()
        page.goto(f"https://wikipedia.org")
        context.expose_function("search_title", partial(handle_title, page))
        page.evaluate("window.onload = () => search_title(document.title)")
        while True:
            page.wait_for_timeout(1000)


if __name__ == "__main__":
    main()

What it does is prints the title, and halts at navigation step indefinitely.

Mongoose validate only one path

I have the following long schema:

const mySchema = new mongoose.Schema({
  // some stuff, firstName, lastName ... etc
  password: {
    type: String,
    minLength: 8,
    maxLength: 120,
  }
})

And I am inside one of the routes, I want to run validation on the password filed only.
Is there something that I can do in Mongoose such as:

mySchema.fields.password.validate("123") // Error: password is less than 8 characters!

Is there something like that?

Filling out a batch of pdfs using .txt on acrobat

I keep getting the error cannot open file. I have made this work on mac only. It is supposed to go through lines of the .txt file and fill out the pdf then save as the names. It saves loads of time as there are 70+ pdf’s I need to save. I have tried changing the “/” for the path to “” but that returns syntax error: unterminated string literal. It is asking me to add more details to post this so I will just add more words until it goes away.

   // specify the filename of the data file
var fileName = "/Users/rgivens/Documents/Courseware Audit Report.txt";     
    // the tab delimited text file containing the data
var outputDir = "/Users/rgivens/Desktop/Grade Change Form/";    // make sure this ends with a '/'

var err = 0;
var idx = 0;
while (err == 0) {
    err = this.importTextData(fileName, idx); // imports the next record
    if (err == -1) app.alert("Error: Cannot Open File"); 
    else if (err == -2) 
        app.alert("Error: Cannot Load Data"); 
    // else if (err == -3) 
        // We are not reporting this error because it does 
        // indicate the end of our data table: We've exhausted 
        // all rows in the data file and therefore are done with 
        // processing the file. Time to exit this loop. 
        // app.alert("Error: Invalid Row"); 
    else if (err == 1) 
        app.alert("Warning: User Cancelled File Select"); 
    else if (err == 2) 
        app.alert("Warning: User Cancelled Row Select"); 
    else if (err == 3) 
        app.alert("Warning: Missing Data"); 
    else if (err == 0) { 
        this.saveAs(outputDir + this.getField("Stu Name").value + "_" + this.getField("Stu Name 1").value + ".pdf"); // saves the file idx++; 
    }
}

Is it possible to add interactivity to the HTML body of the email in an Outlook Addin?

I’d like to develop an Outlook Add-in which adds some HTML content to the body of the email.
If the user has this add-in installed, I’d like to add interactivity to the elements (for instance, replacing anchor tags with actual buttons that could trigger either a command, or open a task panel).

This would make the UX better by managing the entire user flow directly from the email content, without having to visit an external app.

Currently. I noticed that doing the following will return the string of the HTML content. But there’s no way to actually addEventListener or replace elements in any way.

Office.context.mailbox.item.body.getAsync(Office.CoercionType.Html, callback)

If anyone could point me to the right direction, i’d appreciate it!

Material UI components not working in React JS project

this is my app.js code:

import React from "react";
import './App.css';
import {Button} from "@mui/material";
function App() {
  return (
    <div className="App">
      <h1>COVID-19 TRACKER</h1>
      <Button variant="outlined">Text</Button>
    </div>
  );
}

export default App;

it should display desired button but instead there is a blank screen enter image description here

And also there is an error in console logenter image description here

Kindly help me overcome this error

convert $_id to string on the fly

I have the following update query, I want to use the value of the _id field. However, I can’t, because _id is an ObjectId. and the field that I am writing on requires a string.

How to convert the _id to a string on the fly, within the request, in the concat function?

{ $concat: [`email`, ' #deleted(','$_id', ')'] }
  • I am using MongoDB in Mongoose In JavaScript.

full code if required:

await Model.findOneAndUpdate(req.params.id, [
    {
      $set: {
        email: {
          $concat: ['$email', ' #deleted(', '$_id', ')'],
        },
        _archived: Date.now(),
      },
    },
  ])

currently getting:

MongoServerError: Plan executor error during findAndModify :: caused
by :: $concat only supports strings, not objectId

Listen for Oculus controller events in any website

Is it possible for a webpage to listen for button presses of a Oculus controller simply using some generic javascript code like document.addEventListener?

In VR browsers by default the primary thumbstick scrolls the page up and down. The idea is to re-map it to trigger different actions.

From my research it looks like I need to use an A-frame but I’m looking for a generic solution that works across different websites with just Vanilla Javascript.

enter image description here

How smoothly break CSS animation on hover with CSS or JS?

  1. Can I smoothly break CSS-animation on hover with CSS or JS?
  2. Why transition don’t work after CSS-animation?

Example:

.button {
  animation: resizing 2000ms linear infinite alternate;
  transition: transform 200ms linear; // don't work after animation
}

@media (hover: hover) {
  .button:hover {
    animation: none;
    transform: scale(1.1);
  }
}

@keyframes resizing {
  100% {
    transform: scale(2);
  }
}

Public routes with parameters that do not require authentication do not work in express

function jwt() {
  const { secret } = config;
  return expressJwt({ secret, algorithms: ["HS256"] }).unless({
    path: [
      // public routes that don't require authentication
      "/users/authenticate",
      "/users/create",

      "/series/getAllSeries",

      "/series/getByIdSeries/:id",
      "/series/getByStreamingService/:streamingService",
      "/series/getMonthSeries/:monthPosition/:streamingServiceName?",
    ],
  });
}

This routes only work with token. The exception for them to work publicly does not work

"/series/getByIdSeries/:id",
"/series/getByStreamingService/:streamingService",
"/series/getMonthSeries/:monthPosition/:streamingServiceName?",