The function runs once, the loop inside it runs 2 times?

I simplified the code to explain the problem. When I click the button in my program 3-4 times and the last time I click it, messageStatus = true, the loop runs 3-4 times.

ipcMain.on('sendMessageMail', async (err, data) => {
    if (messageStatus) {
        console.log('Stop');
        messageStatus = false;
        return;
    }

    if (!messageStatus) {
        console.log('Start');
        messageStatus = true;
    }

    for (let i = 0; messageStatus && i < 100; i++) {
        console.log(i);
        await sleep(1000);
    }
})

Console Output

What is the problem? Why is the loop running 3-4 times while the event is running once?

Can’t perform a React state update on an unmounted component. in MapViewDirections

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in MapViewDirections

import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import MapView, {Marker} from 'react-native-maps'
import tw from 'twrnc';
import { useSelector } from 'react-redux';
import { selectDestination, selectOrigin } from '../../navSlice/navSlice';
import MapViewDirections from 'react-native-maps-directions';
import {GOOGLE_MAPS_APIKEY} from "@env";


const Map = () => {
  const origin = useSelector(selectOrigin);
  const destination = useSelector(selectDestination);
  return (
    <MapView 
    style={tw`flex-1`}
    mapType= {'standard'}
    initialRegion={{ 

      latitude: origin.location.lat,
      longitude: origin.location.lng,
      latitudeDelta: 0.005,
      longitudeDelta: 0.005,
    }}
  > 
  {origin && destination && (
    <MapViewDirections
      origin={origin.description}
      destination={destination.description}
      apikey={GOOGLE_MAPS_APIKEY}
      strokeWidth={3}
      strokeColor="black"
    />

  )}

  {origin?.location && (
    <Marker    
      coordinate = {{
        latitude: origin.location.lat,
        longitude: origin.location.lng,

      }}
      title= "Origin"
      description={origin.description}
      identifier="origin"
    />
  )}
  
  </MapView>
  )
}


export default Map

// const styles = StyleSheet.create({})

Run https://github.com/akella/webgl-mouseover-effects code locally

I want to implement image hover effect like on this website https://miew.pt/, and the closest example I got or came across can be found here https://github.com/akella/webgl-mouseover-effects

  1. I have downloaded and extracted the files but when I run/open e.g step3.html, I am getting errors.

  2. I have run yarn add but still getting same error as in point 1.

The error in point 1 & 2 is “Uncaught SyntaxError: Cannot use import statement outside a module”

What’s the correct way to set up the code locally(Win 10)?

Why prepend does trigger once in a loop?

I’m not very good at Javascript, I am trying to make an auto collapsing on overflow menu using Vanilla Js.
I’m happy with what I’ve managed to do so far. But I have a problem with “`appendChild“` / “`prepend“`, they are triggered only once in my loop. When I refresh the page every overflowed link has gone under the more menu, but As I resize (decrease) the window,overflowed links still goes under the more menu, but the more menu itself isn’t updating.

function collapseMenu() {
let menu = document.querySelector(".menu");
let menuChildren = menu.querySelectorAll('li');
let i = menuChildren.length - 1;

let other = document.createElement("li");
other.setAttribute("onclick", "submenu(this)");
other.id = 'other';
other.innerHTML = 'More';

let submenu = document.createElement("ul");
submenu.classList.add('submenu', 'hidden');
other.appendChild(submenu);

if (menu.offsetWidth >= window.innerWidth) {
    let drop;
    if (!menu.contains(document.getElementById('other'))) {
        menu.appendChild(other);
    }
    while (menu.offsetWidth >= window.innerWidth) {
        drop = menu.removeChild(menuChildren[i]);
        submenu.appendChild(drop);
        i--;
    }

} else {
    //On increase window
}

}

collapseMenu();
window.addEventListener('resize', collapseMenu);

Please help, thanks

Object showing empty but has values? Undefined when mapping

I have an object that I’m filling with some information, when logging the object it shows empty but when opening the object up in chrome, it shows that correct details are filled present.

This is what the logs look like

closed: closed obj

open:
opened obj

When mapping the object I get the following error Cannot read properties of undefined (reading 'map')

