Is there a better way to assign a class to multiple elements?

I’m trying to code a table with infinite horizontal scrolling and I need to assign a certain color pattern the each row, but the start position in such color pattern is not the same for each row.

As you can see in my code, row 0 has as eventListener that toggles its class and applies the color pattern (it’s a 35 cells color pattern).

I need to do it for 5 rows, but I had to attrib colors with 35 nth-child selectors for row 0 alone.

Do I really have to code all those 35 selectors or there’s a better way to do it?

I’m talking about class cRow0 and all those td:nth-child(35n + x).

Rows 1 to 4 have a different approach, and colors are assigned as the cells are created.

The color pattern is defined in:

const mColors = ["red","red","cyan","cyan","lime","lime","lime","lime","lime","red","red","red","lime","lime","lime","lime","lime","lime","cyan","cyan","cyan","lime","lime","lime","lime","lime","red","red","cyan","cyan","lime","lime","lime","lime","lime"];`

As the user scrolls to the left, an eventListener creates 1 cell per row and the color assign follows a correction defined in:

mRow_Correction = [0,1,2,3];

Actually in the final version that correction will be something like

mRow_Correction = [2,0,3,1];

Anyway, in this example I’m assigning colors via

let hCell = document.createElement("td");
iRow_Correction = mRow_Correction[(iRow - 1)];
let sColor = mColors[iRow_Correction];
hCell.setAttribute("style", "background-color: " + sColor + ";");

That seems to work, but the problem is: I don’t want to assign colors as the cells are created. I want to toggle the class, like I do for row 0.

For what I see, I’ll have to code 35 nth-child selectors for each row, but there should be a better way to do it… or there isn’t?…

    var iColumns = 1, iShift = 0;
    const mColors = ["red","red","cyan","cyan","lime","lime","lime","lime","lime","red","red","red","lime","lime","lime","lime","lime","lime","cyan","cyan","cyan","lime","lime","lime","lime","lime","red","red","cyan","cyan","lime","lime","lime","lime","lime"];
    
    const hRow0 = document.getElementById("idRow0");
    hRow0.addEventListener("click", function() {
        hRow0.classList.toggle("cRow0");        
    });
    
    const hDiv_Table = document.querySelector("#idDiv_Table");
    hDiv_Table.addEventListener("scroll", () => {
        if (hDiv_Table.scrollLeft + hDiv_Table.clientWidth >= hDiv_Table.scrollWidth) fCreate_Cell();
    });
    
    for (let iColumn = 1; iColumn < 11; iColumn++){
        fCreate_Cell();
    }
    
    function fCreate_Cell() {
        let iRow_Correction, mRow_Correction = [0,1,2,3];
        let iColumn = iColumns;
        for (let iRow = 0; iRow < 5; iRow++){
            let hRow = document.getElementById("idRow" + iRow);
            let sID = "r" + iRow + "c" + iColumn;
            let hCell = document.createElement("td");
            hCell.setAttribute("id", sID);
            hRow.appendChild(hCell);
            if (iRow == 0) {
                hCell.innerHTML = "col " + iColumns;
            } else {
                iRow_Correction = mRow_Correction[(iRow - 1)];
                ((iRow_Correction + iShift) < 35) ? iRow_Correction += iShift: iRow_Correction = (iRow_Correction + iShift) - 35;
                let sColor = mColors[iRow_Correction];
                hCell.innerHTML = "col " + iColumns + "<br>" + sColor;
                hCell.setAttribute("style", "background-color: " + sColor + ";");
            }
        }
        (iShift < 34) ? iShift++ : iShift = 0;
        iColumns++;
    }
    html {
        text-align: center;
    }
    
    .cDiv_Main {
        width:100%;
        height: 100%;  
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
    }
    
    .cDiv_Title {
        width: 100%;
        height: 15%;
        border: 1px solid black;
        background-color: blue;
        color: white;
        font-weight: bold;
        display: flex;
        justify-content: center;
        flex-direction: column;
    }
    
    .cDiv_Table {
        width: 100%;
        height: 85%;
        overflow: auto;
    }
    
    .cDiv_Main table {
        width: 100%;
        height: 100%;
        border-spacing: 0;
    }
    
    table tr {
        height: 20%;
    }
        
    table td {
        min-width: 50px;
        min-height: 20px;
        border: 1px solid black;
    }
    
    .cColum_Fixed_Row_Odd, .cColum_Fixed_Row_Even {
        position: -webkit-sticky;
        position: sticky;
        left: 0;
        font-weight: bold;
    }
    
    .cTable_Main tr:nth-child(2n+1) {
        background-color: white;
    }
    .cTable_Main tr:nth-child(2n) {
        background-color: lightgray;
    }
    
    
    .cColum_Fixed_Row_Odd {
        background: white;
    }
    .cColum_Fixed_Row_Even {
        background: lightgray;
    }
    
    .cRow0 td:nth-child(35n + 2),
    .cRow0 td:nth-child(35n + 3) {
        background-color: red;
    }
    .cRow0 td:nth-child(35n + 4),
    .cRow0 td:nth-child(35n + 5) {
        background-color: cyan;
    }
    .cRow0 td:nth-child(35n + 6),
    .cRow0 td:nth-child(35n + 7),
    .cRow0 td:nth-child(35n + 8),
    .cRow0 td:nth-child(35n + 9),
    .cRow0 td:nth-child(35n + 10) {
        background-color: lime;
    }
    .cRow0 td:nth-child(35n + 11),
    .cRow0 td:nth-child(35n + 12),
    .cRow0 td:nth-child(35n + 13) {
        background-color: red;
    }
    
    .cRow0 td:nth-child(35n + 14),
    .cRow0 td:nth-child(35n + 15),
    .cRow0 td:nth-child(35n + 16),
    .cRow0 td:nth-child(35n + 17),
    .cRow0 td:nth-child(35n + 18),
    .cRow0 td:nth-child(35n + 19) {
        background-color: lime;
    }
    
    .cRow0 td:nth-child(35n + 20),
    .cRow0 td:nth-child(35n + 21),
    .cRow0 td:nth-child(35n + 22) {
        background-color: cyan;
    }
    
    .cRow0 td:nth-child(35n + 23),
    .cRow0 td:nth-child(35n + 24),
    .cRow0 td:nth-child(35n + 25),
    .cRow0 td:nth-child(35n + 26),
    .cRow0 td:nth-child(35n + 27) {
        background-color: lime;
    }
    
    .cRow0 td:nth-child(35n + 28),
    .cRow0 td:nth-child(35n + 29) {
        background-color: red;
    }
    .cRow0 td:nth-child(35n + 30),
    .cRow0 td:nth-child(35n + 31) {
        background-color: cyan;
    }
    
    .cRow0 td:nth-child(35n + 32),
    .cRow0 td:nth-child(35n + 33),
    .cRow0 td:nth-child(35n + 34),
    .cRow0 td:nth-child(35n + 35),
    .cRow0 td:nth-child(35n + 36) {
        background-color: lime;
    }
    <div id="idDiv_Main" class="cDiv_Main">
        <div id="idDiv_Title" class="cDiv_Title">INFINITE HORIZONTAL SCROLLING</div>
        <div id="idDiv_Table" class="cDiv_Table">
            <table id="idTable_Main" class="cTable_Main">
                <tbody>
                    <tr id="idRow0">
                        <td class="cColum_Fixed_Row_Odd">ROW 0</td>
                    </tr>
                    <tr id="idRow1">
                        <td class="cColum_Fixed_Row_Even">ROW 1</td>
                    </tr>
                    <tr id="idRow2">
                        <td class="cColum_Fixed_Row_Odd">ROW 2</td>
                    </tr>
                    <tr id="idRow3">
                        <td class="cColum_Fixed_Row_Even">ROW 3</td>
                    </tr>
                    <tr id="idRow4">
                        <td class="cColum_Fixed_Row_Odd">ROW 4</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

How to add symbols or characters between each react element?

I am designing a reusable component for breadcrumbs and I am using compound components pattern. I need to insert symbols between each breadcrumb name like how we would do for array elements and use join method but I am not sure how to do that with react elements.

import React from "react";

const BreadcrumbsItem = ({ children }) => (
  <p>
    {children}
  </p>
);

const Breadcrumbs = ({ children }) => <FlexContainer>{children}</FlexContainer>;

Breadcrumbs.Item = BreadcrumbsItem;

export default Breadcrumbs;

Input:

<Breadcrumbs>
  <Breadcrumbs.Item>Home</Breadcrumbs.Item>
  <Breadcrumbs.Item>Library</Breadcrumbs.Item>
  <Breadcrumbs.Item>Data</Breadcrumbs.Item>
</Breadcrumbs>

Output:

enter image description here

How to export functions in a another function?

To serve my app as a microfrontend with qiankun, I need to export these three functions in main.ts file.

export async function bootstrap () {
  // ...
}

export async function mount (props) {
  // ...
}

export async function unmount () {
  // ...
}

What I am trying to achieve is, how can I export these functions in another function?

serveMicroApp({
  onMount: (props) => { /** */ },
  onBootstrap: () => { /** */ }
  onUnmount: () => { /** */ }
})

So, how should be the content of serveMicroApp function to achieve the same thing as above (first code block)?

how to fix redux time issue with react date picker

i am using the react datepicker module and in that i am using it only for month and year picker. when i get the date in my onChange in react date picker. i get ‘Mon Nov 01 2021 00:00:00 GMT+0400 (Gulf Standard Time)’ and in my redux store i get 2021-10-31T20:00:00.000Z. there is a four hours lap due to which i get the error date.format is not a function and in some cases i get invalid time format error as well. so please if anybody knows let me know.
my code for date picker is below
`

