Drag and Drop with resizing browser window (react-use-gesture)

I used hook useDrag from ‘react-use-gesture’.

 const drag = useDrag((params) => {},
        {
            bounds: {...bounds}
        }
    )

I use bounds in full clientWidth.

It works fine with constant bounds. But after resizing browser window (open devtools panel in my case) hook use previous offset value(I need to drag all width of resizing clientWidth).

How can I use useDrag with document.body.clientWidth?

Copy worksheet to same workbook and rename it using Javascript

I am trying to write a function where a specified workbook is opened and then we need to copy existing sheet and make a copy of it in the same workbook and rename that worksheet.
I saw this feature is implemented In VBA using the code below.

Worksheets(“Sheet1”).Copy After:=Worksheets(“Sheet3”)

In Javascript I am trying to do

  var xlApp = new ActiveXObject("Excel.Application");
  var xlWorkbooks = xlApp.Workbooks;
  var xlWorkbook = xlWorkbooks.Open(xlFileName);
  var xlWorksheets = xlWorkbook.Worksheets;
  var xlWorkSheet = xlObj.getWorksheet("PRC1.1");
  xlWorkSheet.copy();

This code is creating a copy in new workbook but I want in the same workbook.

Any Answers would be highly appreciated.
Thanks in Advance.

P5js sketch slow with WEBGL

I created a sketch which draws 100s of thousands of lines. As expected, it is quite slow. So, I tried the same sketch with WEBGL mode. But this turned out to be slower than the default mode.

My understanding was that WEBGL leverages GPU for fast rendering. Is it not true?

Thank you.

createCanvas(windowWidth, windowHeight, WEBGL)

How to have ticks on x axis in 15 min increments on chartJS?

So my current chart has incremental steps of random times.
example

I would like it so that it is broken up into 15 mins increments (i.e. 12:45, 13:00, 13:15, 13:30…)

This is how i currently have the ticks setting:

        ticks: {
          color: theme.colors.primary,
          padding: 2,
          maxTicksLimit: 6,
          autoSkip: true,
          maxRotation: 0,
          minRotation: 0,
          labelOffset: 25,
        },

This is the current data coming in for the date/time:

[
  1645484400, 1645486200, 1645488000, 1645489800, 1645491600,
  1645493400, 1645495200, 1645497000, 1645498800, 1645500600,
  1645502400, 1645504200, 1645506000, 1645507800, 1645509600,
  1645511400, 1645513200, 1645515000, 1645516800, 1645518600,
  1645520400, 1645522200, 1645524000, 1645525800, 1645527600,
  1645529400, 1645531200, 1645533000, 1645534800, 1645536600,
  1645538400, 1645540200, 1645542000, 1645543800, 1645545600,
  1645547400, 1645549200, 1645551000, 1645552800, 1645554600,
  1645556400, 1645558200, 1645560000, 1645561800, 1645563600,
  1645565400, 1645567200, 1645569000, 1645570800, 1645572600,
  1645574400, 1645576200, 1645578000, 1645579800, 1645581600,
  1645583400, 1645585200, 1645587000, 1645588800, 1645590600,
  1645592400, 1645594200, 1645596000, 1645597800, 1645599600,
  1645601400, 1645603200, 1645605000, 1645606800, 1645608600,
  1645610400, 1645612200, 1645614000, 1645615800, 1645617600,
  1645619400, 1645621200, 1645623000, 1645624800, 1645626600,
  1645628400, 1645630200, 1645632000, 1645633800, 1645635600,
  1645637400, 1645639200, 1645641000, 1645642800, 1645644600,
  1645646400, 1645648200, 1645650000, 1645651800, 1645653600,
  1645655400, 1645657200, 1645659000, 1645660800, 1645662600,
  ... 1339 more items
]

Any idea what would be the best way to execute this?

Jquery: How to create a named click event with an anonymous function sent as a parameter

I’m trying to do something like this but this doesn’t seem to work.

function myEvent(callback){
    console.log("Do Stuff");
    callback(); // Then execute callback function
}

$("#myBtn").on("click", myEvent(function(){
    console.log("My anonymous callback");
}));

