How can I use DocumentFragment to speed up this code?

I just learned about DocumentFragment, but I’m not entirely sure how to use it with what I have so far. I have around 9K-10K rows in my table and it takes about 4 seconds to load the entire table.

for (const user of totalsArray)
{
    const truncatedUsername = truncateUsername(user);

    const newRow = table.insertRow(table.rows.length);

    const newCell0 = newRow.insertCell(USERNAME_IDX);
    const newCell1 = newRow.insertCell(TOTAL_COMMENTS_IDX);
    const newCell2 = newRow.insertCell(TOTAL_SCORE_IDX);
    const newCell3 = newRow.insertCell(TOTAL_NEG_COMMENTS_IDX);

    const userName = document.createTextNode(truncatedUsername);
    const totalComments = document.createTextNode(user[TOTAL_COMMENTS_IDX]);
    const totalScore = document.createTextNode(user[TOTAL_SCORE_IDX]);
    const totalNegatives = document.createTextNode(user[TOTAL_NEG_COMMENTS_IDX]);

    newCell0.appendChild(userName)
    newCell1.appendChild(totalComments);
    newCell2.appendChild(totalScore);
    newCell3.appendChild(totalNegatives);
}

From what I understand, you make the new fragment with new DocumentFragment(), then you append to it instead of the DOM, then when you are done with the main loop, you append the fragment to the DOM. But I am not seeing a way to do that with the way I am currently inserting cells into the row, and then appending a new text node to each cell. How does DocumentFragment fit in here?

How to capture a dynamic port before a websocket connection closes from “connect ECONNREFUSED 127.0.0.1:3003”

I’m new to the concept of websocket connections and unsure how to approach this problem where the connection closes with an e.reason connect ECONNREFUSED 127.0.0.1:3003. I can only assume there is a websocket proxy function in the server that provides an open port from the default websocket connection port 3000.

I am trying to make a new websocket connection with a predefined websocket url ws://localhost:3000/

var websocket_url = ws://localhost:3000/...

const websocket = new WebSocket(websocket_url);

websocket.addEventListener("open", function(e){
console.log('websocket open', e.target);
});

websocket.addEventListener("message", function(e){
console.log('websocket message', e.target);
});

websocket.addEventListener("close", function(e){
console.log('websocket closed', e.reason);
});

Unfortunately, the websocket connection closes with a log: connect ECONNREFUSED 127.0.0.1:3003.
What are best practices to prefetch the dynamic port before it fails to connect; because when I manually type port 3003, it works.

Implementation of Javascript logic in power fx – canvas app

I am pretty new to Canvas app and I was actually looking for implementation of JS logic in power fx. Power fx is a low code language but its very complex while applying the logic to it when the filters are nested. Is there any way I could implement the following JS code in Power fx.

let colFilteredVehicles = [
  {name:'foo bar', vehicleFeatures: ["Bow", "Feature2"]},
  {name:'hello world', vehicleFeatures: ["Bow", "Row"]},
  {name:'mind games', vehicleFeatures: ["Test"]},
  {name:'new world', vehicleFeatures: ["Bow", "Row", "Feature3"]},

];

let selectedFeaturesToFilter = ["Bow", "Row"];


let filteredVehicles = colFilteredVehicles.filter(vehicle=>{
    if(vehicle.vehicleFeatures.every(feature=>selectedFeaturesToFilter.includes(feature))){
        return vehicle;
    }
});

console.log(filteredVehicles);

In case of canvas app I have selectedFeaturesToFilter equivalent to the Combobox.SelectedItems and ‘Vehicle’ and ‘Vehicle Features’ are two tables with many to many relationship. I need to get the filteredVehicles.

Seeking Help for Potential Error in Pug File Hyperlink

I’m currently taking online classes in JS and Node.js and working on a project, but I’ve hit a snag and would like to ask a question.

This is my first time using this site and I’m short on time, so I’m not sure how to ask the question properly.

First, here’s the link to my project:

https://codesandbox.io/p/devbox/express-controller-blueprint-forked-sxh4sn?file=%2Fsrc%2Findex.js%3A14%2C1.

In simple terms, I’m creating a movie webpage.

If you click the link, you can see my code (I didn’t know how to upload it here due to its length, so I just linked it. Please understand).

  1. When I click the Movie link, it should add the corresponding ID to the URL and go to the movie details page, but it doesn’t.

  2. Clicking on upload video also has no response.

  3. When I enter the year and rating of a movie, it should filter and display accordingly, but that’s not happening either.