<DatePicker

selected={passenger?.passportExp}   
onChange={date => { 
modifyPassenger(index, { passportExp: date })   }
}   
maxDate={newDate(new Date().getFullYear(),new Date().getMonth()+1, 0)}  
showMonthYearPicker   
dateFormat="MMM yyyy"   onFocusChange={({focused }) => this.setState({ passportExp: focused })}   />

`

Blur/Click difference in Chrome and Firefox

I, perhaps naively, thought there weren’t any significant browser differences anymore, but compare the behaviour of the below in Firefox and Chrome

https://jsfiddle.net/2b5mnvwt/1/

Specifically, type some text in the textbox then press the button. The button click fires in Firefox but not in Chrome

Is the difference because of something I’m doing wrong or is it a well-known issue? Which is right?

document.getElementById("theTextBox").addEventListener("blur", OnBlur, false);
document.getElementById("theButton").addEventListener("click", ButtonClick, false);

function ButtonClick(e) {
  console.log('button')
  alert('button')
}

function OnBlur(e) {
  console.log('blur')
  alert('blur')

  //e.relatedTarget.focus();
  //e.relatedTarget.click();
}
<input id="theTextBox" type="text" />
<button id="theButton">Click Me</button>

Date formatting error in Android in React native

I am getting value like 202001.

I want to covert it like January_2020.

Is there a way to convert it like this?:

202001->January_2020

i tried to do this by using Intl and it is working fine for ios but not working in android.

i tried below one.

const dateToStr = (input) => {
    if (input.length !== 6) {
      return "wrong date syntax, use YYYYMM";
    }
    const parts = input.match(/([0-9]{4})([0-9]{2})/);
    if (!parts) {
      return "wrong date syntax, use YYYYMM";
    }
    // NOTE: check syntax of parts
    const formatter = new Intl.DateTimeFormat("en-EN", { month: "long" })
      .format;
    const formatted = formatter(
      new Date(Date.UTC(parseInt(parts[1]), parseInt(parts[2]) - 1))
    );

    return `${formatted}_${parts[1]}`;
  };

How can i get this updated value in Javascript without using any library in android and ios both?

Better option for creating animation? CSS/JavaScript or animated video?

I want to create a complex animation for my website, which one is a better option?

  1. Using CSS/JavaScript to program the animation using keyframes and JavaScript libraries
  2. Or creating an animated video and embedding the video on the website

I think

For CSS/JavaScript programming :

Disadvantage: it consumes a lot of processing power for rendering the animation on the client side

Advantage: is it is highly customizable

I would love to hear your take on this question.

Not getting response with http GET call in prortactor

I am calling a GET api in my automation suite but not getting response back. Same API works from postman. I have plenty of console.log which are not getting printed. There are no errors too. Below is the snippet.


        var deferred = protractor.promise.defer();
        var options = {
            method: "GET",
            hostname: hostname,
            port: 8080,
            path: '/v1/fis/'+fiId+'/businessCustomers/'+userAuthId+'/approvals',
            headers: {
                'authorization': 'testclient',
                'content-type': 'application/json',
                'accept': 'application/json',
            }
        };
    
        var req = http.request(options, function (response) {
            browser.sleep(1000);
            console.log('headers are:', options);
            console.log('hostname is: ', hostname);
            browser.sleep(1000);
            console.log('STATUS for approval API : ' + res.statusCode);
            var chunks = [];

            response.on("data", function (chunk) {
                console.log('in chunk block::');
                chunks.push(chunk);
            });

            response.on("end", function () {
                var body = Buffer.concat(chunks);
                var finaljson = JSON.parse(body.toString());
                console.log('finaljson is:****', finaljson);
                successCallBack(finaljson.SuccessResponse);
            });
        });

        req.end();
        return deferred.promise;

    };```


