Need help in translating the map function for Python

I tried implementing the following JS code in Python but I am having issues while using the map function. I am unable to get the desired output. I have attached the working JavaScript implementation of the code and my Python implementation (which is not working).

This image contains the working JS implementation

Refer below for my python implementation.

Here is my python implementation

I feel I have messed up the map function in line 8.

IF ELSE not working inside the function javascript [closed]

I’m new to programming and having a hard time in this function. I’m using firebase and confuse why alert is working but the if else is not working.

this is my button and it has onclick
<button id="Insert" class="editrooms-save" onclick="register()" >Insert</button>

it confuses me because i call the ID and onclick. i know the function is working but it seems the if else is not working.

alert("TESTING")

document.getElementById("Insert").addEventListener("click", register);  

function register(){

fname = document.getElementById('fname').value;
mname = document.getElementById('mname').value;
lname = document.getElementById('lname').value;
contact = document.getElementById('contact').value;
dept = document.getElementById('dep=t').value;
email = document.getElementById('email').value;
password = document.getElementById('password').value;
 
if (validate_email(email) == false || validate_pass(pass) == false ){
 alert('Email or Password is XXXXXX')
 return
}

 
if (validate_email(contact) == false){
 alert('Contact is XXXXXX')
 return
}

if (validate_field(fname) == false || validate_field(mname) == false || validate_field(lname) == false || validate_field(dept) == false ){
 alert('Fill all fields!')
 return
}

auth.createUserWithEmailAndPassword(email, password)
 .then(function(){
     var user = auth.currentUser
     

     var user_data = {
       fname: fname,
       mname: mname,
       lname: lname,
       contact: contact,
       dept: dept,
       email: email,
       last_login: Date.now()
     }

     firebase.database().ref().child("adminaccount/" + user.uid).set(user_data)



     alert('user Created!')
 })
 .catch(function(error){
   var error_code = error.code
   var error_message = error.message

   alert(error_message)
 })

}



function validate_email(email){
 expression = /^[^@]+@w+(.w+)+w$/
 if(expression.test(email) == true) {
   return true
 } else{
   return false
 }
}

function validate_pass(password){
 if (password < 6){
   return false
 } else {
   return true
 }
}

function validate_contact(contact){
 express = /^(09|+639)d{9}$/
 if(express.test(contact) == true) {
   return true
 } else{
   return false
 }
}

function validate_field(field){
 if (field == null) {
   return false
 }

 if (field.length <=0){
   return false
 } else {
   return true
 }
}

How to transform an array to an object?

I have an array:

        const y = [
            {
                key: 'field',
                value: 'companyproject'
            },
            {
                key: 'comparisonoperator',
                value: '=='
            },
            {
                key: 'value',
                value: '62378525f7005c49080df965'
            },
            {
                key: '',
                value: ''
            },
        ]

And I want to create a single object using the keys and values of the array:

        const x = {
            field: 'companyproject',
            comparison_operator: '==',
            value: '62378525f7005c49080df965'
        }

Need help understanding regex functions

this is a continuation of How do I use regex to replace periods in a string?

for context I have a large table with strings containing dimensions

ie. " .175" x 2.5" x 8' "

// " means inches, ' means feet

I need to split every string into columns thickness, width and length. The solution I was provided in the previous example:

let x = "0.75 x 0.75 x 5.25 (144 bar)";

    let numbers = x.match(/(d*.)?d+/g).map(n => parseFloat(n))

    var thickness = numbers[0]
    var width = numbers[1]
    var length = numbers[2]
    //Do the regex function

    const regexFun = () => {
        try {
            console.log(x);
            console.log(thickness, width, length);

        } catch (err) {
            console.log(err.message)
        }
    }

The above will only really work 70% of the time for me due to how some entries are written

ie. " 72" extrusion "

Ideally there is a single line solution out there, but I don’t quite understand how regex works:

/(d*.)?d+/g

In the above how does it return .175 , I would assume it finds a number first and then the dot, so the result would be 175.

Single Page Application using injector – Javascrip reload the page

I am making a single page application using injection function :

<html>
<body>
<a href="javascript:injector('../../url1')"> link1 </a>
<a href="javascript:injector('../../url2')"> link2 </a>
<iframe id="iframe" width="100%" src=""></iframe>
</body>
</html>

<script>
function injector(url) {
 window.parent.document.getElementById("iframe").src = url;
}
</script>

There are 2 urls in this simple example. I can save the one that has been clicked on local storage. But:

  1. how do I explain in JavaScript (When the page is refreshed, use the last used url automatically)
  2. How to deal with going back to a previous page (a previous url). Is there a better way to deal with navigation in single page application using JS?

NuxtJS Vue 3: V-for breaks page design

I am currently building an anime search portal.
For this I use NuxtJS3 and Serverless Api.