Basically I need a named event so that I can easily add and remove the event as needed. But I also need to be able to pass a callback to the function that event uses. This function needs to be an anonymous function. Is this possible?

Jquery solutions preferred.

Set class styles to items in a react component

I trie to put a underline in my nav list with this code.

 const [classOn, setClassOn] = useState('menu_selected');
    const [linkMenu, setLinkMenu] = useState('');

    function handleSelectedMenu(nb){
        setLinkMenu(document.querySelectorAll('nav ul li'));
        for(let i=1; i<linkMenu.length; i++){
            linkMenu[i].firstChild.classList.remove(classOn)
        } 
        linkMenu[nb].firstChild.classList.add(classOn) 
    }

on full screen, nothings happen and i have an error in my console log

Uncaught TypeError: Cannot read properties of undefined (reading 'firstChild')

but when i open mobile viwer, the styles are been aplicated.

print error browser

Async with useEffect and loading data into variables

I am trying to use mainData which is an object, that is populated by Supabase via a join. Using segment:SignalJourneyAudiences(segment) ,

Which will give me:

segment: {segment: xyz}

I have this new array which is using that object which is returned from the join like the below.

const unquieConstraints = [
    ...new Map(
      mainData
        .filter(row => row.segment.segment === segment.segment.segment)
        .map(item => [item.constraint_value, item]),
    ).values(),
  ]

But as Supabase runs async functions, and I am running it in useEffect I get that it can’t be read. You can see below that it loads empty then after useEffect has called the async function it loads the mainData

enter image description here

How can I resolve this issue so the app doesnt crash because it’s unable to read segment: {segment: xxx} I have tried a ternary operator within the filter. But that doesnt work 🙁

this is the main logic of my component

  // CONSTRAINT CHECKBOXES
  const [constraintOptions, setConstraintOptions] = useState({
    constraints: [],
  })

  const duplicates = new Set()

  const duplicateObjects = mainData.filter(
    item => duplicates.size === duplicates.add(item.segment.segment).size,
  )

  const duplicateIds = new Set()

  const nextRoundFilteredObjects = duplicateObjects.filter(
    item =>
      duplicateIds.size !== duplicateIds.add(item.audience_id.audience_id).size,
  )

  // We return only the constraint values for the unique segment

  const unquieConstraints = [
    ...new Map(
      mainData
        .filter(row => row.segment === segment.segment)
        .map(item => [item.constraint_value, item]),
    ).values(),
  ]

  if (mainData.length === 0) {
    console.warn('WARNING: mainData is empty')
  } else {
    console.log('mainData', mainData)
  }

  function handleCheckBoxes(e) {
    const {value, checked} = e.target

    if (checked) {
      setConstraintOptions({
        constraints: [...constraintOptions.constraints, value],
      })
    } else {
      setConstraintOptions({
        constraints: constraintOptions.constraints.filter(e => e !== value),
      })
    }
  }

  function openSideBar() {
    setIsOpen(true)
  }

  function closeSideBar() {
    setIsOpen(false)
  }

  // Handles the error / success messages popup
  function popupValidation(type, message) {
    if (type === 'success') {
      setSuccess(true)
      setSuccessMessage(message)

      setTimeout(() => {
        window.location.reload()
      }, 2000)
    } else if (type === 'warning') {
      setWarning(true)
      setWarningMessage(message)

      setTimeout(() => {
        setError(false)
        window.location.reload()
      }, 2500)
    } else if (type === 'error') {
      setError(true)
      setErrorMessage(message)

      setTimeout(() => {
        setError(false)
        window.location.reload()
      }, 2500)
    }
  }

  async function getAudienceConstratints() {
    const {data, error} = await supabase
      .from('SignalJourneyAudienceConstraints')
      .select(
        `
        constraint_id,
        audience_id:SignalJourneyAudiences(audience_id),
        segment:SignalJourneyAudiences(segment) ,
        source:SignalJourneySources(source) ,
        constraint_type:SignalJourneyConstraintType(constraint_type),
        constraint_value,
        targeting,
        frequency,
        period
      `,
      )
      .order('constraint_id', {ascending: true})

    if (data) {
      setMainData(data)
    }
    if (error) {
      setErrorMessage('error', error.message)
    }
  }

  async function addNewRelationship() {
    closeSideBar()

    try {
      const {data, error} = await supabase
        .from('SignalJourneyAudienceConstraintRelations')
        .insert([
          {
            audience_id: segment.audience_id.audience_id,
            relation: relationship.condition,
            constraint_ids: constraintOptions.constraints.join('|'),
          },
        ])

      if (data) {
        popupValidation('success', 'Relationship added successfully')
      }
      if (error) {
        popupValidation('error', error.message)
      }
    } catch (error) {
      console.error(error)
    }

    // RESET Relationships
    setSegment('')
  }

  useEffect(() => {
    getAudienceConstratints()
  }, [])