Any insights will be helpful. TIA!

2) which candidate is assigned to which employee. show employee and employee details

var employes = [{‘name’:’Oliver’,’id’:214,’desk’:1},

{‘name’:’Jack’,’id’:146,’desk’:2},
{‘name’:’Harry’,’id’:125,’desk’:3},

{‘name’:’Jacob’,’id’:176,’desk’:4}];

var candidates = [
{‘name’:’jhon’,
‘id’:101,
‘info’:{
‘Address’:[{‘city’:’NY’,’country’:’USA’},{‘city’:’NJ’,’country’:’USA’}],
‘mobileNo’:[9999999999]
},
‘desk’:[
{‘updated’: true,’updatedDesk’:1},
{‘updated’: false,’updatedDesk’:2}
]
},
{‘name’:’steven’,
‘id’:102,
‘info’:{
‘Address’:[{‘city’:’Texas’,’country’:’USA’},{‘city’:’Mexico’,’country’:’South America’}],
‘mobileNo’:[9999911111,2222255555]
},
‘desk’:[
{‘updated’: false,’updatedDesk’:1},
{‘updated’: false,’updatedDesk’:2},
{‘updated’: true,’updatedDesk’:5}
]
},
{‘name’:’smith’,
‘id’:103,
‘info’:{
‘Address’:[{‘city’:’A&M’,’country’:’USA’},{‘city’:’Brazel’,’country’:’South America’}],
‘mobileNo’:[1111999999,2222266666]
},
‘desk’:[
{‘updated’: false,’updatedDesk’:3},
{‘updated’: true,’updatedDesk’:2}
]
},
{‘name’:’james’,
‘id’:104,
‘info’:{
‘Address’:[{‘city’:’A&M’,’country’:’USA’},{‘city’:’Brazel’,’country’:’South America’}],
‘mobileNo’:[1111999999,2222266666]
},
‘desk’:[ ]
},
{‘name’:’marry’,
‘id’:105,
‘desk’:[
{‘updated’: false,’updatedDesk’:1},
{‘updated’: true,’updatedDesk’:5}
]},
{‘name’:’jamesMarry’,
‘id’:106,
‘desk’:[
{‘updated’: true,’updatedDesk’:3}

]},
{‘name’:’marryJames’,
‘id’:107,
‘info’:{
‘Address’:[{‘city’:’A&M’,’country’:’USA’},{‘city’:’Brazel’,’country’:’South America’}],
‘mobileNo’:[1111999999,2222266666]
},
}
];