The controller and router settings seem to be fine, but I can’t figure out what the problem is.

I’m really working hard on learning to code, but I’m so sad because I just can’t do it alone. Can anyone please read my code and help me out? I’m so frustrated because I don’t even know what I don’t know.

알겠습니다, 영어로 예의 바르게 번역해 드리겠습니다.


I think there might be a problem with the a(href=/movie/${info.id}`)=info.title` part in my movie.pug file. I’ve analyzed the code, but I can’t find anything wrong. As I mentioned earlier, I’m not sure what I don’t know or what might be wrong, so I’m unsure how to search for a solution. Could someone please read through my code and identify any errors if present? I would be very grateful.

How to get the selection of multiple html elements with document.getSelection()

const nodes = Array.from(range.commonAncestorContainer.children);
const cloneNodes = Array.from(range.cloneContents().children);
const selectedNodes = nodes.filter((node: any) => cloneNodes.some((cloneNode: any) => node.isEqualNode(cloneNode)));
console.log(selectedNodes, ‘selected nodes’);
selectedNodes.forEach((node: any) => {
console.log(node);
});

Get only the selected html elements with document.getSelection()

Create a new array based on multiple arrays using javascript

I have 3 arrays.

My sourceArray is

        var sourceArray = [
        {
            "UserName": null,
            "City": "Srinagar",
            "Country": "Country 1",
            "Age": 33,
            "Gender": "Female",
            "Role": "role1"
        },
        {
            "UserName": "uu1",
            "City": "Bangalore",
            "Country": "Country 2",
            "Age": 34,
            "Gender": "Female",
            "Role": "role2"
        },
        {
            "UserName": null,
            "City": "White Field",
            "Country": "Country 3",
            "Age": 30,
            "Gender": "Male",
            "Role": "role3"
        },
        {
            "UserName": null,
            "City": "Gurgaon",
            "Country": "Country 4",
            "Age": 30,
            "Gender": "Male",
            "Role": null
        }
    ]

My targetArray is

        var targetArray = [
        {
            "FirstName": "FIRSTNAME 1",
            "LastName": "LASTNAME 1",
            "City": "Hyderabad",
            "Country": "India",
            "Age": 33,
            "Gender": "Female",
            "Designation": "Senior Associate"
        },
        {
            "FirstName": "FIRSTNAME 2",
            "LastName": "LASTNAME 2",
            "City": "Chennai",
            "Country": "India",
            "Age": 34,
            "Gender": "Female",
            "Designation": "Manager"
        },
        {
            "FirstName": "FIRSTNAME 3",
            "LastName": "LASTNAME 3",
            "City": "Delhi",
            "Country": "India",
            "Age": 30,
            "Gender": "Male",
            "Designation": "Associate"
        },
        {
            "FirstName": "FIRSTNAME 4",
            "LastName": "LASTNAME 4",
            "City": "Kolkata",
            "Country": "India",
            "Age": 30,
            "Gender": "Male",
            "Designation": "Associate"
        }
    ]

My mappingArray is

    var mappingArray = [
        {
            "source": "City",
            "target": "City",
            "transformationType": 3,
            "transformationValue": "3"
        },
        {
            "source": "Country",
            "target": "Country",
            "transformationType": 30,
            "transformationValue": "",
        },
        {
            "source": "Age",
            "target": "Designation",
            "transformationType": 30,
            "transformationValue": ""
        },
        {
            "source": "Gender",
            "target": "Gender",
            "transformationType": 5,
            "transformationValue": "app"
        }
    ]

Here I have to move the data from source array to target array based on mapping array based on the source and target values in mappingArray.

I have to convert the targetArray in a such a way that the columns **that are not present** in mappingArray target are to be maintained as is, where as the columns present in mappingArray target column i.e here in my case City, Country, Age, Gender should be copied from sourceArray. The output array should look like below

    var outputArray = [
        {
            "FirstName": "FIRSTNAME 1",
            "LastName": "LASTNAME 1",
            "City": "Srinagar",
            "Country": "Country 1",
            "Age": 33,
            "Gender": "Female",
            "Designation": "role1"
        },
        {
            "FirstName": "FIRSTNAME 2",
            "LastName": "LASTNAME 2",
            "City": "Bangalore",
            "Country": "Country 2",
            "Age": 34,
            "Gender": "Female",
            "Designation": "role2"
        },
        {
            "FirstName": "FIRSTNAME 3",
            "LastName": "LASTNAME 3",
            "City": "White Field",
            "Country": "Country 3",
            "Age": 30,
            "Gender": "Male",
            "Designation": "role3"
        },
        {
            "FirstName": "FIRSTNAME 4",
            "LastName": "LASTNAME 4",
            "City": "Gurgaon",
            "Country": "Country 4",
            "Age": 30,
            "Gender": "Male",
            "Designation": null
        }
    ]

Can anyone please help me

Uncaught SyntaxError: Cannot use import statement outside a module (at SweetAlert2.js:1:1)

I want to use sweetalert on button click. I has download and refer the sweetalert js file. But, It giving error Cannot use import statement outside a module and Swal is not defined

<!DOCTYPE html>
   <html lang="en">
      <head>
       <meta charset="UTF-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <script src="../sweetalert2-11.10.1/src/SweetAlert2.js"></script>
       <title>Contoh Penggunaan SweetAlert</title>
     </head>
    <body>
     <div class="container">
        <h1>Contoh Pop-up Alert Menggunakan SweetAlert</h1>
        <button class="btn btn-primary" onclick="contoh()">Klik disini</button>
    </div>
    <script type="text/javascript">
        function contoh() {
          Swal.fire({
          title: 'Error!',
          text: 'Do you want to continue',
          icon: 'error',
          confirmButtonText: 'Cool'
        })

        }
    </script>
   </body>
</html>

error

How to handle editing of dates in input React

I am building a form in React that contains an input of type "date". What is the correct way to handle a backspace/edit to the input? For example, when the state is the date 12/12/1212, and I press backspace on the input, it reverts to an empty input.

The state is:

{
  ...,
  date: new Date(),
}

The state change handler looks like:

const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { name, value } = event.target;
  setState({ ... state, date: value });
}

