Problem when using eval to create a function

It was a complicated code, I simplified it to this

class Wr{
    constructor(w){this.w=w}
}
class E{}
Array.prototype.popfirst=function(){
    this.splice(0,1)
}
function w(){
    let a=["Wr",new E()]
    eval(`var f=function(args){return new ${a[0]}(...args)}`)
    a.popfirst()
    console.log(f)
    console.log(",")
    console.log(...a)
    console.log(",")
    console.log(f(a))
}

I want f(a) to be new Wr(new E()),
but when l checked the console, I saw only one ƒ (){ this.splice(0,1) }. But I used 5 log()!

I fixed the code several times but still don’t understand where the problem is.

How to continously map an array in JavaScript?

I am trying to create an alert component in React.JS which would receive one array as props and then loop through all the elements inside and display them in the alert component.

I do not know how to restart the loop when the array map ends.

This is my code:

        useEffect(() => {
                props.messages.map((item, index) => {
                        setTimeout(() => {
                          setMessage(item);
                        }, 5000*index)
                      });
        },[]);

I want to run the loop continuously until the user closes the notification alert.

My guess is to wrap the map inside a while / do while in order to run it until the user closes the notification bar. I am having trouble restarting the loop once the map of the array gets to the last element.

“INVALID QUERY RESULT MASK” PostgreSQL through Javascript

I have been trying to access a psql function using the db.func function.

The following is my query

CREATE OR REPLACE FUNCTION play_game(game INT, IN userid INT, IN card INT, OUT uid INT, OUT cid INT, OUT cardfile varchar(255) ) RETURNS SETOF record as
$$
DECLARE
     playorder integer;
     
     cardtype varchar(6);
     cardcolor varchar(10);
     cardvalue integer;
     
     l_cardtype varchar(6);
     l_cardcolor varchar(10);
     l_cardvalue integer;
     cardid integer;
Begin
    -- check if this is the user who has to play
    SELECT play_order INTO playorder FROM user_game WHERE user_id = userid;
    
    IF playorder = 1 THEN
        -- get card attributes
        SELECT card_type, card_color, card_value
             INTO cardtype, cardcolor, cardvalue
            FROM card
         WHERE card_id = card;
     
         -- get the attributes of the last card that was played for this game
         select c.card_id, c.card_type, c.card_color, c.card_value
           INTO cardid, l_cardtype, l_cardcolor, l_cardvalue
           FROM play_card pc, card c
           WHERE pc.card_id = c.card_id
                  AND pc.game_id = game
                  AND pc.id = (SELECT MAX(id) FROM play_card WHERE game_id = game);
       Begin
            -- check this is the right card to play
            IF cardcolor = l_cardcolor AND
                 cardtype = 'NOM' THEN
                INSERT INTO play_card (game_id, user_id, card_id) VALUES (game, userid, card);
                -- delete card from draw card
                DELETE FROM game_card WHERE game_id = game and card_id = card;
            END IF;
            commit;
       End;
       
       -- move play to the next player
       Begin
          IF cardtype = 'NOM' THEN
               UPDATE user_game
                        SET play_order = play_order - 1
                 WHERE game_id = game;
               
               UPDATE user_game
                        SET play_order = (SELECT count(user_id) from user_game WHERE game_id = game)
                 WHERE game_id = game;
            ELSE
                  UPDATE user_game
                           SET play_order = 1 + (SELECT count(user_id) from user_game WHERE game_id = game) - play_order
                       WHERE game_id = game;
            END IF;
       End;
       
    End if;

    -- get game state and return to Front END
  RETURN QUERY SELECT gc.user_id, gc.card_id, c.image_file FROM game_card gc, card c WHERE gc.card_id = c.card_id AND gc.game_id = game ORDER BY user_id;
END;
$$ LANGUAGE plpgsql;

This is my javascript function

db.func("play_game", { gameId, userId, cardId })
    .then((results) => {
      let card = results;
    })
    .catch((error) => {
      console.log("error in play_game databse function: ", error);
    });