Interact with multiple contracts using Web3.js

Background: Hello, so I have multiple solidity contracts which are separated into a single file each. It has 1 base contract and the others are derived contracts like:

// BaseContract.sol
contract BaseContract {
...
}
// DerivedContract.sol
...
import "./BaseContract.sol";
contract DerivedContract is BaseContract{
...
}

I use ^0.8.0 version. I have compiled the contracts so I have a multiple .json file containing ABI and fucntions for each contract. I also use truffle react box, it has a getWeb3.js file (which is just a simple web3 init file)

Problem: Since my contracts are separated into multiple files, how can I instantiate the contract instance with web3? Should I only instantiate the BaseContract? or should I only instantiate the leaf contract (since it’s a derived contract with all parent contracts’ functionality)? Or should I instantiate each contract? Or maybe… should I repack every single contract file into a single file with only 1 contract?

And how can I achieve that? Below is my method to instantiate a single contract

...
import SimpleStorageContract from "./contracts/Storage.json";
...
componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();

      // Use web3 to get the user's accounts.
      const accounts = await web3.eth.getAccounts();

      // Get the contract instance.
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = SimpleStorageContract.networks[networkId];
      const instance = new web3.eth.Contract(SimpleStorageContract.abi,deployedNetwork && deployedNetwork.address,);

      // Set web3, accounts, and contract to the state, and then proceed with an
      // example of interacting with the contract's methods.
      this.setState({ web3, accounts, contract: instance });
    } catch (error) {
      // Catch any errors for any of the above operations.
      alert(`Failed to load web3, accounts, or contract. Check console for details.`);
      console.error(error);
    }
  };

JS spread operator workflow on React

React suggests not to mutate state. I have an array of objects which I am manipulating based on some events. My question is, is it okay to write it like this:

const makeCopy = (arr) => arr.map((item) => ({ ...item }));

function SomeComponenet() {
    const [filters, setFilters] = useState(aemFilterData);

    const handleFilterClick = (filter, c) => {
        let copiedFilters = makeCopy(filters);

        /**
         * Apply toggle on parent as well
         */
        if (!("parentId" in filter)) {
            copiedFilters[filter.id].open = !copiedFilters[filter.id].open;
        }
        setFilters(copiedFilters);
    }
}

