Dynamically fitting flex items in a container with flex-wrap and variable sizes

link to the image

Can anyone help me with that,
I have a flex container with flex wrap property. I am adding items in the container using an array in js. The problem is that I want to fit the items dynamically in the container in a way so that they must occupy less space as they can. As you can see in the picture the item5 can be fit in the place with item1, and that of item6 with item2. The items in the array can be deleted and added. The container must retain its property. The size of each item may be different from the other ones. So, using grid is not the right option for that.

I tried many css properties but they didn’t work well.

Material UI: Delay issue when passing large dataset to Autocomplete component in Material-UI

I am using the Autocomplete component from Material-UI in my React application. When trying to pass a large dataset of approximately 10,000 items as a prop to the Autocomplete component, I am experiencing a significant delay of around 5 seconds before the dropdown menu renders with the expected data.

I have implemented the Autocomplete component following the documentation provided by Material-UI at https://mui.com/material-ui/react-autocomplete/#checkboxes.

Here’s the relevant code snippet for reference:

import * as React from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Checkbox from '@mui/material/Checkbox';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import CheckBoxIcon from '@mui/icons-material/CheckBox';

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

type AutoSelectDropdownProps = {
    dropdownData?: any,
    isMultiple?: boolean,
    onChange?: any
    defaultvalue?: any,
    valueField?: string
    displayField?: string,
}

export function AutoCompleteDropDown(props: AutoSelectDropdownProps) {

    let newObj = [...props.dropdownData];

    const loadValues = (event: any, values: any) => {
        const target = {
          value: [],
          name: undefined
        };

        if (values && values.length > 0) {
          target.value = values.map((item: any) => item[props.valueField || 'value']);
        }

      props.onChange({target});

    }


  return (
    <Autocomplete
      multiple
      options={newObj}
      getOptionLabel={(option) => option.value}
      limitTags={2}
      onChange={loadValues}
      defaultValue={
        props.dropdownData.filter((item: any) => {
          return props.defaultvalue.includes(item[props.valueField || 'value']);
        })
      }
      renderOption={(props, option, { selected }) => (
        <li {...props}>
          <Checkbox
            icon={icon}
            checkedIcon={checkedIcon}
            checked={selected}
            />
          {option.value}
        </li>
      )}
      size="small"
      sx={{ minWidth: 180, width: '100%', mt: 1, backgroundColor: "white" }}
      renderInput={(params) => (
        <TextField {...params} size='small' />
      )}
    />
  );
}


export default AutoCompleteDropDown;

(Sequelize) Product category enum values from Category model

I have ProductCategory and Category models. What is the right way to make category field of ProductCategory be one of category_name values in Category model? (Category model is a set of permitted category values)

models/product-category.js

const Sequelize = require('sequelize');
const sequelize = require('../utils/database');