Am I doing something wrong?

here is my code:

function Admin() {
  const [loading, setLoading] = useState<boolean>(false);
  const [webAppTypes, setWebAppTypes] = useState<IWebAppType[]>([]);

  var nm: { [key: number]: Array<IWebApp> } = {};

  useEffect(() => {
    setLoading(true);
    fetch(`${process.env.REACT_APP_API_URL}/webapptype/read_all`, {
      headers: headers,
    })
      .then((data) => {
        setLoading(false);
        return data.json();
      })
      .then((res) => {
        setWebAppTypes(res);
      });
  }, []);

  useEffect(() => {
    webAppTypes.map((a) => {
      fetch(`${process.env.REACT_APP_API_URL}/webapp/read_all/${a.id}`, {
        headers: headers,
      })
        .then((data) => {
          return data.json();
        })
        .then((data) => {
          let arr: Array<IWebApp> = [];
          data.map((a: any) => {
            const model: IWebApp = {
              id: a.id,
              name: a.name,
              description: a.description,
              link: a.link,
              image: a.image,
            };
            arr.push(model);
          });
          nm[a.id] = arr;
        });
    });
    console.log(nm);
  }, [webAppTypes]);

  if (loading) return <h6>Loading...</h6>;

  return (
    <div style={{ padding: 100, paddingLeft: 200, width: 500 }}>
      {webAppTypes.map((a) => {
        return (
          <Accordion key={a.id}>
            <AccordionSummary
              expandIcon={<ExpandMoreIcon />}
              aria-controls="panel1a-content"
              id="panel1a-header"
            >
              <Typography>{a.name}</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <>
                {nm[a.id].map((t) => {
                  return <Typography>{t.id}</Typography>;
                })}
              </>
            </AccordionDetails>
          </Accordion>
        );
      })}
    </div>
  );
}

Any help would be appreciated.

Custom schema for crm as per user. Any idea how to do it?

I am creating one CRM with customize fields. Can anyone give me an idea how to store that in data base?

Example:
I am using a retail Crm , there I am creating a custom model type like Customer, Inside shop I would like to add fields like name, address, mobile etc.

Then user can add records to that customer model. [Remember this customer model can be any thing custom made by user not predefined mongoose schema]

Can any one help me how to solve this.
Using: Nodejs, express, mongoose,

While using strict mode in javascript, will it not execute lines ahead of the code where it finds error?

I am using strict mode in javascript and then called a function but before that function I used the keyword interface. And when I remove that code of line then my function abc() gets called but if I use that line it does not.
Why is it so?

'use strict';
const interface = 'xyz';
console.log(inteface);

function abc()
{
    console.log('executed!')
    console.log(this);
}
abc();

Pass props to a TabNavigator

Hello I try to pass the name of the city from a component to a TabNavigator to use it in all the screens of the TabNavigator.
App:

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { MaterialCommunityIcons, MaterialIcons, FontAwesome, Entypo, FontAwesome5, Ionicons, AntDesign  } from '@expo/vector-icons';

import Home from './components/home';

import Localisation from './components/OAD/localisation';
import Exploitation from './components/OAD/monExploit';
import RisquesRDT from './components/OAD/risquesRDT';
import RisquesPRIX from './components/OAD/risquesPRIX';
import Resistance from './components/OAD/resistance';
import Optimisation from './components/OAD/optimisation';

import Sol from './components/SiteWeb/solutions';
import Abo from './components/SiteWeb/abonnements';
import About from './components/SiteWeb/QuiSommesNous';
import Join from './components/SiteWeb/nousRejoindre';
import Contact from './components/SiteWeb/nousContacter';

const Tab = createBottomTabNavigator();

