React JSX mapping components – render component order direction –> erratic behavior question

Below is my JSX in a react component. There is some strange behavior how the mapped components render and expand the parent container. When you add the first speakersComponent and it is mapped it will push the ItemButton (used to add speaker components) up. This causes the add button to move off screen. When you add subsequent speaker components, the parent container is expanded down. Sometimes it may act even more randomly and all the speaker components will be push the item button up because they are not expanding the container down. I don’t know what could be causing this. Ideally, I just want the ItemButton to remain in the same spot as the user clicks and all the speaker components expand the parent div down. I have another mapped component elsewhere that exhibits the same behaviour. Does anyone have insights regarding this kind of behaviour?

 <ItemButton
        handler={addSpeaker}
        text={CreateEvent.participants.addSpeaker}
        plusSign={true}
        lengthOn={true}
        propertyLength={renderIndex.length}
        lengthMax={6}
        icon={speaker}
        fullWidth={true}
        ariaLabel={CreateEvent.participants.addSpeaker}
        limit={6}
      />
      <div className="h24" />
      {renderIndex.map((componentIndex, index) => {
        return (
          <div key={componentIndex}>{speakersComponentMap[componentIndex]}</div>
        );
      })}

here is the SASS / CSS i am using for the parent div that holds both components:

.parent-div {
    display: flex;
    flex-direction: column;
    position: relative;
    border: 2px solid rgba(0, 0, 0, 0.25);
    padding: 48px 78px 48px 78px;
    border-radius: $br--standard;
    margin-bottom: 48px;
    box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.25);
    min-width: 1036px;
    max-width: 1036px;

    &:focus-visible {
      outline: $access-ob;
      outline-offset: $access-o6;
    }

    @media (max-width: $mobile) {
      min-width: 85vw;
      max-width: 85vw;
      padding: 36px;
    }

    @media (max-width: $phone) {
      padding: 12px 0px 36px 0px;
      padding-left: 2vw;
      padding-right: 2vw;
      min-width: 100vw;
      max-width: 100vw;
      border: 0px;
      border-radius: 0px;
      border-top: 2px solid rgba(0, 0, 0, 0.25);
      border-bottom: 2px solid rgba(0, 0, 0, 0.25);
      box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.15);
    }
}

I tried adjusting the CSS to flex-grow, experimented with fit-content, column, column-reverse etc. I can’t seem to figure out any css properties that changes the behaviour.

Remove promise callbacks from video events

There is a problem with following code.

async function loadVideo (src, crossOrigin)
{
   let video  = makeVideo (src, crossOrigin);

   return new Promise((resolve, reject) =>
   {
       Promise.allSettled ([
            new Promise ( (resolve, reject) => {video.addEventListener('playing',     () => {resolve(1);}, true )}   ),
            new Promise ( (resolve, reject) => {video.addEventListener('timeupdate',  () => {resolve(1);}, true )}   )   ])
            .then((values) => 
       {
         resolve(video);
       });
   });
}

I use the code for creating webgl2 textures. The problem is that event callbacks for playing is called ever again when video begins, and timeupdate event is called permanently. It doesn’t cause big nor visible issues, but I need them to be called only once. Is there a way to remove listeners after first invocation?

See full code in following snippet:

function makeVideo (src, crossOrigin)
{
   let video  = document.createElement("video");
   if (crossOrigin) video.crossOrigin  =  crossOrigin;
   video.src         =  src;
   video.autoplay    = true;
   video.playsInline = true;
   video.muted       = true;
   video.loop        = true;
   video.play();
   return video;
}

async function loadVideo (src, crossOrigin)
{
   let video  = makeVideo (src, crossOrigin);
   video.width = 300;
   return new Promise((resolve, reject) =>
   {
       Promise.all ([
            new Promise ( (resolve, reject) => {video.addEventListener('playing',     () => {resolve(1);}, true )}   ),
            new Promise ( (resolve, reject) => {video.addEventListener('timeupdate',  () => {resolve(1);}, true )}   )   ])
            .then((values) => 
       {
         resolve(video);
       });
   });
}
document.addEventListener('DOMContentLoaded', async () => 
{
   loadVideo ("https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4")
      .then(vd => {document.body.appendChild(vd)});
});

Mongoose find() not returning all parts of document

I am trying to retrieve user information from a MongoDB database, and whenever I use find() the return value is empty. To make it weirder, findOne returns an object with only the ’email’ property. I have wasted too much time here please help xD. I’m also using Next.js with next-auth