const ProductCategory = sequelize.define('product_category', {
  id: {
    type: Sequelize.INTEGER.UNSIGNED,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  category: { // `category` values should be one of `category_name` values

    // type: Sequelize.ENUM(...categories),
    // defaultValue: defaultValue,
  },

}, {
  freezeTableName: true
});


module.exports = ProductCategory;

models/category.js

const Sequelize = require('sequelize');
const sequelize = require('../utils/database');

const options = [
  'sale', 'lease', 'others'
];

const Category = sequelize.define('category', {
  id: {
    type: Sequelize.INTEGER.UNSIGNED,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  category_name: {
    type: Sequelize.ENUM(...options),
    defaultValue: defaultValue
  },
  
}, {
  freezeTableName: true
});


module.exports = Category;

Later on, I will probably have associations like this:

Product.hasOne(ProductCategory);
ProductCategory.belongsTo(Product);

ProductCategory.belongsTo(Category);
Category.hasMany(ProductCategory);

I’m wondering whether I’m heading at the right direction

Javascript Object reference behavior [duplicate]

Asking because I’m a bit mind boggled.

Why does the function return the ref to the a object, but b remains unchanged in this scenario?

Not very familiar with the chained equals

const a = {b: {c: 1}};
const b = a.b.c = 2;

const ab = () => ({a,b});

a.b.c = 3; 
console.log(ab());

Toggle parent of a DIV onclick

I have a code where I have a page divided into four columns/ lists. There are in total 32 list, but only the group of four are displaying at the same time.

Inside each column there are a list of DIV elements that contains a button. When the button is clicked, I want them to be moved. So if a DIV is located in “List3”, I want it to be moved to “List1”. And if it is located in “List4”, I want it to be moved to “List2”. This needs to be a toggle, so that I can swap back and forth.

I can get the script to work no problem. What I am strugling with is when there are 35 list, and I have to specify an ID for each of the 32 lists, and soon to be even more.

Is there a way to specify that the DIV that will be moved always will go between L3-L1 and L4-L2. If so – that would save me the hassle of having to make a new script for each list that shoul all link in the same manner. Would love som help one this one!

See code below

document.addEventListener("DOMContentLoaded", function() {
    var buttons = document.querySelectorAll(".moveBtn2");
    var list1 = document.getElementById("L1");
    var list2 = document.getElementById("L3");

    function moveItem(e) {
        var moveTo = this.parentElement.parentElement == list1 ? list2 : list1;
        moveTo.appendChild(this.parentElement);
    }

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", moveItem);
    }
}); 

document.addEventListener("DOMContentLoaded", function() {
    var buttons = document.querySelectorAll(".moveBtn3");
    var list2 = document.getElementById("L2");
    var list4 = document.getElementById("L4");

    function moveItem(e) {
        var moveTo = this.parentElement.parentElement == list2 ? list4 : list2;
        moveTo.appendChild(this.parentElement);
    }

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", moveItem);
    }
}); 
<div id="G235" class="topshort hidden">
<h2 class="test1" style="position: absolute; left: 22%">Bestått</h2>
<div class="div-left">
<br>
 <h3 style="font-size: 16px">Fellesfag</h3>
     <div class="boxy" style="width: 100%; height: 50px; background-color: lightgray; position: relative; margin-bottom: 15px; border-bottom: solid; border-top: solid"><strong><br><i>Fag</i><i style=" position: absolute; right: 80px;">Karakter</i></strong></div>
 <div id="L1">
</div>
</div> 
<div class="div-leftleft">
  <br>
 <h3 style="font-size: 16px">Programfag</h3>
     <div class="boxy" style="width: 100%; height: 50px; background-color: lightgray; position: relative; margin-bottom: 15px; border-bottom: solid; border-top: solid"><strong><br><i>Fag</i><i style=" position: absolute; right: 80px;">Karakter</i></strong></div>
 <div id="L2">

</div>
</div> 
<div class="vlshort"></div>
       
       <h2 class="test2" style="position: absolute; left: 71%;">Ikke bestått</h2>
       <div class="div-right"> 
<br>
      <h3 style="font-size: 16px">Fellesfag</h3>
           <div class="boxy" style="width: 100%; height: 50px; background-color: lightgray; position: relative; margin-bottom: 15px; border-bottom: solid; border-top: solid"><strong><br><i>Fag</i><i style=" position: absolute; right: 80px;">Karakter</i></strong></div>
       <div id="L3">
<div class="lines">
   <a>Text</a>
   <button class="moveBtn2">Legg til</button>
      <hr>
  </div>
   </div>
</div>
    
<div class="div-rightright">
  <br>
 <h3 style="font-size: 16px">Programfag</h3>
     <div class="boxy" style="width: 100%; height: 50px; background-color: lightgray; position: relative; margin-bottom: 15px; border-bottom: solid; border-top: solid"><strong><br><i>Fag</i><i style=" position: absolute; right: 80px;">Karakter</i></strong></div>
 <div id="L4">
 <div class="lines">
   <a>Text</a>
   <button class="moveBtn3">Legg til</button>
      <hr>
  </div>
</div>
</div> 
<a style="position: absolute; left: 35px; bottom: 35px; color: grey;" contentEditable="true">IB = Ikke bestått</a>
    
     </div>
       

Pass variables to one onclick function

I have one function downloadfile(){}, how can I download multiple files using one onclick function passing different variables. For example, one button has to download elementary school data i.e elem=1,other higher=1, and so on.. my api url looks like this.. “https/www.example.com?download&elem=&higher=” When I click on elem button.. I have to pass the value 1 to the elem and download that particular file. likewise for higher…So that I do not want to use mulitple onclick functions for each downloadfile.

