return value from function and add to map [closed]

Send Key & value from a function and add in map. How to do that?

Arr = [2,5,7,9,8,6,1]
Sum = 15

Result = twoSum(Arr,Sum)

function twoSum(nums, target) {
    let map = new Map()
    for(let i=0;i<nums.length;i++){
        let complement = target - nums[i]
        if(map.has(complement))
            return [map.get(complement),i]
        map.set(nums[i],i)
    }
};

console.log(Result)

I trying to get the output both the Index and the Index value. Example :

Output : Index :2 Value : 7
Index : 4 Value : 8

How to achieve that?

Second array reversed on serving by express

I’m working with node with express and leaflet (server and client) to build a map, On the server I have:

app.get('/data', async (req, res) => {
    try {
        const data = await getRandomRoad();
        res.status(200).json({'data':data});
        // res.status(200).render({'data':JSON.stringify(data)});
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

The data being returned ia a couple of coordinates , and looks like:

[ [ -112.1067146, 31.6712959 ], [ -112.1216258, 31.6653063 ] ]

On the client side I have:

 async function getGeoJSONArr() {
    const response = await fetch("http://localhost:3000/data");
    console.log('response ',response);
    const jsonArr = await response.json();
    console.log("respo", jsonArr);
    
    return jsonArr.data;
  }

In my console I have:

respo {data: Array(2)}data: Array(2)0: (2) [-112.1067146, 31.6712959]1: (2) [31.6653063, -112.1216258]length: 2[[Prototype]]: Array(0)[[Prototype]]: Object

You can see that the second coordinate array is reversed. – Why?

Unable to Correctly Pass State/Event Data from Grandchild Component to Parent?

I have a darkMode toggle as a separate component (grandchild) which is embedded in a Navbar component (child). That Navbar component is called in the App component (parent).

Essentially, my goal is that when I toggle the darkMode/lightMode button in the DarkMode component, it sends this ‘event’ through the Navbar and up to the App.js where the CSS change will be called and is dependent on a conditional operator.

I’ve tried to pass some props with what basic knowledge I have, but I can’t seem to work out how to actually pass the state/event.

I’m not sure if what I am trying to do is even achievable and/or is too complex, so would really appreciate suggestions. I know I can place all of this code in the App.js, but I wanted to separate my components.

App.js (parent)

const App = () => {
  const [darkMode, setDarkMode] = useState(true);

  return (
    <div className={darkMode ? "darkmode" : "lightmode"}>
      <Navbar darkMode={darkMode}/>
      <Hero />
    </div>
  );
}

Navbar.js (child)

const Navbar = ({darkMode}) => {
  return (
    <div className="row">
      <div className="col">
        <h3>This is the Navbar component</h3>
      </div>
      <div className="col">
        {/* This is the DarkMode component button */}
        <DarkMode darkMode={darkMode} />
      </div>
    </div>
  )
}      

DarkMode.js (grandchild)

const DarkMode = ({darkMode}) => {

  const [isDarkMode, setDarkMode] = useState(false);
  const [imageSrc, setImageSrc] = useState(SunIcon);

  const switchModes = () => {
    setDarkMode(prevMode => !prevMode);
    isDarkMode ? setImageSrc(SunIcon) : setImageSrc(MoonIcon);
  };

  return (
    <>
      <button>
        <img
          className=""
          onClick={switchModes}
          src={imageSrc}
          alt="lightning-bolt"
          height="30px"
        />
      </button>
    </>
  )
}

Can a file uploaded by a user to Survey123 be accessed directly from the XLSForm’s Javascript code?

I’m working on a Survey123 form to which users need to upload a csv or excel file. I want to perform a validation of the file content immediately the user uploads it and before the user sends it. For this I am trying to use javascript code in the XLSForm and Webpack to be able to use additional functions and libraries. However when trying to access the file I can only get its name and not its content. It occurred to me to access the temporary file that is generated in the system when the user uploads his file, using libraries such as fs or Papa.parse, but these libraries, not being the original ones but a translated and reduced variation for Webpack, do not count with the necessary functions to access the file.

It should be noted that survey (or webpack) does not allow me to use asynchronous functions or promise requests.

Is there a way to access the content of the files to be able to execute the validations before submitting the form?

How to find best match in a list of strings in javascript

I have an array of products like this

let products= ['Avocado', 'Grapes', 'Oranges', 'Pineapple', 'Apples'];

I need a function that given a variable, it will return the product more similar to it. For instance

'Avo' = 'Avocado'
'Grape'  = 'Grapes'
'ORANGES' = 'Oranges'
'Apple' = 'Apples'

I tried using a filter like this, but I think I will need to do a Regex pattern to match the product name.

  let product  = products.filter(
          (obj, index) =>
            products.findIndex(
              (item) =>
                variable.match(
                  item
                ) 
            ) === index
        );

How to maintain the sheet style/format when automating an email?

My code is working to a certain extend, the email get sent with the right title and message, the problem is that when the data is copied from the google sheets, it is paste only values. I needed the formats/colors/shapes etc in the email as well can someone please help???

here is my code

function shiftsetting(){}
const d = new Date();
var day = d.getDay();
var shift="AM";
var month= d.getMonth();
var numberday = d.getUTCDate();

var dayNames = ["Sunday", "Monday", "Tuesday","Wednesday","Thursday", "Friday", "Saturday"];
var weekday = dayNames[day]



function getshift(){
if (d.getHours()>14){
 shift = "PM";
} else {
 shift = "AM";
}}

 function testTableHTML(){

  
  var file=SpreadsheetApp.openById('1vQIpduKw8qp65oNMJt5XsTNOMQEsNaR8FA64kL1GXi0');
  var ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CO Plan Release");
  var data= ss.getRange("B2:G22").getValues();
  var emailcontent= data
  return (tableHTML(emailcontent));
}
function tableHTML(emailcontent){
  return emailcontent;
}

  var sendto = "[email protected]";
  var text= 'CO ' + weekday +'  ' + month+'/'+numberday +' '+ shift +'  '+'Plan Review';

  MailApp.sendEmail(sendto, text, testTableHTML(), {
  cc: '[email protected]'});

Cannot find usages of overwritten JavaScript function in WebStorm

WebStorm(2023.1.1) cannot find all usages of an overwritten function in JavaScript language.

Example:

abstract class Vehicle {
  abstract drive()
}

class Car {
  drive() {
  ....
  }
}

If I now call the drive() method of a Car instance somewhere in the code and check for usages, WebStorm is not able to find them.
Am I missing some setting or does someone else have the same problem?

Handler for turbo frame-related errors that displays custom error messages

I’m using Rails 7 and am thinking of implementing a handler for turbo frame-related errors that displays custom error messages. For example, I would like to display An error occurred, try later instead of the default Content missing message, maybe associating error messages with HTTP statuses and handling this in one place and globally via JS.

Any insight about? For example, where (i.e. in which file e.g. app/javascript/application.js) and how (e.g. using addEventListener(), turbo:frame-missing event, custom actions) should I make that?

How to Pass Variable declared in script tag from handlebars page to mysql database Using NodeJs Sequelize?

I want to pass the value of variable declared in script tag of handlebar page to mysql database while submitting the form. I want to give some ratings and reviews to a particular post. On mouseenter and mouseleave the rating value will change and on submit it will be stored into database

This is my form in handlebars page

<form class="custom-form hero-form" action="/papers/add_review/{{paper.id}}" method="POST" role="form">

   <div class="row">

    <div class="col-12">
      <div class="d-flex flex-wrap align-items-center mt-4 mt-lg-0">
         <span class="text-black mb-lg-0 mb-md-0 me-3">Rate The Paper:</span>
           <h4 class="text-center mt-2 mb-4"><i class="fa-solid fa-star star-regular submit_star mr-1" id="submit_star_1" data-rating="1"></i>
<i class="fa-solid fa-star star-regular submit_star mr-1" id="submit_star_2" data-rating="2"></i>
<i class="fa-solid fa-star star-regular submit_star mr-1" id="submit_star_3" data-rating="3"></i>
<i class="fa-solid fa-star star-regular submit_star mr-1" id="submit_star_4" data-rating="4"></i>
<i class="fa-solid fa-star star-regular submit_star mr-1" id="submit_star_5" data-rating="5"></i>
                </h4>
        </div>
        </div>
   <div class="col-lg-12 col-12">
        <div class="input-group">
            <textarea class="form-control" name="user_review" id="user_review" placeholder="Comment As {{name}}"></textarea>
        </div>
      </div>
                    
<div class="col-lg-12 col-12">
<button type="submit" class="form-control" id="save_review">
Submit
</button>
</div>
</div>
</form>

This is my script tag in that same hbs file

<script>

     var rating_data = 0
     $(".submit_star").on('mouseenter', function(){
              var rating = $(this).data('rating');
              reset_background();
         for(var count = 1; count <= rating; count++)
          {

            $('#submit_star_'+count).addClass('text-warning');

        }
      })
       
    
   
      function reset_background()
    {
        for(var count = 1; count <= 5; count++)
        {

            $('#submit_star_'+count).addClass('star-light');

            $('#submit_star_'+count).removeClass('text-warning');

        }
    }
   
   
      $(".submit_star").on('mouseleave', function(){
              reset_background();

        for(var count = 1; count <= rating_data; count++)
        {

            $('#submit_star_'+count).removeClass('star-regular');

            $('#submit_star_'+count).addClass('text-warning');
        }
         }) 

          $(".submit_star").on('click', function(){
          rating_data = $(this).data('rating');

    })
    
  
</script>


Now, on submit the button I want to store the value of “rating_data” variable in to mysql database in user_rating column.

This is my route for submission

router.post("/add_review/:id", checklogin, (req, res) => {
  if (req.role === "admin" || req.role === "user") {
    console.log(req.email);
    let { user_review, rating_data } = req.body;
    let commentDate = new Date().toLocaleDateString();
    let commentTime = new Date().toLocaleTimeString();

    User.findOne({ where: { email: req.email } }).then((user) => {
      Paper.findOne({
        where: { id: req.params.id },
        include: [
          {
            model: PaperTopic,
            //required: true
          },
          {
            model: Category,
          },
        ],
      }).then((p1) => {
        const newReview = new Review({
          user_name: user.name,
          user_email: user.email,
          user_rating: rating_data,
          user_review,
          commentDate,
          commentTime,
          paperId: p1.id,
          userId: user.id,
        });
        newReview.save().then((new_review) => {
          res.redirect('/papers/' +p1.title )
          
        });
      });
    });
  } else {
    let { user_name, user_email, user_review, rating_data } = req.body;
    let commentDate = new Date().toLocaleDateString();
    let commentTime = new Date().toLocaleTimeString();
    
      User.findOne({ where: { email: req.email } }).then((user) => {
        Paper.findOne({
          where: { id: req.params.id },
          include: [
            {
              model: PaperTopic,
              //required: true
            },
            {
              model: Category,
            },
          ],
        }).then((p1) => {
          const newReview = new Review({
            user_name,
            user_email,
            user_rating: rating_data,
            user_review,
            commentDate,
            commentTime,
            paperId: p1.id,
            userId: "NULL",
          });
          newReview.save().then((new_review) => {

            res.redirect('/papers/'+p1.title )
           
          });
        });
      });
    
  }
});
module.exports = router;

I tried using req.body . After that it shows null. Please help me out

Scientific notation when importing data from MySQL to node.js by express [duplicate]

As in the title, I have very long ID’s in my database, and when I import them to node.js by express, in object data is converted to scientific notation, and rounds after 16 places.

31551979034426737773395171961457358310 –> 3.1551979034426736e+37
59493556845631438533043909910482570895 –> 5.949355684563144e+37

value.toLocaleString(‘fullwide’, {useGrouping:false}) = 31551979034426736000000000000000000000

Is there a way to keep the accuracy? Those are ID’s so they need to be represented in accurate form

How to move special characters and numbers to the end when sorting using `localCompare`?

The problem statement

I want to sort words alphabetically, but move numbers and special characters to the end of the list

For example, sorting:

zdx
9or
abc
a=c

should result in:

abc
a=c
zdx
9or

As you can see localeCompare doesn’t work like that. It treats numbers and symbols as “smaller” than characters.

const items = ['zdx', '9or', 'abc', 'a=c']
items.sort((a, b) => a.localeCompare(b))
console.log(items)

What I have tried:

Replacing all non-letters with a char code higher than z

const items = ['zdx', '9or', 'abc', 'a=c']
const last = String.fromCharCode('z'.charCodeAt(0) + 1)
items.sort((a, b) => a.replace(/[^a-z]/g, last).localeCompare(b.replace(/[^a-z]/g, last)))
console.log(items)

console.log(element.children) returns undefined in the console [duplicate]

let xxxy = document.getElementsByClassName("is-flex-container columns-3 alignwide wp-block-post-template is-layout-flow");

console.log(xxxy.children);

I am editing a WordPress theme and am trying to access the li children of a ul element. while logging out the ul parent (accessed as you can see in the first line of code) returns a node list with 1 element, as expected, logging out the children gives undefined (last line). what could be causing this?

Twitter API V2 reply to a tweet (getting 403 (unsupported authentication) with bearer token)

getting these error

Error Part

{
    "title": "Unsupported Authentication",
    "detail": "Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint.  Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context].",
    "type": "https://api.twitter.com/2/problems/unsupported-authentication",
    "status": 403
}


const { TwitterApi } = require("twitter-api-v2");
const config = require("../../config");
const client = new TwitterApi({
  appKey: config.twitter_config.api_key,
  appSecret: config.twitter_config.api_secret,
  accessToken: config.twitter_config.access_token,
  accessSecret: config.twitter_config.access_secret,
});
const bearer = new TwitterApi(process.env.BEARER_TOKEN);
const twitterClient = client.readWrite;
const twitterBearer = bearer.readOnly;
module.exports = { twitterClient, twitterBearer };



// i tried with these 2 methods 




async function replyToTweet(tweetId, replyMessage,accesstoken) {
            const accessToken =accesstoken ; 
            const url = `https://api.twitter.com/2/tweets`;
            const headers = {
              Authorization: `Bearer ${accessToken}`,
              'Content-Type': 'application/json',
            };
            const data = {
              hidden: false,
              in_reply_to_user_id: tweetId,
              status: replyMessage,
            };
            try {
              const response =await axios.post(url,{
                tweet:{
                    in_reply_to_status_id:tweetId,
                    text:replyMessage,
                }
              },{headers});
              console.log('Reply sent successfully:', response);
            } catch (error) {
              console.error('Error replying to tweet:', error);
            }
          }



   async function replyToTweet() {
                try {
                  const tweet = await client.v1.tweets.reply(tweetId, {
                    status: "maggi reply",
                  });
                  console.log('Reply sent successfully:', tweet.text);
                } catch (error) {
                  console.error('Error replying to tweet:', error);
                }
              }


I am trying hard to find a way to reply to a tweet with Twitter API V2, but it seems there is no endpoint for doing something like that, in Twitter API V2 package i found a way to a tweet, but i am struggling with replies, can you please help me with this? Thanks.