[…nextauth].js

...
async authorize(credentials) {
        try {
          await dbConnect();

          const user = await User.find({}).exec();

          return user;
...

Mongoose Schema
User.js

import mongoose from "mongoose";

const Schema = mongoose.Schema;

const userSchema = new Schema ({
    email: {
      type: String,
      required: true,
      unique: true
    },
    password: {
      type: String,
      required: true
    },
    roles: [{
      type: String
    }],
  }, {
    collection: 'users',
    timestamps: true
  }
);
userSchema.index({ email: 1 }, { unique: true});

const User = mongoose.models.User || mongoose.model("User", userSchema);
export default User;

and yeah, if I use findOne instead of find, I get an object with only the email property

Recreated collection
Schema.add in User.js
Projection with find()

Vue packages version mismatch when trying to use @component plugin from better-docs

I want to add jsdoc to my vue project after adding @component plugin from better-docs. I face error.

Error message:
`
Vue packages version mismatch:

  • [email protected] (C:UserspatreOneDrivePulpitWorkinstoreappnode_modulesvueindex.js)
  • [email protected] (C:UserspatreOneDrivePulpitWorkinstoreappnode_modulesvue-template-compilerpackage.json)

This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@>=10.0, simply update vue-template-compiler.
If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
`

jsdoc.json
{ "plugins": [ "node_modules/better-docs/component" ], "source": { "includePattern": "\.(vue|js)$", "include": [ "./src/App.vue" ] }, "sourceType": "module", "recurseDepth": 10, "opts": { "destination": "./docs/App.vue", "recurse": true }, "tags": { "allowUnknownTags": true, "dictionaries": [ "jsdoc", "closure" ] }, "templates": { "cleverLinks": false, "monospaceLinks": false } }

package.json

"dependencies": { "@glidejs/glide": "^3.6.0", "@vitejs/plugin-legacy": "^4.0.4", "@vueuse/components": "^10.1.2", "@vueuse/core": "^10.1.2", "pinia": "^2.1.3", "vue": "^3.3.4", "vue-router": "^4.2.2" }, "devDependencies": { "@vitejs/plugin-vue": "^4.2.3", "@vue/compiler-sfc": "^3.3.4", "better-docs": "^2.7.2", "jsdoc": "^4.0.2", "sass": "^1.62.1", "terser": "^5.17.7", "vite": "^4.3.9" }

I want to have jsdoc comments in .vue files. (There is no need for vue syntax support)

I tried to install vue-loader and vue-template-compiler as dependencies but it didn’t change anything. I also tried to delete node_modules and package-lock.json and try to install it again.

circular dependency and updateMany is not a function errors in mongoose

I have two files, questions.js and users.js, both of which are Mongoose models. I have implemented pre and post functions that are triggered before and after a save event. For example, when I save a user, it successfully updates the “evaluation” list attribute with the available topics from the “topics” document.

However, I encounter an issue when I add a new topic. The post function fails (that is supposed to push into the evaluation list of all the users the new topic), and I receive the following error message:
Warning: Accessing non-existent property 'updateMany' of module exports inside circular dependency TypeError: User.updateMany is not a function.

Upon investigation, I noticed that the circular dependency is caused because topic.js imports users.js and users.js imports topic.js. I need this mutual import because both models require access to each other for their respective pre and post save methods.

I’m not sure if the circular dependency is directly causing the “updateMany is not a function” error. How can I resolve this issue and ensure that the pre and post functions work correctly without the error?
topics.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const User = require("./users")

const questionAnswerSchema = new Schema({
    question: {
      type: String,
      required: true
    },
    answers: {
      type: [String],
      required: true
    }
  },{_id: false});
  
  const Topics = new Schema({
    name: {
      type: String,
      required: true,
      unique: true
    },
    questionAnswers: {
      type: [questionAnswerSchema],
      required: true
    }
  });

  Topics.post('save', async function (doc, next) {
    try {
      const updatedTopic = doc.toObject();
      await User.updateMany({}, { $push: { evaluations: { name: updatedTopic.name, correctAnswers: 0, wrongAnswers: 0 } } });
    } catch (error) {
       next(error)
    }
  });
  
  const Topic = mongoose.model("topic", Topics);
  module.exports = Topic;

users.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs')
const Topic = require('./topics.js')

const Topics = new Schema({
  name: {
    type: String,
    required: "The topic requires a name",
  },
  correctAnswers: {
    type: Number,
    default: 0
  },
  wrongAnswers: {
    type: Number,
    default: 0
  }
})

const User = new Schema({
  name: {
    type: String,
    required: "The user requires a name",
    unique: true
  },
  password: {
    type: String,
    required: "The user requires a password"
  },
  evaluations: {
    type: [Topics],
    default: []
  }
});

User.pre('save', function(next) {
  let user = this;
  if (!user.isModified('password')) return next();
  bcrypt.genSalt(10, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(user.password, salt, null, (err, hash) => {
      if (err) return next(err);
      user.password = hash;
      next();
    });
  });
});

User.pre('save', async function(next) {
  if (this.isNew) {
    try {
      const topics = await Topic.find().select('name').lean();
      this.evaluations = topics.map(topic => ({
        name: topic.name,
        correctAnswers: 0,
        wrongAnswers: 0
      }));
    } catch (err) {
      return next(err);
    }
  }
  next();
});

const User = mongoose.model("user", User);
module.exports = User;

How can I make tabs in my angularJS application look like this?

I have implemented some tabs in my AngularJS application like this:

enter image description here

I would like to style them so they look like this:

enter image description here

I’m not sure how to do that though. Here is the code:

<tabset justified="false" type="tabs">
  <tab>
    <tab-heading class="clickable" bindonce>
      <span bo-bind="'tab 1'"></span>
    </tab-heading>
    ...
  </tab>
  <tab>
    <tab-heading class="clickable" bindonce>
      <span bo-bind="'tab 2'"></span>
    </tab-heading>
    ...
  </tab>
  <tab>
    <tab-heading class="clickable" bindonce>
      <span bo-bind="'tab 3'"></span>
    </tab-heading>
    ...
  </tab>
</tabset>

I have tried adding styles to the tab tag and the tab-header tag to no effect.

How does one style the elements in AngularJS?

Thanks!

Export data in react v6 & react-router-dom 6.14.0 between 2 class components

I’m making a Quiz Game, and I need to send the results of the quiz since Play.js to QuizSummary.js

My Play.js looks like:

import React, { Component, Fragment} from "react";
import withRouter from "../../withRouter"

//[More code]

class Play extends Component {


//[More code]

    endGame = () => {
        const { navigate } = this.props

        alert('Quiz has ended!');
        const { state } = this;
        const playerStats = {
            score: state.score,
            numberOfQuestions: state.numberOfQuestions,
            numberOfAnsweredQuestions: state.numberOfAnsweredQuestions,
            correctAnswers: state.correctAnswers,
            wrongAnswers: state.wrongAnswers,
            fiftyFiftyUsed: 2 - state.fiftyFifty,
            hintsUsed: 5 - state.hints
        };
        console.log(playerStats)
        setTimeout(() => {
            navigate('/play/quizSummary', {state:{playerStats}});
        }, 1000);
    }


//[Rest of the code]

And my QuizSummary.js looks like:

import React, {Component} from "react";

class QuizSummary extends Component {
    constructor (props) {
        super(props);
        this.state = {
            score: 0,
            numberOfQuestions: 0,
            numberOfAnsweredQuestions: 0,
            correctAnsewers: 0,
            wrongAnswers: 0,
            usedHints: 0,
            usedFiftyFifty: 0
        };
    }
    render () {
        console.log(this.props.playerStats)
        return (
            <h1>Hello from Quiz QuizSummary</h1>
        );
    }
}
export default QuizSummary;

I want that when I finish the game, I redirect to the summary page (that works fine) & send the data to display the results. But when I check-it the console displays like “undefined”.

How I can send the data in endGame() function to the QuizSummary.js?

Correct way of setting hidden value fields in javascript

in javascript i am using this code to set the value of some hidden fields on a page that is not mine

let hiddenField = document.querySelectorAll('input[type="hidden"].class1');
for (k = 0; k < hiddenField.length; k++) {
        console.log("previous value: " + hiddenField[k].value);
        hiddenField[k].value = hiddenValue;
        console.log("new value: " + hiddenField[k].value);
        console.log(hiddenField[k]);
}

The problem is that only one of the two hidden values is being correctly setted, in fact the output I obtain on the console is

previous value: 0
new value: 4.5
<input type=​"hidden" name=​"left.result.0.stars" class=​"class1" value=​"4.5">​
previous value: 0
new value: 4.5
 <input type=​"hidden" name=​"right.result.0.stars" class=​"class1" value=​"0">​

as you can see when I print hiddenField[k].value the value is correctly setted but when I print the element on the console the value has been not setted, what can be the problem?

How to remove last saved cheche element click

How many times I click the buttons, it will get all clicked count, and put that elements on my table tr!
I want to for each button click once time and added to my table tr without duplicated data!
if you didn’t here the example

$("body").on("click", "button.list_of_drugs_main", function() {
  var l_drug_id = $(this).attr("data-did");
  var l_drug_generic_name = $(this).text().trim();

  for (var i = 0; i < $(".pt_list_table_tbody tr").length; i++) {
    var ef = $(".pt_list_table_tbody tr")[i];
    if ($(ef).hasClass("drug_id_" + l_drug_id)) {
      //console.log(1);
    } else {
      //console.log(0);
      $(".pt_list_table_tbody").append("<tr class=' drug_id_" + l_drug_id + "'><td>" + l_drug_id +
        "</td><td>" + l_drug_generic_name + "</td></tr>");
    }
  }
});
table {
  border-collapse: collapse;
  margin-top: 10px;
}

table td,
table th {
  border: 1px solid green;
  padding: 6px;
  text-align: right;
}
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

<button type="button" class="list_of_drugs_main" data-did='1'>Drug 1</button><br>
<button type="button" class="list_of_drugs_main" data-did='2'>Drug 2</button><br>
<button type="button" class="list_of_drugs_main" data-did='3'>Drug 3</button>

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Drug Name</th>
    </tr>
  </thead>
  <tbody class="pt_list_table_tbody">
    <tr></tr>
  </tbody>
</table>

I want to: when I Click the button/s add|append button/s details into my table rows without duplicated rows! thanks

Sitemap showing breakage in structure (layout) when adding hreflang

My Sitemap was showing correctly both its operation and its layout, but after inserting the attribute xhtml:link rel="alternate" the same start to be displayed in a strange way
Sitemap structure with xtml:link

However, when checking the source code of this page, its content presents correctly.

  • How to maintain the layout correctly? it looks like the Html is interpreting the attribute and breaking the layout;
  • Does this affect the Site’s performance on Google?

I expected the structure to be presented correctly

Receive data to UDP server, parse them, trasnfer them to JSON and post them to RESTAPI

I have a quite complex question (at least from my perspective). I am a beginner in node .js but I have a difficult task.

I need to create UDP server where I will be able to send a packet. The packet must be parsed and converted based on specifications that I have. After that It should be converted to json format and sent through the UDP server to REST API. The JSON format should look like this or at least this structure this API accepts.

I have a specific gatewayID of the API which I cant post here but I will give an example: 1000000000000003, then I have also APIUrl which will be for example this: api.com/api. I tried many codes and I have even tried ChatGPT but I still can’t figure out how to process the data correctly so the restAPI will accept them. If I add the json structure as fixed package it works and I am able to send it but I am unable to make the correct processing of data and I am not even sure how to send them to the UDP server so that it accepts and converts them correctly. I was told that the data will be received in hex I think and it should read it analyze it, process it, transfer it to json and send it to API. I am really hopeless since I have no idea how else I could do it. I have been programming in node js. for a week so please consider it that I am complete beginner. Thank you for understanding and for any help. I will be very grateful.

Structure of json data which API accepts (gatewayID of packet is different for each packet and different from API gatewayID):

{        
    "gatewayId": "1111111111111112",
    "devices": [

            {
                "id": "EDCVIRTUAL06",
                "packetId": 12,
                "deviceType": 6,
                "energyFence": 73,
                "voltageFence": 12.5,
                "voltageSource": 25,
                "voltageBattery": 14.2,
                "voltageFenceLowTreshold": 7800,
                "powerOutput": 50,
                "voltageGround": 2.54,
                "impedance": 0,
                "faults": 0,
                "state": 2,
                "signal": 0,
                "vFenAvg": 65535,
                "vFenMin": 65535,
                "vFenMax": 65535,
                "impMin": 65535,
                "impMax": 65535,
                "latitude": 48.88539020710477,
                "longitude": 16.051812954246998
            }
        ]
}

There is the specification for the data and for parsing the data:

spec1

spec2

spec3

I tried this and many other versions. I think there is also a problem when I send the data from console because I don’t really know how to send them.

How I tried to send data:
echo 0200000000000000000000C2020C00130232002C010000FFFFFFFF31302E303030313138 | ncat -u 127.0.0.1 12345

My current code:

const dgram = require('dgram');
const axios = require('axios');

const udpServer = dgram.createSocket('udp4');
const udpPort = 12345;

const restApiGatewayId = '1000000000000003';
const udpServerHost = "127.0.0.1";


udpServer.on('message', (message, remote) => {
  const packet = message;

 
  const packetGatewayId = packet.slice(2, 10).toString('hex');

  
  const devEui = packet.readBigUInt64LE(1);
  const cmdCompleteLog = packet.readUInt8(9);
  const packetId = packet.readUInt32BE(10);
  const voltageFence = packet.readUInt8(14) / 100;
  const batteryVoltage = packet.readUInt8(15) / 100;
  const voltageGround = packet.readUInt8(16) / 10;
  const alarmLevelFor = packet.readUInt8(17) / 100;
  const extSourceVoltage = packet.readUInt8(18) / 100;
  const state = (packet[19] & 0b00000001) !== 0 ? 'ON' : 'OFF';
  const power = (packet[19] & 0b00000010) !== 0 ? 'HIGH' : 'LOW';
  const energy = packet.readUInt8(20);
  const impedance = packet.readUInt16LE(21);
  const gpsLat = packet.readUInt32LE(23) * 100000;
  const gpsLon = packet.readUInt32LE(27) * 100000;
  const gpsAccur = packet.readUInt8(31);
  const accelerometerMotion = packet.readUInt8(32);
  const txPeriod = packet.readUInt8(33);
  const alarmField = {
    alarmLoopLowResist: (packet[34] & 0b00000001) !== 0,
    alarmLoopLowVoltage: (packet[34] & 0b00000010) !== 0,
    alarmLowBattery: (packet[34] & 0b00000100) !== 0,
    alarmGround: (packet[34] & 0b00001000) !== 0,
    alarmLowBattBeep: (packet[34] & 0b00010000) !== 0,
    alarmTransformerError: (packet[34] & 0b00100000) !== 0,
  };
  const voltageOnFenceAvg = packet.readUInt8(35) / 100;
  const voltageOnFenceMax = packet.readUInt8(36) / 100;
  const voltageOnFenceMin = packet.readUInt8(37) / 100;
  const impedanceMax = packet.readUInt16LE(38);
  const impedanceMin = packet.readUInt16LE(40);
  const cellularSignal = packet.readUInt8(42);


  const analyzedPacket = {
    gatewayId: packetGatewayId,
    devices: [
      {
        id: devEui.toString(),
        packetId: packetId.toString(),
        deviceType: '06',
        energyFence: energy.toString(),
        voltageFence: voltageFence.toString(),
        voltageSource: extSourceVoltage.toString(),
        voltageBattery: batteryVoltage.toString(),
        voltageFenceLowTreshold: voltageOnFenceMin.toString(),
        powerOutput: power === 'HIGH' ? '32' : '00',
        voltageGround: voltageGround.toString(),
        impedance: impedance.toString(),
        faults: '00',
        state: state.toString(),
        signal: cellularSignal.toString(),
        vFenAvg: voltageOnFenceAvg.toString(),
        vFenMin: voltageOnFenceMin.toString(),
        vFenMax: voltageOnFenceMax.toString(),
        impMin: impedanceMin.toString(),
        impMax: impedanceMax.toString(),
        latitude: gpsLat.toString(),
        longitude: gpsLon.toString()
      }
    ]
  };


  const apiUrl = 'api.com/api';

  axios.post(apiUrl, {
    packet: analyzedPacket,
    gateway: restApiGatewayId
  })
    .then(response => {
      console.log('Packet send to API');
    })
    .catch(error => {
      console.error(error);
    });
});


udpServer.bind(udpPort, udpServerHost, () => {
  console.log(`UDP listens on address ${udpServerHost}:${udpPort}`);
});

How to move last name to the first?

I have names from a database in this format:

lastname mi firstname

And I’d like to change it to

firstname mi lastname

However, I keep getting a numeric value using the stuff Google has told me to do so far:

let s = 'lastname mi firstname'
let sa = s.split(' ')
let correctOrder = sa.unshift(sa.pop())  // 3
let correctOrder = sa.push(sa.shift());  // 3

What is the correct way to move firstname from the last position into the first?