function SiteTabs( { navigation } ) {
 return (
    <Tab.Navigator  initialRouteName="Solutions"
    screenOptions={({
          tabBarActiveTintColor: '#8197F8',
          tabBarInactiveTintColor: 'gray',
          
          headerRight: () => (
              <Entypo name="home" size={20} color="#8197F8" onPress={() => navigation.navigate('Home')} style={styles.HOME} />
          ),
          headerTitleAlign: "center",
          headerStyle : {backgroundColor:'#E2ECF1'},
          tabBarStyle: {  backgroundColor:'#E2ECF1'},
        })}>
      <Tab.Screen  
        name="Solutions" 
        component={Sol}
        options={{
          tabBarLabel: 'Solutions',
          tabBarIcon: ({ color, size }) => (
            <AntDesign name="check"  color={color} size={size} />
          ),
        }}/>

      <Tab.Screen   
      name="Abonnements" 
      component={Abo} 
      options={{
          tabBarLabel: 'Abonnements',
          tabBarIcon: ({ color, size }) => (
            <AntDesign name="solution1" color={color} size={size} />
          ),
        }}/>
      
      <Tab.Screen   
      name="Qui sommes-nous ?" 
      component={About} 
      options={{
          tabBarLabel: "A propos",
          tabBarIcon: ({ color, size }) => (
            <AntDesign name="questioncircleo" size={size} color={color} />
          ),
        }}/>
        
      <Tab.Screen    
      name="Nous rejoindre" 
      component={Join} 
      options={{
          tabBarLabel: 'Nous rejoindre',
          tabBarIcon: ({ color, size }) => (
            <FontAwesome5 name="handshake" color={color} size={size} />
          ),
        }}/>
      
      <Tab.Screen  
      name="Nous contacter" 
      component={Contact} 
      options={{
          tabBarLabel: 'Contact',
          tabBarIcon: ({ color, size }) => (
            <AntDesign name="phone" color={color} size={size} />
          ),
        }}/>
  </Tab.Navigator>
  );
}

function OADTabs( { navigation } ) {
  return (
    <Tab.Navigator  initialRouteName="Mon exploitation" 
    screenOptions={({
          tabBarActiveTintColor: '#91CF4E',
          tabBarInactiveTintColor: 'gray',
          
          headerRight: () => (
              <Entypo name="home" size={20} color="#91CF4E" onPress={() => navigation.navigate('Home')} style={styles.HOME} />
          ),
          headerTitleAlign: "center",
          headerStyle : {backgroundColor:'#E2ECF1'},
          tabBarStyle: {  backgroundColor:'#E2ECF1'},
        })}>
      <Tab.Screen  
        name="Mon exploitation" 
        component={Exploitation}
        options={{
          tabBarLabel: 'Exploitation',
          tabBarIcon: ({ color, size }) => (
            <MaterialIcons name="agriculture" color={color} size={size} />
          ),
        }}/>

      <Tab.Screen   
      name="Risques rendement" 
      component={RisquesRDT} 
      options={{
          tabBarLabel: 'Risques rdt',
          tabBarIcon: ({ color, size }) => (
            <Ionicons name="thunderstorm" color={color} size={size} />
          ),
        }}/>

      <Tab.Screen    
      name="Risques prix" 
      component={RisquesPRIX} 
      options={{
          tabBarLabel: 'Risques prix',
          tabBarIcon: ({ color, size }) => (
            <FontAwesome name="euro"color={color} size={size} />
          ),
        }}/>
      
      <Tab.Screen   
      name="Résistance" 
      component={Resistance} 
      options={{
          tabBarLabel: 'Résistance',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="arm-flex" size={size} color={color} />
          ),
        }}/>
      
      <Tab.Screen  
      name="Optimisation" 
      component={Optimisation} 
      options={{
          tabBarLabel: 'Optimisation',
          tabBarIcon: ({ color, size }) => (
            <FontAwesome5 name="piggy-bank" color={color} size={size} />
          ),
        }}/>
  </Tab.Navigator>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
      <NavigationContainer>
      <Stack.Navigator screenOptions={{contentStyle:{backgroundColor:'#FFFFFF'}, headerTitleAlign: "center",}} initialRouteName="Home">

        <Stack.Screen 
          name="Home" 
          component={Home}
          options={{headerShown: false}}  />

        <Stack.Screen  
        name="Localisation" 
        component={Localisation} />

        <Stack.Screen  
        name="Ma simulation" 
        component={OADTabs}
        options={{headerShown: false}} />

        <Stack.Screen  
        name="Solutions" 
        component={SiteTabs}
        options={{headerShown: false}} />
        
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

const styles = StyleSheet.create({
  HOME: {
    marginRight: 20,
  }
})

Localisation :

import React, {useState} from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity } from 'react-native';
import RNPickerSelect from 'react-native-picker-select'
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import communes from "../data/communes"