I have even tried passing the parameters without the object but I get the error saying “invalid query result mask”

It also gives the following hint:
No function matches the given name and argument types. You might need to add explicit type casts.

Please let me know what to do. Any help is appreciated. Thank you 🙂

how to auto generate git PATs?? (personal access tokens)?

I also using JavaScript, vue.js, Wsl , git ssh, and java ( Spring, Spring boot )

enter image description here

i have been trying to get Personal access token ( PATs ) from github.com.

but in the project that i am working on, the token is not permanent.

it just goes away after i have used the token several times.

in github.com it says This token expires on Mon, Jan 10 2022 but i think it has been

invalidated after i used it multiple times even if there is a month left before expiration date.

so i want to regenerate the token after invalidation through Java ( 1.8 ) or JavaScript

please let me know any ways to solve this problem

Rendering Approach for Complex Text Annotation

I am looking for a way to provide rendering of complex annotations for text in a javascript context. The annotations are based on the way a user has tagged individual words and groups of words. The annotating can be hierarchical. E.g. a group may have an annotation that spans the width of the group while individual words within the group may also have their own annotation. I have considered css, canvas and svg. With the latter two am not clear on how to position the rendering such that it lines up with the text. See sample markup below.

Sample markup

How to process socket.io events in their incoming order

I have the following setup:

async MyFunction(param) {
    //... Do some computation
    await WriteToDB()
}

io.on('connection', (socket) => {
    socket.on('AnEvent', (param) => MyFunction(param))
})

When an event comes in, it calls an asynchronous function which does some computation and in the end write the result to a database with another asynchronous call.

If MyFunction doesn’t have an asynchronous call to write the database in the end, for example

MyFunction(param) {
    //... Do some computation
}

then it is obviously that all events will be processed in their incoming order. The processing of the next event will only start after the processing of the previous one finishes. However, because of the asynchronous call to the database, I don’t know if those incoming events will still be fully processed in order. I am afraid that the processing of the next event starts before the previous await WriteToDB() finishes. How do I change the code to fully processing them in order?

Why does Node pass in the exports argument on top of the module argument?

It is known that each module in Node.js is wrapped in a function, where 5 arguments are passed in (i.e. exports, module, require, __filename, __dirname) and the module.exports object is returned.

Since exports is just an alias for module.exports, is there a reason why both module and exports are listed as 2 separate arguments? In terms of design, is it simply for the ease of accessing the exports object?

I couldn’t find this question being answered, but I’m happy to be redirected to an existing one.

// function (exports, module, require, __filename, __dirname) {

const a = 1;
console.log(a);

// return module.exports;
// }

How to format data-logger results as JSON?

I have a data logger that records time, status & temperature by appending to a file. (The logger is called from a cron job.)

It would be great if I could read the data into a web page script as JSON, but I don’t see a good way to do it — either my logger is more complicated, or my reader is more complicated.

My data is lines like:

[ timestamp, "status", temperature ]
[ 123456789, "sync",   12345]

I can add commas to the line ends easily enough, but either way, it’s not well-formatted JSON — you need brackets around the whole thing.

So either my logger must detect an empty data file and add a leading bracket, plus seek to the end, back up a character, replace the last close-bracket with a comma, and then append its own record with an extra closing bracket, or the reader has to massage the pre-JSON by slicing off a trailing comma and adding brackets around.

Is there an easier way to do this?

Unable to get required values from a regex match in javascript

I’m having some problems with regular expression

Here is the code:

var interpolate = /{ .* }/g

var data = "{ name } { roll } data { app }"

console.log(data.match(interpolate))

I expect the output to be ["{ name }", "{ roll }", "{ app }"]
But when I actually run it, I get the complete string as output,

i.e:

[Running] node "/home/mayukh/Desktop/Projects/tests/regular.js"
[ '{   } { roll } data { app }' ]

I don’t know what exactly is happening.

Reactjs Dynamically call components having cards under tabpanels using array

This is where Tab header and tab content is defined, expectation is Tabs_content has component name, and under tabpanel it should traverse array tabs_content and display component < AddQueueCard /> and call the component shown in image 3