The input is:

<input
  type="date"
  name="date"
  value={DateTime.fromJSDate(newOverride.date).toFormat(
    "yyyy-MM-dd",
  )}
  onChange={handleNewInputChange}                                   
/>

In essence, I want to be able to delete/edit the date, without clearing the whole thing and starting again. How can this be achieved?

highcharts pattern fill with diagonal lines

I’m trying add a pattern fill to a highcharts column chart.

enter image description here

The column color is #9fdae9 with the diagonal pattern black at 20% opacity. Prefer not do with an image as will be having columns with different colors with the same diagonal pattern.

I’ve looked Highcharts pattern-fill.js and the examples are lacking. I’m not experienced with svg pattern so not sure if can be done with that.

Any advice is appreciated.

Create matrix table in JS with HTML

My code is below.
I have problem about create matrix table with span cell.
Please see in picture output attached,

  • I saw extension beyond cell the right of table.
  • In column ‘Pareto’, if same (Process name) category, data is paste in only that cell(delemiter by “,”)
// Your data
var data = [{
    Process: 'PCAL',
    DATE: '29 Nov 2023',
    FPY: '0.0',
    QTY: '1',
    RTY: '0.0',
    Pareto: 'Client BER META 1 Serdes 142',
    Fail: '1'
  },
  {
    Process: 'CAL',
    DATE: '28 Nov 2023',
    FPY: '100.0',
    QTY: '2',
    RTY: '100.0',
    Pareto: 'None',
    Fail: 'None'
  },
  {
    Process: 'FVT',
    DATE: '28 Nov 2023',
    FPY: '50.0',
    QTY: '2',
    RTY: '50.0',
    Pareto: 'Client BER Lane 12',
    Fail: '3'
  },
  {
    Process: 'FVT',
    DATE: '28 Nov 2023',
    FPY: '50.0',
    QTY: '2',
    RTY: '50.0',
    Pareto: 'Client BER',
    Fail: '1'
  },
  {
    Process: 'ESS',
    DATE: '28 Nov 2023',
    FPY: '100.0',
    QTY: '1',
    RTY: '100.0',
    Pareto: 'None',
    Fail: 'None'
  },
  {
    Process: 'ESS',
    DATE: '29 Nov 2023',
    FPY: '0.0',
    QTY: '1',
    RTY: '0.0',
    Pareto: 'Module Power',
    Fail: '4'
  },
  {
    Process: 'ESS',
    DATE: '29 Nov 2023',
    FPY: '0.0',
    QTY: '1',
    RTY: '0.0',
    Pareto: 'Module A Power',
    Fail: '14'
  },
  {
    Process: 'EXS',
    DATE: '30 Nov 2023',
    FPY: '100.0',
    QTY: '3',
    RTY: '100.0',
    Pareto: 'None',
    Fail: 'None'
  }
];