Is there a code style/ESLint rule for consistent export syntax?

Is there a way to force automatically a specific syntax for exporting modules in JavaScript (either export keyword or export {name} at the end of the file) ?

I spent few hours in the docs to find it without success… If it doesn’t really exist, I could create a custom rule.

I also checked how Google (source) address this aspect, but these syntaxes seem to be both allowed.

Thank you in advance!

Multi-row span cells in HTML tables cannot be aligned

I am new to HTML, if anyone can help me solve the below issue only using HTML without CSS, I will appreciate very much.

The main issue is Multi-row span cells in last row in HTML tables cannot be aligned

I want draw a table with multi-row span cell using HTML. The effect picture is demonstrated with an excel table in the attached picture.
Effect picture

I use below code to realize it.

<table border="1">
  <tr>
    <td rowspan="11" colspan="5">TD1#R11C5</td>
    <td rowspan="1" colspan="6">TD2#R1C6</td>
    <td rowspan="1" colspan="7">TD3#R1C7</td>
    <td rowspan="2" colspan="8">TD4#R2C8</td>
  </tr>
  <tr>
    <td rowspan="1" colspan="6">TD5#R1C6</td>
    <td rowspan="1" colspan="7">TD6#R1C7</td>
  </tr>
  <tr>
    <td rowspan="2" colspan="2">TD7#R2C2</td>
    <td rowspan="2" colspan="2">TD8#R2C2</td>
    <td rowspan="2" colspan="2">TD9#R2C2</td>
    <td rowspan="1" colspan="8">TD10#R1C8</td>
    <td rowspan="1" colspan="7">TD11#R1C7</td>
  </tr>
  <tr>
    <td rowspan="6" colspan="8">TD12#R6C8</td>
    <td rowspan="6" colspan="7">TD13#R6C7</td>
  </tr>
  <tr>
    <td rowspan="5" colspan="2">TD14#R5C2</td>
    <td rowspan="5" colspan="2">TD15#R5C2</td>
    <td rowspan="5" colspan="2">TD15#R5C2</td>
  </tr>

  <tr>
    <td rowspan="2" colspan="21">TD18#R2C21</td>
  </tr>
</table>

But the final result in chrome browers is like this:
the real result in chrome brower

the layout I want. I use excel to draw this layout.
TD1#R11C5, this is a td name to describe the td, TD1 is the td name,#R11C5 is the description of the TD, R11 means this cell’s rowspan equals 11, C5 means this cell’s colspan equals 5.

LibreOffice CLI Highlighting Words in Generated PDF using Macros

I wanted to make a generic system in my application where I could input a file of a readable type, let’s say a Text Document and convert it to a PDF.

My research has lead me to the CLI version of LibreOffice which allows you to do just that, the conversion from a given file type to a PDF, specifically, this is the command I found,

libreoffice --headless --convert-to pdf path/to/file, this will automatically convert, if convertible the file that was specified and it will output a .pdf that contains, hopefully all the data.

Now, the end goal is to have the ability to specify a list of words which are to be highlighted within that document, specifically, highlight them with a yellow background.

This has led me to some things called Macros and I’ve noticed I could write one in JavaScript.

I created my JavaScript Macro for LibreOffice

function highlight( words ) {
    var document = XSCRIPTCONTEXT.getDocument();
    var descriptor = document.createSearchDescriptor();

    descriptor.setPropertyValue( "SearchCaseSensitive", true );
    descriptor.setPropertyValue( "SearchWords", true );

    for( let i = 0; i < words.length; i++ ) {
        descriptor.setSearchString( words[ i ] );

        let found = document.findFirst( descriptor );
        while( !found ) {
            let text = found.getText();
            text.CharBackColor = "#FFFF00"; // Yellow Hex
            found = document.findNext( found.getEnd(), descriptor );
        }
    }
}

So I tried to modify my command from above,

libreoffice --headless --norestore --invisible --convert-to pdf path/to/file macro:///home/macros.highlight(${words})

Notice that I run this command inside a container, there I have create a mount point which contains all my macros.

The command I’m showing above I have constructed programmatically using my Node.JS application.

Mongo Memory Server – UnexpectedCloseError: Instance closed unexpectedly with code “48” and signal

