How to center the label in MUI Textfield

I want to center the label and helper text in the middle of the Textfield. I got it working with adding a padding to MuiInputLabel-root. But this is not responsive on other screen sizes (Textfield changes size and the label isnt in the center anymore). I have tried using textAlign: 'center' but it doesnt work.

  1. Currently I have the Textfield with label on the left: Current

  2. I want to center the label and eventually helper Text too: Expected

  3. Currently when focused paddingLeft is set to 0 again: Focused

const StyledTextField = styled(TextField)({
    '& .MuiInputLabel-root': {
        paddingLeft: '85px',
    },
    '& label.Mui-focused': {
        color: '#000000',
        paddingLeft: '0px',
    },
    
     <StyledTextField
                        helperText="Privacy Policy "
                        InputProps={{
                            inputProps: {
                                style: { textAlign: 'center' },
                            },
                        }}
                        margin="normal"
                        fullWidth
                        id="email"
                        label="Email Address"
                        name="email"
                        autoComplete="email"
                        autoFocus
                        sx={{
                            m: 1,
                        }}
                    />

How do I dynamically create route using a function return in next.js

I am trying to create a simple multiplayer game. I want to use a randomly generated room id in the route in order to route to the newly created lobby but can not pass the functions return to router.push as query ; I don’t know why? Can you help me?

const RandomRoom = () =>{
        let romstr = "";

        for(let i=0; i<5; i++){
            const randomElement = randomchars[Math.floor(Math.random() * randomchars.length)];

            romstr += randomElement;

        }
        return romstr;
    }
    const handleSubmit = function () {

        return function () {
            if (!executed) {

                const param = RandomRoom;

                executed = true;

                socket.emit("joinroom", data1);

                console.log("roomid" + param);

                router.push({
                    pathname: `/lobby/[lobbyid]`,
                    query: {param}
            });
            }
        }
    }()

Why doesn’t event loop have timeout for microtasks?

async function() {
  while (true) {
    await null;
  }
}

This will block the thread forever, because the event loop would try to finish all microtasks in one frame.

With timeout be like:

  1. Event loop suspends processing next microtask after 1 sec, so the thread can be used to process other code, for example, animation frame
  2. In the next frame, event loop continues to process microtasks including those from the last frame until another 1 sec.

So the while (true) will block the thread for only 1 sec per frame, because await null; is suspendable.

I don’t mean I must have this feature.

I’d like to know why event loop was not designed like that, before microtasks/promises started existing, at that moment no backwards compatibility was needed.

Search an array – Javascript [duplicate]

the below code gives “The number doesn’t exist” even when input value matches. Thank you!

<input type="number" placeholder="Phone" id="phone" onkeyup="myfunction()">
<div id="msg" style="color:red;"></div>

<script>
function myfunction() {
var phone = document.getElementById("phone").value;
var array = [[0123456], [0789]];

if (array.flat().indexOf(phone) != -1) {
document.getElementById("msg").innerHTML = "The number already exists";
}else {
document.getElementById("msg").innerHTML = "The number doesn't exist";
}
}
</script>

how to close dropdown on click in html using javascript

i have a website where there is a dropdown like below:

<li class="dropdown">
  <a class="nav-link" href="#" id="shop_submenu" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        Rent
                      </a>
  <ul class="submenu dropdown-menu" aria-labelledby="shop_submenu">


    <li><a href="">Short Gowns</a></li>
    <li><a href="">Couple Combo Sherwani</a></li>

  </ul>
</li>

the javascript code is like below:

(function($bs) {
  const CLASS_NAME = 'has-child-dropdown-show';
  $bs.Dropdown.prototype.toggle = function(_orginal) {
    return function() {
      document.querySelectorAll('.' + CLASS_NAME).forEach(function(e) {
        e.classList.remove(CLASS_NAME);
      });
      let dd = this._element.closest('.dropdown').parentNode.closest('.dropdown');
      for (; dd && dd !== document; dd = dd.parentNode.closest('.dropdown')) {
        dd.classList.add(CLASS_NAME);
      }
      return _orginal.call(this);
    }
  }($bs.Dropdown.prototype.toggle);

  document.querySelectorAll('.dropdown').forEach(function(dd) {
    dd.addEventListener('hide.bs.dropdown', function(e) {
      if (this.classList.contains(CLASS_NAME)) {
        this.classList.remove(CLASS_NAME);
        e.preventDefault();
      }
      e.stopPropagation(); // do not need pop in multi level mode
    });
  });

  // for hover
  document.querySelectorAll('.dropdown-hover, .dropdown-hover-all .dropdown').forEach(function(dd) {
    dd.addEventListener('mouseenter', function(e) {
      let toggle = e.target.querySelector(':scope>[data-bs-toggle="dropdown"]');
      if (!toggle.classList.contains('show')) {
        $bs.Dropdown.getOrCreateInstance(toggle).toggle();
        dd.classList.add(CLASS_NAME);
        $bs.Dropdown.clearMenus();
      }
    });
    dd.addEventListener('mouseleave', function(e) {
      let toggle = e.target.querySelector(':scope>[data-bs-toggle="dropdown"]');
      if (toggle.classList.contains('show')) {
        $bs.Dropdown.getOrCreateInstance(toggle).toggle();
      }
    });
  });
})(bootstrap);

this is working fine fore opening, now i want to close it when the user clicks on it again, can anyone please tell me how to accomplish this, thanks in advance

Adding dropdown menu to navigation bar

Evening,

Learning on the job, currently doing a new website for my family business.

How can I make this drop down navigation menu work on desktop/mobile? I don’t want it too fancy, same design as the main navigation itself, I have fiddled around trying to make it work like the actual toggle so when users click ‘Services’ it would toggle down but it is not working as expected.

Ideally on hover it should display the drop down links for desktop, and mobile it should require a touch for it to display.

HTML

<div class="navigation-bar">
  <div class="navigation-item">
    <div class="logo">
      <a href="index.html">
        <img src="/assets/img/logo.jpg" alt="Company Logo">
      </a>
    </div>
    <ul class="navigation-bar-menu">
      <li class="active"><a href="index.html" class="active">Home</a></li>
      <li><a href="#">Services <i class="fa-thin fa-chevron-down"></i></a>

        <ul class="navigation-bar-dropdown">
          <li><a href="#">Managed Print Service</a></li>
          <li><a href="#">Document Management</a></li>
          <li><a href="#">Machine Finance Options</a></li>
          <li><a href="#">Machine Repair & Support</a></li>
        </ul>

      </li>
      <li><a href="#">Products <i class="fa-thin fa-chevron-down"></i></a>
        <ul class="navigation-bar-dropdown">
          <li><a href="#">Machines</a></li>
          <li><a href="#">Ricoh</a></li>
          <li><a href="#">Lexmark</a></li>
          <li><a href="#">Konica Minolta</a></li>
          <li><a href="#">Software</a></li>
          <li><a href="#">Kofax</a></li>
          <li><a href="#">Papercut</a></li>
          <li><a href="#">Filestar</a></li>
        </ul>
      </li>
      <li><a href="contact.html">Contact Us</a></li>
    </ul>
    <button class="navigation-bar-toggle">
      <i class="fa-light fa-bars"></i>
      Menu
    </button>
  </div>
</div>

CSS

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: #242424;
  font-family: 'proxima-nova', sans-serif;
  font-weight: 100;
  font-style: normal;
  font-size: 16px;
  line-height: 1.5rem;
}

li {
  list-style-type: none;
}

a {
  text-decoration: none;
  color: inherit;
}

.navigation-bar {
  background-color: #ffffff;
  padding: 2rem 1rem;
  position: relative;
  box-shadow: rgba(14, 30, 37, 0.12) 0px 2px 4px 0px, rgba(14, 30, 37, 0.32) 0px 2px 16px 0px;
}

.navigation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo img {
  width: 10rem;
  display: block;
}

.navigation-bar-toggle {
  padding: 1rem;
  background-color: #ecf0f1;
  color: inherit;
  cursor: pointer;
  text-transform: uppercase;
  border: none;
  font: inherit;
  border-radius: 0.25rem;
}

.navigation-bar-dropdown {
  display: flex;
  flex-direction: column;
}

.navigation-bar-menu {
  flex-direction: column;
  right: 0;
  overflow: hidden;
  top: 100%;
  background: #ecf0f1;
  display: none;
  position: absolute;
  width: 100%;
}

.navigation-bar-menu .active {
  background-color: #242424;
  color: #ffffff;
  font-weight: 300;
}

.navigation-bar-menu li {
  display: flex;
  justify-content: center;
  padding: 1rem;
}

.navigation-bar-menu a {
  text-transform: uppercase;
}

.navigation-bar a:hover {
  opacity: 1 !important;
}

.navigation-bar-menu :not(.active):hover {
  background-color: #242424;
  color: #ffffff;
  opacity: 1;
  animation-name: fadeInOpacity;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  animation-duration: 500ms;
}


.navigation-bar-menu.open {
  display: flex;
}

@media only screen and (min-width: 700px) {
 /* NAVIGATION BAR */
 .navigation-bar-toggle {
   display: none;
  }
  
  .navigation-bar-menu {
    display: flex;
    flex-direction: row;
    position: relative;
    background: none;
    justify-content: end;
    width: auto;
    gap: 1rem;
  }

  .navigation-bar-menu li {
    background-color: #ecf0f1;
    border-radius: 0.25rem;
    padding: 1rem;
  }
}

JS

  window.addEventListener('DOMContentLoaded', () => {
  const menuToggler = document.querySelector('.navigation-bar-toggle')
  const menu = document.querySelector('.navigation-bar-menu')

  menuToggler.addEventListener('click', () => {
    menu.classList.toggle('open')
  })
})

Any help would be greatly appreciated.
https://jsfiddle.net/fc471p3e/4/

I want to create a function App in Azure which will take data from ADX and SQL and perfrom transfromation on their data using JavaScript

I want to create a function app using JavaScript which will fetch the data from Azure data explorer and SQL DWH and perfrom some transformation to the the data and send the data to Blob file.

I tried to fetch data from ADX using Azurekusto data npm and my data looks like in the image below. I have parsed the JSON data and now I want to perfrom inner join on data between two different sources, that is Timeseries data from ADX table and payload data from DWH. I am new to JavaScript. Any suggestions on how to use my data from two sources and perfrom transformations like inner join to it

This is how my code looks like

module.exports = async function (context, req) {

const KustoClient = require("azure-kusto-data").Client;
const KustoConnectionStringBuilder = require("azure-kusto-data").KustoConnectionStringBuilder;

const kcsb = KustoConnectionStringBuilder.withAzLoginIdentity(`https://clustername.kusto.azuresynapse.net`); // optionally also pass authorityId
const client = new KustoClient(kcsb);

const results = await client.execute("Database", "Table | limit 10");
//console.log(JSON.stringify(results));
//console.log(results.primaryResults[0].toString());

const obj1 = results.primaryResults[0].toString();
const obj2 = JSON.parse(obj1);
x = obj2.data;
console.log(x);

}

This is how my result looks like :

JSON format of ADX table data

Transform Google Analytics 4 datalayer to braze purchase

I would like to use our GA4 (Google Analytics 4) purchase datalayer to send those information to our customer engagement tool braze. I am not sure how to loop through the GA4 items and pass them to braze. Any help is highly appreciated!

The GA4 datalayer looks like that:

dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
dataLayer.push({
  event: "purchase",
  ecommerce: {
      transaction_id: "T_12345",
      affiliation: "Google Merchandise Store",
      value: 25.42,
      tax: 4.90,
      shipping: 5.99,
      currency: "USD",
      coupon: "SUMMER_SALE",
      items: [
       {
        item_id: "SKU_12345",
        item_name: "Stan and Friends Tee",
        affiliation: "Google Merchandise Store",
        coupon: "SUMMER_FUN",
        currency: "USD",
        discount: 2.22,
        index: 0,
        item_brand: "Google",
        item_category: "Apparel",
        item_category2: "Adult",
        item_category3: "Shirts",
        item_category4: "Crew",
        item_category5: "Short sleeve",
        item_list_id: "related_products",
        item_list_name: "Related Products",
        item_variant: "green",
        location_id: "L_12345",
        price: 9.99,
        quantity: 1
      },
      {
        item_id: "SKU_12346",
        item_name: "Google Grey Women's Tee",
        affiliation: "Google Merchandise Store",
        coupon: "SUMMER_FUN",
        currency: "USD",
        discount: 3.33,
        index: 1,
        item_brand: "Google",
        item_category: "Apparel",
        item_category2: "Adult",
        item_category3: "Shirts",
        item_category4: "Crew",
        item_category5: "Short sleeve",
        item_list_id: "related_products",
        item_list_name: "Related Products",
        item_variant: "gray",
        location_id: "L_12345",
        price: 20.99,
        promotion_id: "P_12345",
        promotion_name: "Summer Sale",
        quantity: 1
      }]
  }
});

To log purchases in braze the data needs to adjust to the braze model:

braze.logPurchase(productId, price, currency, quantity);

The mapping would be the following:

braze GA4


productID -> item_id

price -> price

currency -> currency

quantity -> quantity

Why is the document not deleting in the database?

The problem that occurs is the user is not getting removed from the document in the database. The user is named mention.

This is the ingroups schema that im using

const mongoose = require("mongoose")

const groupSchema = mongoose.Schema({
    User:String,
    GroupName:String,
    TotalAmountDonated:Number,
})

module.exports = mongoose.model("InGroup", groupSchema, 'InGroups')

**This is where the mention variable comes from**
 .addSubcommand(subcommand =>
             subcommand
            .setName('kick')
            .setDescription('Kick an unfortunate group member')
            .addUserOption(option =>
              option
            .setName('groupmember')
            .setDescription('Group member you would like to kick')
            .setRequired(true))),```
These are the if statements and for some reason the findOneAndDelete line is not working

 
  const mention  = interaction.options.getUser('groupmember')
     const data1 = await ingroups.findOne({User:mention.id})
if (data1 !== null) {
        if(data1.GroupName !== user.GroupName){
           return await interaction.reply('The person you are attempting to kick is not in your group.')
      } 
     await ingroups.findOneAndDelete({ User:mention.id })
    return await interaction.reply(`<@${mention.id}> has been successfully kicked from the group`)
    } else {
        return await interaction.reply('The user you are trying to kick is not in a group!')
    }
                }
            }
}

MapboxGL Add multiple markers from array using Flask

Im currently trying to create a live flight tracker but I can’t figure out how to convert my table of flights call signs and their lat/long to a marker.

Here is the code I am currently working on

            const table = document.querySelector('table')
            for (const r of table.rows) {
                var planeinfo = []
                for (const c of r.cells) {
                    planeinfo[c] = c.innerHTML
                    console.log(planeinfo[c] = c.innerHTML)
                }

                
                const marker = new mapboxgl.Marker()
                    .setLngLat([planeinfo[1], planeinfo[2]])
                    .addTo(map)
            }

It works at pulling the info from the table which is attached below but it won’t create a marker and is throwing errors on creation of the marker.

I appreciate any assistance!

image of table

the id of cart shows null in controller but i m sure i m sending it NODE JS

I m sending the id of the product from this view (I m using express and mongoose db)

    <form action="/cart" method="POST">
      <input type="hidden" name="id" value="<%= product._id %>" />
      <button class="btn" type="submit">Add to Cart</button>

I m sure it is not null here

then I have this middleware to receive it

router.post("/cart", shopController.postCart);

and here is the function post Cart

exports.postCart = (req, res, next) => {
  const prodId = req.params.id;
  console.log("id returned from the params : " + prodId);
  Product.findById(prodId)
    .then((product) => {
      console.log(product);
      return req.user.addToCart(product);
    })

When I first receive it in the postcard function I made a log and it gives me the log console

id returned from the params: undefined
null

I tried wrapping the id with ObjectId of mongoose then it shows me this message

exports.postCart = (req, res, next) => {
  const prodId = req.params.id;
  console.log("id returned from the params : " + ObjectId(prodId));
  Product.findById(ObjectId(prodId))
    .then((product) => {
      console.log(product);
      return req.user.addToCart(product);
    })

error :

id returned from the params : 62c9a1ca3b17ea86134d12fc
null

product:
in database :

{  "_id": {    "$oid": "62c87c728594df06fd459521"  },  "title": ",gh,",  "price": 44,  "description": "nfggfngh ",  "imageUrl": "https://media.gettyimages.com/photos/stack-of-books-picture-id157482029?s=612x612",  "userId": {    "$oid": "62c71d0ab0312958a8082d6f"  },  "__v": 0}

Setting UTC timezone with numeric values in JS [UTC+2, UTC+3, UTC-12, etc]

How can I create a date with a specific timezone like that [UTC+2, UTC+3, UTC-12, etc] but not with string like that ‘America/New York’ in js/moment.js? I have a list of all timezones from server in this format [UTC+2, UTC+3, UTC-12, etc], so I need to create dates with a choosen timezone. I tried to use moment.js but it accepts only strings formate. Thanks ahed!

Create a js variable using a python function [duplicate]

I created a Python function named get_maps() that has 2 arguments, year and category and I would like to access it from JS, customizing those 2 arguments. However the code below returns an error:

list is not specified

function onSubmit(e) {
  e.preventDefault()
  
  if (year.value === "" || cat.value === "") {
    msg.textContent = "Please fill out the fields"
    msg.classList.add("error");
  } else {
    msg.textContent = ""
    msg.classList.remove("error");
    
    $.ajax({
      type: "POST",
      url: "~/mapsinterpeter.py",
    }).done(function(o) {
      list = get_maps(year.value, mapdict.cat.value)
    });
    
    year.value = ""
    cat.value = ""
    
    console.log(list)
  }
}

How do I Output a value of a nested object in Javascript after looping through?

I’m having some trouble printing out some of my data of a forEach loop. I’m working on a Twitter clone and I’m trying to loop through an object and print out the tweets for a user. I’m getting the divs to print out in the console but I can’t seem to figure out to get the tweets to print inside the div.

Any help would be appreciated.

var user1 = {
    userName: '@elonmusk',
    displayName: 'Elon Musk',
    joinedDate: 'June 2009',
    followingCount: 103,
    tweetAmount: 18600,
    followerCount: 47900000,
    avatarURL: 'assets/elonmusk.jpg',
    coverPhotoURL: 'assets/elonmusk-cover.jpeg',
    tweets: [
        {
            text: 'I admit to judging books by their cover',
            timestamp: '2/10/2021 00:01:20'
        },
        {
            text: 'Starship to the moon',
            timestamp: '2/09/2021 18:37:12'
        },
        {
            text: 'Out on launch pad, engine swap underway',
            timestamp: '2/09/2021 12:11:51'
        }
    ]
};

var container = document.getElementById('container');
var midSection = document.getElementById('mid-section')
var sections = document.createElement('div');
sections.classList.add('container');

sections.innerHTML = `
    <div class="left-section"></div>
    <div class="mid-section">
        <div id="header">
            <img class="arrow" src="./assets/arrow-left.svg" />
          <div class="user-info">
            <h2>${user1.displayName}</h2>
        <div class="numberOfTweets light-text">${user1.tweetAmount}K Tweets</div>
        </div>
        </div>
        <div class="cover-photo"><img src="${user1.coverPhotoURL}"/></div>
        <div id="avatar">
        <div class="profileImage"><img src="${user1.avatarURL}"/></div>
        <div class="follow">
            <button class="btn-more"><img src="./assets/three-dots.svg"/></button>
            <button class="btn-follow btn-primary">Follow</button>
        </div>
        </div>
        <h2 class="pl20">${user1.displayName}</h2>
        <div class="user-info2 light-text pl20">${user1.userName}</div>
        <div class="join-date light-text pl20 pt10">Joined ${user1.joinedDate}</div>
        <div class="following pl20 pt10">
        <p><span class="bold">${user1.followingCount}</span> Following</p>
        <p class="pl20"><span class="bold">${user1.followerCount}</span> Followers</p>
        </div>

        <div class="tab-navigation pt20">
           <div class="tabs">Tweets</div>
           <div class="tabs">Tweets & replies</div>
           <div class="tabs">Media</div>
           <div class="tabs">Likes</div>
        </div>
        <div class="tweets">
      
        </div>
    </div>

    <div class="right-section"></div>
`;

var user1Tweets = user1.tweets;

var tweetDivs = user1Tweets.map((tweetDiv) => {
    if(!tweetDiv.tweets) {
        return { ...tweetDiv, tweets: []};
    } else if (!Array.isArray(tweetDiv.tweets)) {
        return { ...tweetDiv, tweets: Object.values(tweetDiv.tweets)};
    }
    return tweetDiv;
});

tweetDivs.forEach(function(tweetDiv, i) {
    var tDiv = document.createElement('div');
    tDiv.classList.add('tweetDiv');
    tDiv.innerHTML = `

    ${tweetDiv.tweets.map(function(tweet) {
        return `<div>${tweet}</div>`
    })}
  
    `;
    console.log(tDiv)
    midSection.appendChild(tDiv);
})

container.appendChild(sections);