// Extract unique dates and sort them in ascending order
var uniqueDates = [...new Set(data.map(item => item.DATE))].sort();

// Create the matrix table
document.write('<table>');
document.write('<tr><th rowspan="2">DATE</th>');

// Create sub-column headers for each unique date
uniqueDates.forEach(date => {
  document.write(`<th colspan="5">${date}</th>`);
});

document.write('</tr>');
document.write('<tr>');

// Create sub-column headers for ['Qty','FTY','RTY','Pareto','Fail']
for (let i = 0; i < uniqueDates.length; i++) {
  document.write('<th>Qty</th><th>FPY</th><th>RTY</th><th>Pareto</th><th>Fail</th>');
}

document.write('</tr>');

// Populate the table with data
var uniqueProcesses = [...new Set(data.map(item => item.Process))];
uniqueProcesses.forEach(process => {
  document.write(`<tr><td rowspan="5">${process}</td>`);

  uniqueDates.forEach(date => {
    var rowData = data.filter(item => item.Process === process && item.DATE === date);

    if (rowData.length > 0) {
      document.write(`
                                <td rowspan="5">${rowData[0].QTY}</td>
                                <td rowspan="5">${rowData[0].FPY}</td>
                                <td rowspan="5">${rowData[0].RTY}</td>
                                <td>${rowData.map(item => item.Pareto)}</td>
                                <td>${rowData.map(item => item.Fail)}</td>
                                `);
    } else {
      // If no data for the process and date, insert empty cells
      document.write('<td rowspan="5"></td><td rowspan="5"></td><td rowspan="5"></td><td></td><td></td>');
    }
  });
  document.write('</tr>');

  // Insert four additional rows for each Process row
  for (let i = 1; i < 5; i++) {
    document.write('<tr>');
    document.write('<td></td>'); // Empty cell for the "Process" column
    uniqueDates.forEach(() => {
      document.write('<td></td><td></td><td></td><td></td><td></td>');
    });
    document.write('</tr>');
  }
});

document.write('</table>');
table {
  border-collapse: collapse;
  width: 100%;
}

table,
th,
td {
  border: 1px solid black;
}

th,
td {
  padding: 10px;
  text-align: left;
}

Output here

  • I don’t need extension beyond cell the right of table.
  • I need to add pareto value to column by each row of column pareto.

MSW does not work in functions within contexts

I’m trying to intercept a post request with MSW to mock the result.
I have a handleLogin function within a context, however, MSW cannot recognize handleLogin as a function. I get the error ReferenceError: handleLogin is not a function.
If I make the api call out of context, it works.

This is my context:

export function AuthProvider({ children }: { children: ReactNode }) {

  ...

  const handleLogin = async function(event: FormEvent<HTMLFormElement>): Promise<AxiosResponse> {
    /**
     * Authenticate the user.
     * if username and password are corrects, the token refresh is stored on localStorage and
     * the isAuthenticate will be truthy.
     */
    const url = 'http://127.0.0.1:8000/api/token/';

    const response = await axios.post(url, {
      username: event.currentTarget.username.value,
      password: event.currentTarget.password.value,
    });

    return new Promise(function(resolve, reject) {
      if (response.status !== 200) return reject('unauthorized');
    
      const tokenRefresh = JSON.stringify(response.data.refresh);
      const tokenAccess = JSON.stringify(response.data.access);

      localStorage.setItem('userTokens', tokenRefresh);
      setUserTokens(tokenRefresh);
      setIsAuthenticated(tokenAccess);

      return resolve(response);
    })
  }

  return (
    <AuthContext.Provider value={{
      userTokens: userTokens,
      isAuthenticated: isAuthenticated,
      handleLogin: handleLogin,
      handleLogout: handleLogout,
    }}>
      {children}
    </AuthContext.Provider>
  )
}

this is my login form:

export default function LoginPage() {
  
  ...

  const { handleLogin, isAuthenticated } = useContext(AuthContext);

  ...

  function handleSubmit(e: FormEvent<HTMLFormElement>): void {
    e.preventDefault();
  
    if (!validateFields()) return;
    
    setLoading(true);

    handleLogin(e)
    .then(() => {
      navigate('/admin/dashboard', { replace: true });
      setLoading(true);
    })
    .catch(() => {
      setLoading(false);
      setUsernameError('username or password is invalid');
    });
  }

  ...
}

this is my test

import { render, screen, fireEvent } from '@testing-library/react';
import LoginPage from '..';
import { BrowserRouter } from 'react-router-dom';
import { userEvent } from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
 
const handlers = [
  http.post('http://127.0.0.1:8000/api/token/', () => {
    return new HttpResponse(null, { status: 401 })
  }),
]

const server = setupServer(...handlers);

function renderLoginPage() {
  return (
    render(
      <BrowserRouter>
        <LoginPage />
      </BrowserRouter>
    )
  )
}

describe('<loginPage />', () => {
  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  it('should render error message if user not found', async () => {
    renderLoginPage();

    // mock input data
    const usernameInput = screen.getByLabelText(/username/i);
    const passwordInput = screen.getByLabelText(/password/i);
    fireEvent.change(usernameInput, {target: {value: 'test'}});
    fireEvent.change(passwordInput, {target: {value: 'test'}});

    const button = await screen.findByText(/sign in/i);     

    await userEvent.click(button);
  
    await screen.findByText(/usuário ou senha inválidos/i);

  });
})

my error

enter image description here

I created a login function directly inside the login form, and everything works normally, but I need the handleLogin function within the context.

component-based XML library

Is there an XML library where we divide the code into various components?

and on final we build/merge it

main.xml content is:

<?xml version="1.0" encoding="UTF-8"?>
<Component1>
  <SubComponent />
</Component1>

<Component2 />

Component1.xml, SubComponent.xml, Component2.xml content is:

<1-- xml code for component here -->

Audio always stops halfway through the scene (phaserjs 3.70)

I’m working on a game and I started analyzing the game’s audio in Phaser 3. The audio works well at the beginning of the scene, no lag or anything like that, with some tweens running along. However, at a certain point (usually halfway through the scene) the audio for the entire game stops and no more sounds play.

My game config:

{
      autoFocus: true,
      banner: false,
      disableContextMenu: true,
      roundPixels: true,
      audio: {
        disableWebAudio: false,
      },
      physics: {
        default: "arcade",
        arcade: {
          debug: false,
        },
      },
      render: {
        antialias: true,
        preserveDrawingBuffer: false,
        failIfMajorPerformanceCaveat: false,
        powerPreference: "high-performance",
      },
      type: Phaser.AUTO,
      fps: {
        target: 15,
      },
      plugins: {
        scene: [
          {
            key: "SpinePlugin",
            plugin: window.SpinePlugin,
            start: true,
            mapping: "spine",
          },
        ],
      },
      scale: {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        expandParent: true,
      },
      scene: BootScene
    };

I think it’s important to say that the user only sees the execution of the tweens in this scene, they don’t take any action.

How to create precise platformer movement using MatterJS?

I’m using MatterJS to create a simple tile-based platformer, but running into issues getting both gravity and movement to work together.

My goal is to have it so the player is only partially physics driven, where they are affected by gravity, collide with walls, and push other physics objects around, but at the same time have “snappy,” left/right movement, where the instant the direction isn’t being held, the player stops moving in that direction.

Things I’ve tried and the results:

  • Using Matter.Body.setVelocity() resulted in the object moving long after I released the button.
  • Using Matter.Body.setVelocity() and then trying to clear the velocity in afterUpdate means gravity stops being applied correctly.
  • Using Matter.Body.translate() for L/R movement resulted in almost exactly what I wanted, except the player would always lightly clip into walls, causing them to get stuck instead of sliding down.
  • Using Matter.Body.applyForce() in beforeUpdate() to apply the direction vector resulted in the object still moving after I released the button, and moving at different speeds depending on if it was on the ground or not.
  • Using Matter.Body.applyForce() in beforeUpdate() and attempting to apply an equal but opposite force in afterUpdate() resulted in some really strange behavior.

Any idea how I would go about implementing this?