I am using Jest and mongo-memory-server to test my code. I try to do some tests then I received an error message (UnexpectedCloseError: Instance closed unexpectedly with code "48" and signal "null") but when I select “run just failed tests” mode, all of them passed. Here is the code and error message;

Error

 PASS  src/test/health.test.ts
 FAIL  src/test/user.test.ts
  ● Console

    console.warn
      Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:
       UnexpectedCloseError: Instance closed unexpectedly with code "48" and signal "null"
          at MongoInstance.closeHandler (/Users/ertan/Desktop/jsarticles/jsad-backend/node_modules/mongodb-memory-server-core/src/util/MongoInstance.ts:546:52)
          at ChildProcess.emit (node:events:520:28)
          at maybeClose (node:internal/child_process:1092:16)
          at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)

      at MongoMemoryServer.<anonymous> (node_modules/mongodb-memory-server-core/src/MongoMemoryServer.ts:293:17)
      at node_modules/mongodb-memory-server-core/node_modules/tslib/tslib.js:169:75
      at __awaiter (node_modules/mongodb-memory-server-core/node_modules/tslib/tslib.js:165:16)
      at node_modules/mongodb-memory-server-core/src/MongoMemoryServer.ts:284:68

  ● User Models › should insert a doc into user collection

    Instance closed unexpectedly with code "48" and signal "null"

      at MongoInstance.closeHandler (node_modules/mongodb-memory-server-core/src/util/MongoInstance.ts:546:52)

  ● User Models › should find all users

    Instance closed unexpectedly with code "48" and signal "null"

      at MongoInstance.closeHandler (node_modules/mongodb-memory-server-core/src/util/MongoInstance.ts:546:52)

  ● User Models › should find user by email

    Instance closed unexpectedly with code "48" and signal "null"

src/test/employee.test.ts

import {
  afterAll,
  afterEach,
  beforeAll,
  describe,
  it,
  jest,
  expect,
} from "@jest/globals";

import {
  connectDB,
  dropCollections,
  dropDB,
} from "../configs/mongoMemoryServer";

import {
  UserModel,
  createUser,
  deleteUserById,
  findUserByEmail,
  findUserById,
  findUsers,
} from "../model/user";

jest.useRealTimers();

describe("User Models", () => {
  beforeAll(async () => {
    await connectDB();
  });

  afterAll(async () => {
    await dropDB();
  });

  afterEach(async () => {
    await dropCollections();
  });

  it("should insert a doc into user collection", async () => {
    const MOCK_USER = {
      email: "[email protected]",
      gdprInfo: {
        isAccepted: true,
        ip: "111.111.1.1",
      },
    };

    const createdUser = await createUser(MOCK_USER.email, MOCK_USER.gdprInfo);

    expect(createdUser.email).toBe(MOCK_USER.email);
    expect(createdUser.gdprInfo.ip).toBe(MOCK_USER.gdprInfo.ip);
    expect(createdUser.gdprInfo.isAccepted).toBe(MOCK_USER.gdprInfo.isAccepted);
    expect(createdUser.sentNewsletters).toEqual([]);
    expect(createdUser.createdAt).toBeInstanceOf(Date);
    expect(createdUser.updatedAt).toBeInstanceOf(Date);
  });

  it("should find all users", async () => {
    const MOCK_USERS = [
      {
        email: "[email protected]",
        gdprInfo: {
          isAccepted: true,
          ip: "111.111.1.1",
        },
      },
      {
        email: "[email protected]",
        gdprInfo: {
          isAccepted: true,
          ip: "111.111.1.2",
        },
      },
    ];

    await createUser(MOCK_USERS[0].email, MOCK_USERS[0].gdprInfo);
    await createUser(MOCK_USERS[1].email, MOCK_USERS[1].gdprInfo);

    const users = await findUsers([]);

    expect(users).toBeDefined();
    expect(users.length).toBeGreaterThan(0);

    users.forEach((user) => {
      expect(user).toBeInstanceOf(UserModel);
    });
  });

  it("should find user by email", async () => {
    const MOCK_USERS = [
      {
        email: "[email protected]",
        gdprInfo: {
          isAccepted: true,
          ip: "111.111.1.1",
        },
      },
      {
        email: "[email protected]",
        gdprInfo: {
          isAccepted: true,
          ip: "111.111.1.2",
        },
      },
    ];

    await createUser(MOCK_USERS[0].email, MOCK_USERS[0].gdprInfo);
    await createUser(MOCK_USERS[1].email, MOCK_USERS[1].gdprInfo);

    const user = await findUserByEmail("[email protected]");

    expect(user).toBeDefined();
    expect(user).toBeInstanceOf(UserModel);
    expect(user?.email).toBe("[email protected]");
    expect(user?.email).not.toBe("[email protected]");
  });

  it("should find user by id", async () => {
    const MOCK_USER = {
      email: "[email protected]",
      gdprInfo: {
        isAccepted: true,
        ip: "111.111.1.1",
      },
    };

    const createdUser = await createUser(MOCK_USER.email, MOCK_USER.gdprInfo);

    const user = await findUserById(createdUser?._id?.toString() || "");

    expect(user).toBeDefined();
    expect(user).toBeInstanceOf(UserModel);
    expect(user?.email).toBe("[email protected]");
  });

  it("should delete user", async () => {
    const MOCK_USER = {
      email: "[email protected]",
      gdprInfo: {
        isAccepted: true,
        ip: "111.111.1.1",
      },
    };

    const createdUser = await createUser(MOCK_USER.email, MOCK_USER.gdprInfo);

    const deletedUser = await deleteUserById(
      createdUser?._id?.toString() || ""
    );

    expect(deletedUser).toBeDefined();
    expect(deletedUser).toBeInstanceOf(UserModel);
    expect(deletedUser?._id).toEqual(createdUser._id);
  });
});