let tabs_data= ['Add Queue','Edit Queue','Remove Queue'];
    let tabs_content= ['<AddQueueCard />','EditQueueCard','C content' ];
<div class="card-body">
        <div class="tab-content">
          <div class="tab-pane active">
          <div>
               <div  id="test">
        <Tabs>
          <ul>
            <TabList>
              
            {tabs_data.map(i => (
                <Tab>{i}</Tab>
                  ))}`***enter code here***`
            </TabList>
            </ul>
            {tabs_content.map(i => (
            
                <TabPanel>
              {i}   {/* here I want to call cards dynamically like <AddQueueCard /> <EditQueueCard> if clicked on 1st or 2nd tab respectively. How do I do that */}
               </TabPanel> 
            
              ))}
          </Tabs>
        </div>
        </div>
         </div>
          <div class="tab-pane">
      
          </div>
          
        </div>
      </div>

Currently cards are not called
enter image description here
Expected output

ArcGIS-JS-API – Custom Content in Popup Template is display nothing (Angular 11)

I want to display a hyperlink on the bottom of the popup template in arcgis esri map. I’ve added the code I’ve tried, but hyperlink is not displaying in the popup template. Only the fields table is displaying. Could you please have look into this code and let me know if I’ve missed something.

.ts file

const popUpTemplate = new PopupTemplate({
      title: "{name}",
      content: [
          {
              type: "fields",
              fieldInfos: [
                  {
                      fieldName: "PhysicianName",
                      label: "Physician Name"
                  },
                  {
                      fieldName: "PrimarySpecialty",
                      label: "Primary Specialty",
                  },
              ]
          },
    
        new CustomContent({
          outFields: ["*"],
          creator: (graphic) => {
              const a = document.createElement("a");
              a.href = graphic.attributes.url;
              a.target = "_blank";
              a.innerText = graphic.attributes.url;
              return a;
          }
      })
      ],
      outFields: ["*"]
    });
    
    const dataFeedLayer = new FeatureLayer({
        source: locationData.map((d,i)=>(
          {
              geometry: new Point({
                longitude: d.longitude,
                latitude: d.latitude
              }),
              attributes: {
                ObjectID: i,
                ...d
              }
          }
        )),
      objectIdField: 'ObjectID',
      popupTemplate : popUpTemplate,
    });

.html file

 <!-- Map Div -->
    <div #mapViewNode></div>

How to run custom made node.js commands inside of a running application?

I’m trying to make a Discord bot, I would like a way to reload commands or the client through the console white my application is running.

EG: When you type commands into a servers console or something similar to like that. Or I can type ‘reload’ and it will reload the client.

I could try doing something with readline https://www.npmjs.com/package/readline, but I’m mostly wondering what is the best way to achieve this.

Thanks in advance,
Luke.

Why does React rerender when the state is set to the same value via an onClick event?

I have what I thought would be a simple test to prove state changes, I have another test which does the change by timer and it worked correctly (at least I am assuming so) but this one is trigged by a click event and it’s failing my rerender check.

  it("should not rerender when setting state to the same value via click", async () => {
    const callback = jest.fn();
    const baz = "baz";
    function MyComponent() {
      const [foo, setFoo] = useState("bar");
      callback();
      return (<div>
        <div data-testid="set1" onClick={() => { setFoo(baz); }} >FF</div>
        <div data-testid="test">{foo}</div>
      </div>)
    }

    const { getByTestId } = render(<MyComponent />)
    const testElement = getByTestId("test");
    const set1 = getByTestId("set1");
    expect(testElement.textContent).toEqual("bar");
    expect(callback).toBeCalledTimes(1)

    fireEvent.click(set1);
    await waitFor(() => expect(testElement.textContent).toEqual("baz"));
    expect(callback).toBeCalledTimes(2)

    fireEvent.click(set1);
    await waitFor(() => expect(testElement.textContent).toEqual("baz"));
    expect(callback).toBeCalledTimes(2) // getting 3 here.

  })