export default function Localisation({ navigation }) {


const [city, setCity]= React.useState('');

  return (
    <View style={styles.plus}>
      <Text> Selectionner la commune de votre choix </Text>
      <RNPickerSelect  
        style={pickerSelectStyles}
        onValueChange={(itemValue, itemIndex) => setCity(itemValue)} 
        placeholder={{label: 'Choisissez une ville', value: null, color: '#9EA0A4',}}

        items={[ 
          {label:"78850 - Thiverval-Grignon", value:"Grignon"},
          {label:"A", value:"PdT oise"},
          {label:"B", value:"Bett Oise"},
          {label:"C", value:"Grand Est"},
          {label:"D", value:"Berry"},
          {label:"E", value:"Charrente"},
          {label:"F", value:"Sud Ouest"},]}/>
      <Text> {city} </Text>
      
      <View style={{alignItems: "center",}}>
        <TouchableOpacity onPress={() => { navigation.navigate('Ma simulation', {ville: city} ) }} style={styles.button} >
          <Text> Valider </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

I tried

  • to passe it in the Tab.Navigator as a screenProps
  • to pass it like a route.params
  • I read the documentation in react navigation to pass params in an other screen and also the docs of the TabNavigation and try their codes but it doens’t work.

But nothing works in the App fiel the const ville is any however its “string” in the localisation fiel.

Someone can help me ?

Firefox appends nodes strangely in while loop

I’m doing a Website with multiple horizontal carousel sliders of 100vw width and a fixed height. Some sliders contain multiple slides, others only one slide.

Markup:

<article id='project1'>
  <ul class='loop'>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
  </ul>
</article>

<article id='project2'>
  <ul class='loop'>
    <li class='slide'>...</li>
  </ul>
</article>

<article id='project3'>
  <ul class='loop'>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
    <li class='slide'>...</li>
  </ul>
</article>

If there are not enough slides to fill the full width slider (i.e. if there is only one slide) I wrote a script to clone the slides using a while loop. To make sure all images are fully loaded before cloning the slides I added the imagesloaded plugin.

Here my JS to clone the slides:

const sliders = document.querySelectorAll('article.project');

sliders.forEach(slideshow => {
  const images = slideshow.querySelectorAll('img');
  imagesLoaded(images, slideshows);

  function slideshows() {
    const slider = slideshow.querySelector('.loop');
    let slides = slider.querySelectorAll('.slide');
    let slidesWidth;
    function getNewSlidesWidth() {
      slidesWidth = 0;
      for (let i = 0; i < slider.children.length; i++) {
        slidesWidth = slidesWidth + slider.children[i].clientWidth;
      }
      return slidesWidth;
    }
    slidesWidth = getNewSlidesWidth();
    const originalSlidesWidth = slidesWidth;

    console.group(slideshow.id)
    console.log('old: ' + slider.children.length + ' Slides. Total width: ' + originalSlidesWidth + 'px');

    function cloneSlides() {
      for (let i=0; i < slides.length; i++) {
        let clonedSlide = slides[i].cloneNode(true);
        clonedSlide.classList.add('clone');
        slider.appendChild(clonedSlide);
        slidesWidth = getNewSlidesWidth();
      };    
    }

    function letsClone() {
      while (slidesWidth <= window.innerWidth + originalSlidesWidth) {
        cloneSlides();
      };
    };

    letsClone();

    console.log('new: ' + slider.children.length + ' Slides. Total width: ' + slidesWidth + 'px');
    console.groupEnd();
  }
});

Everything works fine in Chrome and Safari. Slides getting cloned and repeated, console output as follows:

project1:
  old: 3 Slides. Total width: 846px
  new: 9 Slides. Total width: 2538px
project2:
  old: 1 Slides. Total width: 632px
  new: 3 Slides. Total width: 1896px
project3:
  old: 5 Slides. Total width: 1410px
  new: 10 Slides. Total width: 2820px

But now in Firefox I get this:

project1:
  old: 3 Slides. Total width: 846px
  new: 546 Slides. Total width: 1932px
project2:
  old: 1 Slides. Total width: 632px
  new: 542 Slides. Total width: 1714px
project3:
  old: 5 Slides. Total width: 1410px
  new: 560 Slides. Total width: 2500px

The while loop keeps cloning the slides hundreds of times as if they had no width. Plus the recalculation of the total width of the slider is not accurate. Even if I log slider.scrollWidth after letsClone() I get a total width that is still much too short (on project3 2500px for 560 slides).

I tried to delay the action with a setTimeout() but that helped nothing.
How can I fix this?

socket.remoteAddress is undefined when there is a timeout or an error

I made this promise function which makes a connection to a specific host however I need to have the remoteAddress to be present in the logs when there is a timeout or an error. It seems like this gets deleted from the object. This is my code:

const makeTCPConnection = async (host, portNumber) =>
  new Promise((resolve, reject) => {
    const client = new Socket();
    let remoteAddress;
    let localAddress;
    const timeout = 2;

    client.setTimeout(timeout);

    client.connect(portNumber, host, () => {
      console.log("TCP connection established", {
        host,
        portNumber,
        localAddress,
        remoteAddress
      });
    });

    client.on("connect", () => {
      localAddress = client.localAddress;
      remoteAddress = client.remoteAddress;
      // client.destroy();
      resolve();
    });

    client.on("close", () => {
      client.destroy();
      resolve();
    });

    client.on("drain", () => {
      client.destroy();
      resolve();
    });

    client.on("end", () => {
      client.destroy();
      resolve();
    });

    client.on("timeout", (error) => {
      console.error("TCP client timeout after 1s", {
        error,
        host,
        portNumber,
        localAddress,
        remoteAddress
      });
      // client.destroy();
      reject(error);
    });

    client.on("error", (error) => {
      console.error("TCP client connection error", {
        error,
        host,
        portNumber,
        localAddress,
        remoteAddress
      });
      client.destroy();
      reject(error);
    });
  });

I been testing this with timeout mainly, I tried to remove the client.destroy() on timeout event but then I get like 4 logs before I get the one with remoteAddress on it. The same thing is happening with localAddress.

Anyone have any ideas?

How to increase the height of the bands?

I have created a funnel with the below script.

Highcharts.chart('container', {
    chart: {
        type: 'funnel'
    },
    title: {
        text: 'Sales funnel'
    },
    plotOptions: {
        series: {
            dataLabels: {
                enabled: true,
                format: "Sales Chart:<br>{point.name}<br>Cart: {point.value:,.0f}<br>New Users: {point.unique:,.0f}<br>Total Orders Rate: {point.cr}%",
                softConnector: true,
                inside: true,
            },
            neckHeight: "0%",
                neckWidth: "80%",
                width: '15%',
                reversed: true,
        }
    },
    legend: {
        enabled: false
    },
    series: [{
    name: 'Unique users',
    keys: ["name", "y", "value", "unique", "did", "cr"],
    data: [
      ['Website visits', 1, 659, 541, '1', '1.31'],
      ['Downloads', 1, 392, 288, '38', '0.70'],
      ['Requested price list', 1, 562, 467, '101', '1.13'],
      ['Invoice sent', 1, 338, 282, '97', '0.68' ],
      ['Finalized', 1, 77, 59, '25', '0.14' ]
    ]
  }],
});

jsfiddle: https://jsfiddle.net/kiranuk/xhfbyj64/

The band looks crowded. How can I increase the height of the bands?

enter image description here

Thanks for the help.

Get Current Window Electron

Hi,
I have a electron app, i need to make button that close, minimize, maximize the window. I search so far on internet. My problem is how to get the current window from rendred page. I found the remote.getCurrentWindow() but it’s not working because remote module is deprecated. I need a new solution alternative to get the current open window from rendred page. I need just a idea to do this. Sorry for my bad English