configs/mongoMemoryServer

import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose, { ConnectOptions } from "mongoose";

let mongo: MongoMemoryServer;

const connectDB = async () => {
  mongo = await MongoMemoryServer.create({
    instance: {
      port: Number(process.env.DB_PORT),
    },
  });
  const uri = mongo.getUri();

  await mongoose.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  } as ConnectOptions);
};

const dropDB = async () => {
  if (mongo) {
    await mongoose.connection.dropDatabase();
    await mongoose.connection.close();
    await mongo.stop();
  }
};

const dropCollections = async () => {
  if (mongo) {
    const collections = await mongoose.connection.db.collections();
    for (const collection of collections) {
      await collection.drop();
    }
  }
};

export { connectDB, dropDB, dropCollections };

Versions

  • NodeJS: v16.14.0
  • mongodb-memory-server-*: ^8.13.0
  • mongoose: ^7.2.2
  • Jest ^29.5.0
  • system: MacOS M1

Opening and closing vue-ctk-date-time-picker using a button click in Vue

I am using the component – https://github.com/chronotruck/vue-ctk-date-time-picker in my component. The issue that I am facing is that i want to keep the component as it is but somewhere in my component a button should be able to open and close it, It seems like the component does not offer any such functionality, can anyone please help with the same.

Any help is appreciated

Code sandbox – Sanbox

Why NodeValue or textContent is one char less

The focusNode has full entered text (in a contenteditable div) but not the same for focusNode.nodeValue (one character less). The same is true for focusNode.textContent

var sel = getSelection();


 console.log(sel.focusNode); //Hello World
 console.log(sel.focusNode.nodeValue); //Hello Worl

How to stop setInterval inside a function using Event Listener in JS

I created a countdown timer function for a bank application wherein this timer will start the countdown once the user started login into the application.

//TIMEOUT TIMER FUNCTION
const timeOutTimer = () => {
    const tick = () => {
        const minute = time / 60;
        const second = time % 60;
        time--;
        labelTimer.textContent = `${String(Math.trunc(minute)).padStart(2, 0)}:${String(second).padStart(2, 0)}`;
        console.log(`${String(Math.trunc(minute)).padStart(2, 0)}:${String(second).padStart(2, 0)}`);
        if (time === 0) {
            clearInterval(timer);
        }
    };
    
    let time = 10;
    const timer = setInterval(tick, 1000);
}

//LOGIN BUTTON FUNCTION
btnSignIn.addEventListener('click', (e) => {
    e.preventDefault();
    //Timer initiate
    timeOutTimer();
})

Is there a way to stop the timer from a different function? in my case, I want to stop the timer function once the user clicked the logout button.

btnLogOut.addEventListener('click', () => {
    //Function to be executed to stop the timer function.
})