Am I mutating the original object by doing like above? Or does it make a difference if written like this:

const makeCopy = (arr) => arr.map((item) => ({ ...item }));

function SomeComponent() {
    const handleFilterClick = (filter, c) => {
        let copiedFilters = makeCopy(filters);

        /**
         * Apply toggle on parent as well
         */
        if (!("parentId" in filter)) {
            copiedFilters = copiedFilters.map((f) => {
            if (filter.id === f.id) {
              return {
                ...f,
                open: !f.open,
              };
            } else {
              return { ...f };
            }
          });
        }
        setFilters(copiedFilters);
    }
}

What’s the preferred way to do this? Spread operators are getting a lot verbose and I am not liking it, but I prefer it if that’s how I need to do it here. immutable.js and immer or not an option right now.

How can in find lips landmark position using mediapipe and p5.js/javascript

I’m working on a project and I want to find only lips keypoint, and I’m using mediapipe and p5.js, so can anyone tell me how can I find only the lips keypoints and place some object on the lips.
for now, I’m getting the whole face mash and the code looks like this

faceMash = function () {
    stroke(0);
    strokeWeight(3);

    beginShape(POINTS);
    for (let i = 0; i < detections.multiFaceLandmarks[0].length; i++) {
      let x = detections.multiFaceLandmarks[0][i].x * width;
      let y = detections.multiFaceLandmarks[0][i].y * height;
      vertex(x, y);
    }
    endShape();
  };

detections is a javascript object that contains key points

How to send stored chat history from Websocket on page load?

Using a Javax/Jakarta Websocket for a group chat application and I am storing each group’s message history in a ConcurrentList<String>. I want to send users all the old messages whenever they open up the chat.jsp page. Unfortunately, it seems the websocket’s onOpen() only runs on websocket creation and doesn’t run each time the page is opened. This means each time my users refresh chat.jsp, it clears all the messages in the chat box.

What would be an effective way to perform chatHistory.get(group).forEach(m -> curSession.getAsyncRemote().sendText(m)); each time the user opens up the chat page? Is there some event I can utilize here either client or server side? I know there is a client onLoad event but I’m not sure how I would ask the server to send the message history data when that event fires.

ChatServerEndpoint.java

@ServerEndpoint("/message")
public class ChatServerEndpoint {

// Key: unique group code, Value: Sessions of users in that group
private static ConcurrentHashMap<String, Set<Session>> groupSessions = new ConcurrentHashMap<String, Set<Session>>();

// Key: unique group code, Value: list of messages in order sent
private ConcurrentHashMap<String, List<String>> chatHistory = new ConcurrentHashMap<String, List<String>>();

private String group;

@OnOpen
public void onOpen(Session curSession) {
    // Get group code from user session
    group = curSession.getRequestParameterMap().get("group").get(0);
    
    // Add user to group session
    if (!groupSessions.containsKey(group)) {
        groupSessions.put(group, Collections.synchronizedSet(new HashSet<Session>()));
    }
    groupSessions.get(group).add(curSession);
    
    // Start chat history if doesn't exist for this group
    if (!chatHistory.containsKey(group)) {
        chatHistory.put(group, Collections.synchronizedList(new ArrayList<String>()));
    } else {
        // Send old messages to client
        chatHistory.get(group).forEach(m -> curSession.getAsyncRemote().sendText(m));
    }
}
        
@OnClose
public void onClose(Session curSession) {
    // Remove user from group session
    if (groupSessions.get(group).size() == 1) {
        groupSessions.remove(group);
    } else {
        groupSessions.get(group).remove(curSession);
    }
}

@OnMessage
public void onMessage(String message, Session userSession) {
    chatHistory.get(group).add(message);
    for (Session ses : groupSessions.get(group)) {
        ses.getAsyncRemote().sendText(message);
    }
}

}

chat.js

var wsUrl;
if (window.location.protocol == 'http:') { wsUrl = 'ws://'; }
else { wsUrl = 'wss://'; }

var socket = new WebSocket(wsUrl + window.location.host + "/MyProject/message");
        
socket.onmessage = function(event) {
    var mySpan = document.getElementById("chat");
    mySpan.innerHTML += event.data;
};
     
socket.onerror = function(event) {
    console.log("Chat Error ", event)
};

function sendMsg() {
    var msg = document.getElementById("msg").value;
    if (msg) {
        socket.send(msg);
    }
    document.getElementById("msg").value = "";
}