However, when I receive search results from my api and it displays my results with v-for directive , the page’s background is cut off and the rendered elements are “outside” (?) the page. What did I do wrong? Down below is my component and screenshots.

top
bottom

index.vue

//   console.log("doene");

import { ref, onMounted } from "vue";
const searchText = ref("");
const myData = ref([]) as any;
const searchSize = ref(10);
var intervalChecker = ref(true);

onMounted(() => {});

async function searchForAnimes() {
  console.log("BEFORE:", intervalChecker.value);
  if (intervalChecker.value === true) {
    const data = await fetch(`/api/index?search=${searchText.value}`);
    const json = await data.json();
    myData.value = json.results;
    intervalChecker.value = false;
    console.log(searchText.value);
    console.log(json.results);
    console.log("AFTER:", intervalChecker.value);
    setTimeout(() => {
      intervalChecker.value = true;
    }, 7000);
  } else {
    alert("Bitte warte kurz einen Moment...");
  }
}
</script>
  <template>
  <div class="bg">
    <NuxtLayout name="navbar"></NuxtLayout>
    <div class="grid place-items-center h-screen">
      <form id="form" class="input-group flex justify-center mt-2 mb-2" @submit.prevent="searchForAnimes">
        <input
          type="text"
          id="searchInput"
          v-model="searchText"
          placeholder="Type here"
          class="input input-bordered input-primary w-full max-w-xs"
        />
        <button id="formBtn" class="btn btn-primary btn-square">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
        </button>
      </form>

      <div v-for="anime in myData" :key="anime.mal_id">
        <div class="card card-side bg-base-100 shadow-xl m-4">
          <figure>
            <img :src="anime?.image_url" :alt="anime_cover" />
          </figure>
          <div class="card-body">
            <h2 class="card-title">{{ anime?.title }}</h2>
            <p>{{ anime?.synopsis }}</p>
            <div class="card-actions justify-end">
              <button class="btn btn-primary">Watch</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>


<style scoped lang="scss">
.carousel-item {
  width: 15rem !important;
}