Cypress / JavaScript: assertion with an URL that contains a specific word

I’m a beginner with Cypress and JavaScript. I’m trying to improve the following assertion, I report it below.

Here:

cy.xpath('//div[@data-testid="@foleon/maggie-viewer_column-component"]').should('have.css', 'background-image', 'url("https://assets.website.com/assets/house.jpg")');

In the test I am verifying if that div has the css background-image property with that url value, I am trying to convert this assertion in this way: verifying that the div has the css background-image property with a value that contains: “house.jpg” instead of the entire URL.

Many thanks if you can help me

How to accept any order of groups in regex?

as already mentioned in my provider question, how can I change an regex with names capture groups from a dedicated order of the groups to any order is accepted?

As an example of my data:

{
  att1 = "demo1"
  att2 = "ohno"
}
{
  att2 = "demo1"
  att1 = "ohno"
}

If I use this regex, it will work for the first record but not for the second one

/{[ns]*(?:att1 = "(?<att1>w*)"[ns]*(?:att2 = "(?<att2>w*)"[ns]*}/gm

Connecting both groups with an | will not help. Instead it finds only the last group, but why?

/{[ns]*(?:(?:att1 = "(?<att1>w*)"[ns]*)|(?:(?:att2 = "(?<att2>w*)"[ns]*)}/gm

Test in online Tools do not really help because there the regex might work bot not in my local nodejs 16 version

Implementing a clone of the Array concat method

Is the following a close representation of how concat might be implemented on the Array object?

Array.prototype.myConcat = function(...args) {
    let arr = [...this];
    for (let arg of args) {
        // allow one level of unnesting
        if (!Array.isArray(arg)) arg = [arg,]
        for (let subarg of arg) {
            arr.push(subarg);
        }
    }
    return arr;
};
let x1 = [1,2,3].myConcat('hello', 'new', [1,2,3], [1,2,[3,4]]);
let x2 = [1,2,3].concat('hello', 'new', [1,2,3], [1,2,[3,4]]);
console.log(x1, x2, JSON.stringify(x1) === JSON.stringify(x2));

How to use querySelectorAll Nodelist objects as react components

Im using querySelectorAll to grab all tags that have a specific id from a html string, i then want to render the tags in a react component. I do this by trying to map the object given back by querySelectorAll. When i do this i get an uncaught error and im unsure how to fix it. Uncaught Error: Objects are not valid as a React child (found: [object SVGGElement]). If you meant to render a collection of children, use an array instead. i tried turning the objects into an array but i still get errors. Heres my code

   const svg = `<svg>
                <g id="tooth-311-default">
                    <g>
                        <g id="XMLID_9_">
                            <g>
                                <path class="st16" d="M858.8,1050.8c0,0-1.8,11.3,5.2,12.3l24.2-5.5h0c0.8-2.1,1.8-5.1,1.6-7.6c0,0-9.6-14.6-18.2-11.9
                                    C863,1040.7,858.8,1050.8,858.8,1050.8z"/>
                                <path class="st16" d="M888.2,1057.5l-24.2,5.5C873.7,1064.6,888.1,1057.9,888.2,1057.5z"/>
                                <path class="st25" d="M888.2,1057.5c-0.1,0.3-14.5,7.1-24.2,5.5c0,0,10.9,30,17.2,29.5c6.3-0.5,5.9-23,5.7-32.2
                                    C886.9,1060.3,887.5,1059.2,888.2,1057.5L888.2,1057.5z"/>
                            </g>
                            <g>
                                <path class="st20" d="M888.2,1057.5c0.8-2.1,1.8-5.1,1.6-7.6c0,0-9.6-14.6-18.2-11.9c-8.6,2.6-12.8,12.8-12.8,12.8
                                    s-1.8,11.3,5.2,12.3c0,0,10.9,30,17.2,29.5c6.3-0.5,5.9-23,5.7-32.2C886.9,1060.3,887.5,1059.2,888.2,1057.5z"/>
                                <path class="st20" d="M888.2,1057.5c-0.1,0.3-14.5,7.1-24.2,5.5"/>
                            </g>
                        </g>
                    </g>
                </g>
        </svg>`

        console.log(props.tooth)
        var parser = new DOMParser();
        var doc = parser.parseFromString(svg, "text/html");
        var teeth = doc.querySelectorAll(`[id^=tooth-${props.tooth}]`);
        console.log(typeof(teeth), 'swag')
        const teething = [...teeth]
        var htmlObject = document.createElement('div') 
        //return (<div>{teeth.map((tooth => ({tooth}))) }</div>)
        return (teething.map((tooth) => (console.log(tooth, 'ch'), tooth )))

    }



    return(<div>

        <svg version="1.1"  x="0px" y="0px" viewBox="0 0 900 900">
            {findIdTooth()}
        </svg>

        
                



    </div>)

}
    
export default ShowTooth;


Is there anyway i can convert a string to HTML then query all the ids based on a given id and then render it in react? (in my actual code above svg string is larger with many different IDs for many different teeth, i.e theres tooth-211, tooth-213, etc)

How to optimize large data with multiple layers of object in react js?

I am working fetching data from a large json file with object inside object and so on. And the data is updated using an onclick function This is making tha site slow.
So to make it fast I tried making a new useReducer and adding all the called objects in it, now i am stuck as I wanted to render the object present in this reducer from it and rest from the original state. But the original state is rendering every time onclick is called.

To make the condition, i used a conditional statement

!selected object 
? <Data value1={myState.value1} value2={value2} value3={value3} value3={value3} /> 
: <Data value1={myReducer.value1} value2={value2} value3={value3} value3={value3} /> 

And for iteration i have used nested Object.keys

console.log values of different environnement variables with their names stored in an array [duplicate]

I set different environement variables in node. I have an array containing the name of each variable.
I would like to loop through the array and console.log each variable (I mean the value).

Let’s assume I have a helloEnvVar environment variable with the value hello and a second byeEnvVarwith the value bye.

const ENV_VAR = ["helloEnvVar", "byeEnvVar"];
ENV_VAR.forEach(element => {
  console.log(`process.env.${element}`);
});

My goal is to display the value of each environement variable, and not their names.

How could I achieve that ?

What is, or How to Write this JS Code in Python?

would like to write the code js in python for requests module


pwd = "admin"
session.challenge1 = "9QX1DXX3NV29N0XA2DDRABJ0HT"
session.identity = "QWMDWBS9M20C3PSRSLM8ZHFJ0X"s1 = Sha256.hash(session.challenge1 + pwd.utf8Encode())

    NB: the result of s1 = "Ó`#u00071ru000b¿P/gÞ@Õb¬èÃE «W\u0015Sm·¡"

    when i try this methode the result is different

    s1 = Sha256.hash(session.challenge1 + pwd.utf8Encode())

What is a virtual for an URL in Mongoose?

I am currently following a tutorial on implementing a database (Mongoose) in a simple website created using Express-framework. I do not have any problem understanding the concept of models, but I fail to make sense of the lines following the comment “Virtual for book’s URL” in the code attached. How do these lines operate, and what role does having a virtual property have in this context?

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var BookSchema = new Schema(
  {
    title: {type: String, required: true},
    author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
    summary: {type: String, required: true},
    isbn: {type: String, required: true},
    genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
  }
);

// Virtual for book's URL
BookSchema
.virtual('url')
.get(function () {
  return '/catalog/book/' + this._id;
});

//Export model
module.exports = mongoose.model('Book', BookSchema);