.bg {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  height: 100vh;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>

<script lang="ts">
function removeMessage(id) {
  var el = document.getElementById(id);
  if (el.style.display === "none") {
    el.style.visibility = "visible";
    el.classList.add("modal-open");
  } else {
    el.style.visibility = "hidden";
    el.classList.remove("modal-open");
  }
}
</script>

When i run the npm run build for react project i am getting the error, please check below code

'REACT_APP_BUILD_ENV' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `react-csp dev && REACT_APP_BUILD_ENV='test' react-scripts build && gulp licenses`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersShubham JayswalAppDataRoamingnpm-cache_logs2022-03-22T13_44_53_411Z-debug.log

I am trying to build my code but when I run npm run build with react project getting every time error, stuck there don’t have an idea how to resolve that error, could please give me solution how to fix that error.

I am using Windows.

JavaScript: event doesn’t fire on load of window

The code below is supposed to display an hidden text box if option “other” chosen. I don’t want to use jQuery. Could you please help identify the reason why it doesn’t work.

<p class="cart-attribute__field">
  <label>How did you hear about us?</label><br>
  <select required class="required" id="how-did-you-find-us" name="attributes[How did you hear about us?]">
    <option value="Search (Google)"{% if cart.attributes["How Did You Find Us?"] == "Search (Google)" %} selected{% endif %}>Search (Google)</option>
    <option value="Event"{% if cart.attributes["How Did You Find Us?"] == "Event" %} selected{% endif %}>Event</option>
    <option value="Friend / Co-worker"{% if cart.attributes["How Did You Find Us?"] == "Friend / Co-worker" %} selected{% endif %}>Friend / Co-worker</option>
    <option value="Current Customer"{% if cart.attributes["How Did You Find Us?"] == "Current Customer" %} selected{% endif %}>Current Customer</option>
    <option value="Social Media"{% if cart.attributes["How Did You Find Us?"] == "Social Media" %} selected{% endif %}>Social Media</option>
    <option value="Ad"{% if cart.attributes["How Did You Find Us?"] == "Ad" %} selected{% endif %}>Ad</option>
    <option value="News"{% if cart.attributes["How Did You Find Us?"] == "News" %} selected{% endif %}>News</option>
    <option value="Other"{% if cart.attributes["How Did You Find Us?"] == "Other" %} selected{% endif %}>Other</option>
  </select>
</p>
<p id="find-other" class="cart-attribute__field" style="display: none;">
  <label for="how-did-you-find-us-other">Other: </label>
  <input required class="required" id="how-did-you-find-us-other" type="text" name="attributes[How did you hear about us? - Other]" value="{{ cart.attributes["How Did You Find Us - Other"] }}">
</p>

<script>
// Event listener that fires when the Window is loaded
window.addEventListener("load", function() { 
  let howDidYouFindUs = document.getElementById('how-did-you-find-us');
  let findOther = document.getElementById("find-other");
  
  // Change event listener
  howDidYouFindUs.addEventListener("change", function(){
    // Ternary operator to toggle the display
    document.getElementById("find-other").style.display = (howDidYouFindUs.value === "Other") ? "block" : "none";
  });
});  // Get the elements
</script>

Using InnerHTML as php to change div container

Hello dear stack community,
I am frantically trying to change the content of a div container using JavaScript. I have already tried it via InnerHTML. As long as you only use ordinary text, the change is effective. But if I use php, which is mandatory for this, the whole page stays white and nothing happens. Here is the code:

<div class="sidenav lisa-nav" id="mySidenav" onmousemove="openNav()" onmouseout="closeNav()">
            <?php Shortnav::show(); ?>
        </div>





        <div class="lisa-cont" id="LISACont" style="padding-left: 40px">
   

            <script>


                function openNav() {
                    document.getElementById("mySidenav").style.width = "200px";
                    document.getElementById("LISACont").style.paddingLeft = "210px";
                    document.getElementById("mySidenav").innerHTML= "<?php Navigation::show();?>";
                }

                function closeNav() {
                    document.getElementById("mySidenav").style.width = "30px";
                    document.getElementById("LISACont").style.paddingLeft = "40px";
                }


            </script>

The div container with the ID “mySidenav” should be changed from <?php Shortnav::show();?> to <?php Navigation::show();?>.

Does anyone know how to solve this as straightforward as possible?

Thank you very much for your help!

What can I use instead of the JavaScript function constructor to get my parsed function executed in React app

From api I get this HTML:

<div class="my-class" data-src="/event/66478667"></div>
<script>(function(d, s, id) {var js,ijs=d.getElementsByTagName(s)[0];if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://embed.widget.js";ijs.parentNode.insertBefore(js, ijs);}(document, 'script', 'my-js'));</script>

Now I am parsing this HTML through react-html-parser package like:

import parser, { Transform } from 'react-html-parser';

 const transform: Transform = (node: { type: string; children: { data: string }[] }) => {
    if (node.type === 'script' && node.children?.length) {
      // eslint-disable-next-line no-new-func
      Function(node.children[0].data)();
    }
  };

  const options = {
    transform,
  };

  return (
    <div>
      {parser(html, options)}
    </div>
  );

The HTML is containing a <script> with a function. But this <script> tag doesn’t get executed in the React jsx, after parsed and rendered. The only way to get the widget to work, is when I use the JavaScript Function constructor (with an IIFE).

From Eslint I get: The Function constructor is eval.eslintno-new-func.

Is there maybe a better / more safe way to get this function executed in my React app, instead of using the JavaScript Function constructor?

Typescript throwing error: “Spread types may only be created from object types.(2698)”

The code below throws an error when attempting to spread an object after a null check. The error shows subtask as type “never” and then says I can’t use spread because it’s not an object even though I’m clearly checking that subtask exists before spreading it into a new object.

Any idea why this is happening and how I can resolve this error without resorting to removing type safety around the object?

type SubTaskFlow = 'Subtask1' | 'Subtask2'
type Status = 'NotComplete' | 'Complete'
type SubTask = {
  flow: SubTaskFlow
  status: Status
}

type Task = {
  flow: 'Task1' | 'Task2'
  subtasks: Array<SubTask> 
   status: Status
}

type Tasks = Array<Task>

const obj1:Task = {
flow: 'Task1' , 
subtasks: [{flow: 'Subtask1', status: 'NotComplete'}, {flow: 'Subtask1', status: 'NotComplete'}],
status: 'NotComplete'
}
const obj2:Task = {
flow: 'Task2', 
subtasks: [{flow: 'Subtask1', status: 'NotComplete'}, {flow: 'Subtask2', status: 'NotComplete'}],
status: 'NotComplete'
}

const testFunc = (subtaskFlow: SubTaskFlow, status: Status) => {
const tasks = [obj1, obj2]

    let subtask: SubTask | null = null
    let subtaskToUpdateIndex: number = -1
    let taskWithSubtaskToUpdateIndex: number = -1

    tasks.forEach((task, taskIndex) => {
 
        if (task.subtasks && task.subtasks.length) {
          // iterate over the subtasks to check for match
          task.subtasks.forEach((_subtask, subtaskIndex) => {
            if (_subtask.flow === subtaskFlow) {
              subtask = _subtask
              subtaskToUpdateIndex = subtaskIndex
              taskWithSubtaskToUpdateIndex = taskIndex
            }
          })
        }
      })

    

      if(subtask){
        const testsubtask = {...subtask}
      }
}

This TS playground better demonstrates the error:
https://www.typescriptlang.org/play?#code/C4TwDgpgBAygrgIwCoEMDOBrAYgGwPYDuUAvFAOTwLDoYCMZUAPuZdZgExkCwAUKJLGrA4aEuQByeYAGE8AWzA4IwCA2ZlZCpSu59w0SqkxiA3ryhQAZvgIAuWIiPYb5qGiEj7MD2l4BfXl5+aCdTV2tCezIneiZyJ05XNEQ2DDR7AEEAJyyUEAAeQxoAPihXNx8vH39Anlqg-SgnUVJs3IKnYtqAYzwAO3coPAQAK1pbUNIzHgi7eJpYgBoynmSqGnSoAG0TWajWBbJl9xRhTbJJGXlFZVU-Zd2bfZTD48qJKU0bnT8AXUXeCczlFLl9tKoajxegNgENRuwJjQwjMnvMOEcVmtUpsdnsWC9MPQ3qdPB8rlpbmR7lBHpF8et0cTgWSwZS-gDVu8Lp9ruDdAE6lD+oMVO4sHA+t0xAAKLE0XB0oqYBUEJmk7wktAAShIpWm0JFGzEW2GY2WpvYv1qFgs2jcBIwXkcSOYfTgOBwYjdHvKUDtcswSDwAFUwAATU4QACSfTDEAAHvY3XIEBAsmIALS0X121IAdQAlsAABYHQMh8ORmNxxNQZOp9OkLPWm3YgB0ljwWQAoihusXpdLUstUtWEzriHrzL6bVAC5YoEOaG2A2koAAyddQVIrh1oNtKPoAcxLOums4vUAA9Fe5ypciohgA3NPb4vQVeiYB4KD9iDdDArC7KA5FOfsZwvHdPw7Lte37QcAH1V2OB0x3jCcpx4S9L3nRckIdDsbBIYhSFXFUzwg7D7QZQDSHwmjKOw1cg1DCMVDQsRVzQxjL3zItSwdFjK3Y2MEzEUdRPjHibQFKiLD8LVGNki8FJbCw1JtedZQdLVz2wg1YVFYBV1MNszNXZTZwFPwgA

WebSocket connection on wss failed on Load Blanced URL

I do have an web application which runs on two servers (server A and server B) and is load balanced with a single URL.

When I run the load balanced URL on each transaction I am getting the following error om the Chrome Console.

main.d3d29f92e65e59df5742.js:1 WebSocket connection to 'wss://(URL)/websocket' failed: 
E8Ah.e.exports @ main.d3d29f92e65e59df5742.js:1
l @ main.d3d29f92e65e59df5742.js:1
SGzc.w._connect @ main.d3d29f92e65e59df5742.js:1
SGzc.w._receiveInfo @ main.d3d29f92e65e59df5742.js:1
r @ main.d3d29f92e65e59df5742.js:1
s.emit @ main.d3d29f92e65e59df5742.js:1
(anonymous) @ main.d3d29f92e65e59df5742.js:1
r @ main.d3d29f92e65e59df5742.js:1
s.emit @ main.d3d29f92e65e59df5742.js:1
(anonymous) @ main.d3d29f92e65e59df5742.js:1
r @ main.d3d29f92e65e59df5742.js:1
s.emit @ main.d3d29f92e65e59df5742.js:1
xhr.onreadystatechange @ main.d3d29f92e65e59df5742.js:1
T @ polyfills.0a2cb5bcbd9228a348ac.js:1
invokeTask @ polyfills.0a2cb5bcbd9228a348ac.js:1
onInvokeTask @ main.d3d29f92e65e59df5742.js:1
invokeTask @ polyfills.0a2cb5bcbd9228a348ac.js:1
runTask @ polyfills.0a2cb5bcbd9228a348ac.js:1
invokeTask @ polyfills.0a2cb5bcbd9228a348ac.js:1
p @ polyfills.0a2cb5bcbd9228a348ac.js:1
f @ polyfills.0a2cb5bcbd9228a348ac.js:1

This error only appears when I use the load balanced URL. If I use the URL for the individual server this is not present.

Both servers are using https protocol on Tomcat 9 and also use ActiveMQ for integration. I have not done any additional Tomcat configurations for the load balance.

Could you please advise on possible causes

Checked if the certificates are valid
Added wss protocol in the ActiveMQ settings
Checked the answers from the other topics but I am not getting a handshake error

iOS position: fixed glitches

I’m facing a glitch in iOS where position: fixed elements display behind other elements.

enter image description here

css:

.__header {
    position: fixed;
    top: 0;
    background: #000;
    height: 40px;
    width: 100%;
    z-index: 100;
    display: flex;
    justify-content: center;
    align-items: center;
}

    .footer__menu {
        width: 100vw; 
        height: 70px; 
        position: fixed; 
        top: 0;
        z-index: 199;
        background: #000000;
    }

Everything works great in android and chrome.