Two clicks needed for log in

I have to click log in twice before it chacks the data. Can someone help why?

I’m creating a forum website and on my log-in page the user has to click the button twice before it the code validates and responds to the given data.

here is my handle submit which is triggered on button click.

const [values,setValues] =useState({
        email: '',
        password: ''
    })
    const navigate =useNavigate();
    const [errors, setErrors] = useState({})
    const handleInput = (e) => {
        setValues(prev => ({...prev, [e.target.name]: [e.target.value]}))
    }

const handleSubmit = (e) => {
        e.preventDefault()
        setErrors(Validation(values))
        if(errors.password === "" && errors.email === ""){
            axios.post('http://localhost:8081/login', values)
            .then(res => {
                    if(res.data.errorMessage ==='Success'){
                        navigate('/dashboard');
                    }
                    else{
                        console.log(res.data.errorMessage);
                    }
            })
            .catch(err => console.log(err));
            
        }
        
    };

PS validation returns error messages when spots are not filled properly

I’m new to nodejs and react so if anyone could explain it would be a huge help!

How to set equal aspect ratio and define axis limits in plotly.js

I’m trying to set an equal aspect ratio AND axis limits in plotly js.

Setting the “range” of a plotly js axis is pretty trivial. E.g.

var layout = {
  xaxis: {range: [0, 4]}
};

The code here shows a simple example of setting the aspect ratio of a plot using schaleanchor.

However, using the two together seems to override any range set. It’s possible to bypass some of this by setting width and height, but it’s a bit messy. How can I automatically create an equal aspect ratio plot with defined axis ranges?

How can I implement a more complex promise chain in javascript?

I try to implement a more complex promise chain.
Flow and dependencies:

  • Start A, B and D
  • Start C when A and B are done
  • Start E when C and D are done

Here the simulation code:

function test_p(name, sec) {
    console.log(Date.now()-start,'Started ', name, " Sec: ", sec);
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(Date.now()-start,'Resolved ', name, " Sec: ", sec);
            resolve(10);
        }, sec * 1000);
    });
}
start = Date.now(); 
p1 = test_p("A", 2)
    .then((result) => { console.log(Date.now()-start, result); return result });
p2 = test_p("B", 5)
    .then((result) => { console.log(Date.now()-start,result); return result });
pp1 = Promise.all([p1, p2])
    .then((result) => { console.log(Date.now()-start,"p1-p2 startet"); return result })
    .then(() => { console.log(Date.now()-start,"p1-p2 done ") })
    .then(() => {
        p3 = test_p("C", 5)
            .then((result) => { console.log(Date.now() - start, result); return result })
    });    
p4 = test_p("D", 7)
    .then((result) => { console.log(Date.now()-start,result); return result });
pp2 = Promise.all([pp1, p3, p4])
    .then((result) => { console.log(Date.now()-start,"pp1-p4 startet"); return result });

This is the console protocol:
0 ‘Started ‘ ‘A’ ‘ Sec: ‘ 2
VM10447:2 2 ‘Started ‘ ‘B’ ‘ Sec: ‘ 5
VM10447:2 2 ‘Started ‘ ‘D’ ‘ Sec: ‘ 7
Promise {}
VM10447:5 2001 ‘Resolved ‘ ‘A’ ‘ Sec: ‘ 2
VM10489:3 2001 10
VM10447:5 5003 ‘Resolved ‘ ‘B’ ‘ Sec: ‘ 5
VM10489:5 5003 10
VM10489:7 5003 ‘p1-p2 startet’
VM10489:8 5003 ‘p1-p2 done ‘
VM10447:2 5003 ‘Started ‘ ‘C’ ‘ Sec: ‘ 5
VM10447:5 7002 ‘Resolved ‘ ‘D’ ‘ Sec: ‘ 7
VM10489:14 7003 10
VM10489:16 7003 ‘pp1-p4 startet’
VM10447:5 10004 ‘Resolved ‘ ‘C’ ‘ Sec: ‘ 5
VM10489:11 10004 10

I wanted the second Promise.all to fire after C resolved around 10000 msec

html2canvas works on desktop and iPadOS but not on iOS

I’ve been having this problem for a while now, the user of my website uploads an image and then the image is placed inside a template that has already been placed on the website.

When I try to use html2canvas on desktop, everything works, but when I tried to execute it on my iPhone, it didn’t work and just resulted in an image.jpg.txt file.

Then, I tested it on my iPad just to figure out if the problem is with mobile devices or just iOS, and executing it on my iPad worked and resulted in an image file.

HTML:

    <div id="header">
        <a href="index.html" id="generalLink">General</a>
        <a href="page2.html" id="rehearsalLink">Page2</a>
    </div>
    <input type="file" accept="image/*" onchange="imageUpload(event);" id="imageUpload">Upload Image</input>
    <div class="frameMain">
        <div id="frameContainer">
            <img src="images/generalFrame.png" alt="" class="frameImage">
            <div id="uploadedImage">
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@latest/dist/html2canvas.min.js"></script>
    <script src="index.js"></script>

JavaScript:

function imageUpload(event){
    if(event.target.files.length > 0){
      var src = URL.createObjectURL(event.target.files[0]);
      var preview = document.getElementById("uploadedImage");
      preview.style.backgroundImage = "url(" + src + ")";
    }
    
    let myElement = document.getElementById("frameContainer");
    console.log(myElement)

    html2canvas(myElement).then(canvas => {
      const link = document.createElement('a');
      link.download = 'image.jpg';
      link.href = canvas.toDataURL('image/jpg');
      document.body.appendChild(link);
      link.click();
      }).catch(error => {
      console.error('Error:', error);
      });
}

Chessboard.js in a Firefox addon popup doesnt show

I’m trying to show a chessboard in a Firefox addon popup but i cannot get it to work.
Any help would be much appreciated

manifest.json

{
  "manifest_version": 2,
  "name": "Chessboard Popup",
  "version": "1.0",
  "description": "Displays a chessboard in a popup window.",
  "icons": {
    "48": "icon.png"
  },
  "permissions": ["activeTab","webRequest","storage","<all_urls>"],
  "browser_action": {
    "default_icon": {
      "48": "icon.png"
    },
    "default_popup": "popup.html"
    
  }
}

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>Chessboard Popup</title>
  <link rel="stylesheet"
  href="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.css"
  integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU"
  crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2"
  crossorigin="anonymous"></script>
  <script src="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.js"
  integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD"
  crossorigin="anonymous"></script>

</head>
<body>
    <div id="board1" style="width: 400px"></div>
    <script src="board.js"></script>
  </body>
</html>

board.js


var board1 = ChessBoard('board1', 'start');

No board renders. When I load just the html file the board does render. I’ve tried to store the css and js locally but it makes no difference.

How does the JS engine collaborate with WebCore to update the DOM tree?

enter image description here

I curious about rendering engine (webkit) work internally… And so i get this image above

So mt problem and question is

I confused about web api, that is produced by JS engine and then JS engine will be interpreter that and will be communicate into webcore for updating DOM tree?? Its correct??

I guess DOM tree and render object is located at rendering engine (webcore) and to do manipulate that DOM tree rendering engine provide a api and JS engine also provide api in their languange

Is that my guess is correct??

Thankss

FlatList not shown result in React native

I am new to React native and i am trying to create a simple flatlist and fill it from Api https://dummyjson.com/products but it never show results …
here is my App.tsx code

import React from 'react';
import type {PropsWithChildren} from 'react';
import {
  FlatList,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import ShopList from './ReusableComponents/ShopList';
import axios from 'axios';
import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

type SectionProps = PropsWithChildren<{
  title: string;
}>;


function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const shops: ArrayLike<any> | null | undefined = []




    fetch('https://dummyjson.com/products')
    .then(response => response.json())//hat el jsonresponse law rege3
    .then(result => { shops })

    console.log({shops})

  
  return (
    
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
     
     <ShopList />
      
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
  edges: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 5,
    minWidth: 50
  }
});

export default App;

And here is ShopList code

import React, {Component} from 'react';

import {
  View,
  FlatList,
  Image
} from 'react-native'
import ShopListRow from '/Users/nb29042/Desktop/React/DemoShop/ReusableComponents/ShopListRow';
import { ListItem, Avatar } from 'react-native-elements';

export default class ShopList extends Component {
  constructor(props){
    super(props);
    this.state = {
      shops: []
    }
  }


      fetchItem() {
        requestAnimationFrame(() =>
          fetch(`https://dummyjson.com/products`, {
            method: 'GET',
          })
            .then(response => response.json())
            .then(responseJson => {
              this.setState({shops: responseJson})
              // console.warn(this.state.shops);
            })
            .catch(error => {
              {
                alert(error)
              }
            }),
        );
    }
  
    componentDidMount(){
      this.fetchItem()
    }

    
      render() {
        return (

          <View style={{
            flex: 1,
            backgroundColor: '#FFFFFF'
          }}>
    
            
    
            <FlatList
              data = {
                this.state.shops
              }
              renderItem={({ item, index }) => 
                {
                  return <ShopListRow 
                  shop={item} 
                  index={index} 
              
                />}
                
    
              }
              keyExtractor={item => item.id}
              initialNumToRender={16}
              extraData={this.state}
            />

    
          </View>
        );
      }
}

And the ShopListRow Code is:

import React, {Component} from 'react';

import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  FlatList,
  Image
} from 'react-native'
//import Stars from './Stars';
export default class ShopListRow extends Component {
    render() {

        const {
          shop,
          index
        } = this.props
        
        return (
          <View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? 'white' : '#F3F3F7' }}>
    
            <View style={styles.row}>
              
    
              <View >
                <Text>{shop.title}</Text>
                <Text >{shop.description}</Text>
              </View>
    
              <View style={styles.edges}>
                
                <TouchableHighlight 
                  //onPress={this.infoPressed}
                  style={styles.button}
                  underlayColor='#5398DC'
                >
                  <Text style={styles.buttonText}>Info</Text>
                </TouchableHighlight>
    
    
              </View>
            </View>
    
          </View>
        )
      }
}


const styles = StyleSheet.create({
    row: {
      flexDirection: 'row'
    },
    edges: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 5,
      minWidth: 50
    },
    stars: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'row',
      justifyContent: 'flex-start',
      padding: 5,
      minWidth: 50
    },
    nameAddress: {
      flexDirection: 'column',
      flex: 8,
      padding: 5
    },
    addressText: {
      color: 'grey'
    },
    button: {
      borderWidth: 1,
      borderColor: '#0066CC',
      borderRadius: 14,
      paddingHorizontal: 10,
      paddingVertical: 3,
      backgroundColor: '#fff',
    },
    buttonText: {
      color: '#0066CC',
      fontSize: 12
    },
    info: {
      marginHorizontal: 40,
      marginVertical: 10,
      padding: 10,
      backgroundColor: '#fff',
      borderWidth: 1,
      borderColor: '#ddd',
      borderRadius: 4
    }
  })
  

if anyone can help me why flatlist results not shown any results i will be thankful…
best regards

How does changing ‘v => v != false’ to ‘Boolean’ affect the logic of my JavaScript code for calculating sheep in an array on Codewars?

I’ve been training on CodeWars right now and I have a question on the assignment counting sheep…

Here are two versions of my code tell me the differences between them please:

function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(Boolean).length;  
}

and

function countSheeps(arrayOfSheep) {
  return arrayOfSheep.filter(v => v != false).length;  
}

this is an example of an array from which I had to calculate sheep by the value true:

[
  true,  true,  true,  false,
  true,  true,  true,  true,
  true,  false, true,  false,
  true,  false, false, true,
  true,  true,  true,  true,
  false, false, true,  true
]

I know how to solve this task through a loop, but I wanted to solve it in principle using filter()

I decided to create a new array where there will only be values with true and then calculate them using .length, respectively, I managed to calculate this array, but when my code was checked for other random examples, I had an error in calculations, and when I changed (v => v != false) to (Boolean), everything worked for me, but I didn’t quite understand how the logic of my code has changed

Koffi: convert string to pointer

I am using Koffi https://koffi.dev/ to call Windows native functions from “user32.dll”. I am trying to change windows wallpaper from javascript.

I have this C++ code that calls the necessary SystemParametersInfoW and changes the wallpaper.

const wchar_t* text = L"C:\Users\me\wallpaper.png";
SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (PVOID)text, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);

As you can see, the function requires to send path to image as PVOID (void pointer).

How can I implement converting path string to pointer in Koffi?

Why is function returning undefined?

I am trying to write a function that returns the first odd number in an array.

I have this so far but it is returning undefined.

function findFirstOdd(numbers) {
  let oddNumbers = [];
  for (let i = 0; i <= numbers.length; i++) {
    if (numbers[i] % 2 != 0) {
      oddNumbers.push(numbers[i])
    } else {}
  };
  return oddNumbers[0]
};

console.log(findFirstOdd(6, 2, 9, 3, 4, 5));

I would expect this to return 9; being the first odd number.

chrome.tabs.sendMessage response not received immediately

I aim to scrape chats from chatGPT using a Chrome extension. On the link update, I am sending a message to the content script to read the data. Content-writer responds after reading data using the query selector. In the service-worker I am not receiving the data at that time, but if I click on other chats of that page, that previous data is sent after that.

service-worker sends message onupdate

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    console.log("changed to ", tab.url)
    if (changeInfo.status == "complete") {
        if (tab.url.includes("chat.openai.com/c/")) {
            console.log(changeInfo)
            chrome.tabs.sendMessage(tabId, {
                url: tab.url,
                type: 'URL_CHANGE'
            }, (response) => {
                if (response && response.length > 0)
                    console.log('Chat: ', response)
            });
        }
        else if (tab.url.includes("chat.openai.com")) {
            console.log(changeInfo)
            chrome.tabs.sendMessage(tabId, {
                url: tab.url,
                type: 'HOME'
            }, (response) => {
                if (response && response.length > 0)
                    console.log('Home: ', response)
            });
        }
    }
});

content-script reads the message and send response accordingly

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if(request.type === 'URL_CHANGE'){
        console.log(request);
        chats = document.querySelectorAll(".text-base")
        texts = []
        chats.forEach((chat) => texts.push(chat.innerText))
        sendResponse(texts)
    }
    else if(request.type === 'HOME'){
        console.log("Home");
        chats = document.querySelectorAll(".text-ellipsis")
        texts = []
        chats.forEach((chat) => texts.push(chat.innerText))
        sendResponse(texts)
    }
});

I am getting the correct/expected response but after another ‘link update’ not immediately.

Merkle Tree Implementation in JS with keccak256

Merkle Tree Implementation in JS with keccak256

I coded some Merkle Tree implementations in JavaScript with keccak256. This code takes JSON Objects from the local JSON File that called output.json. It has this type of objects:

{
        "key": "{"address":"0xCA1b1d94C8aDbeD62dB06af2933820098d397D12","type":"index"}",
        "value": "{"index":0}"
}

And my code creates the merkle tree from these key-value pairs, selects one of them randomly, finds its index on the tree, hashes it, and tries to concatenate and hash it with its sibling. However, no matter how hard I try to concatenate and hash the same hashes, I never get the same hashes.

Here is the my JS code:


const fs = require('fs');
const keccak256 = require('keccak256');

const json = JSON.parse(fs.readFileSync('output.json', { encoding: 'utf8' }));
let indexArray = [];

function main() {

    const tree = json.map((item) => {
        return {
            key: item.key.toString(),
            value: item.value.toString(),
        };
    });

    searchObject = tree[Math.floor(Math.random() * tree.length)]
    let current = JSON.stringify(searchObject);

    let iter = 0;

    //creating leafs
    for (let i = 0; i < tree.length; i++) {
        let element = tree[i];
        tree[i] = keccak256(JSON.stringify(element));
        indexArray.push(tree[i]);
    }
    
    
    //logging
    for (let i = 0; i < tree.length; i++) {
        //tree[i] = tree[i].toString('hex');
        console.log(`${iter}. layer'ın ${i}. elemanı: ${tree[i].toString('hex')}`);
    }
    iter++;
    
    
    while (tree.length > 1) {
        //create merkle tree
        for (let i = 0; i < tree.length - 1; i++) {
            
            process.stdout.write(`${tree[i].toString('hex')} and ${tree[i+1].toString('hex')}  concatenated and hashed, and the result is this output:`);
            tree[i] = keccak256(tree[i] + tree[i+1]);
            process.stdout.write(`${tree[i].toString('hex')}n`);
            tree.splice(i+1, 1);
            
        }
        
        //logging
        for (let i = 0; i < tree.length; i++) {
            
            indexArray.push(tree[i]);
            console.log(`${iter}. layer'ın ${i}. elemanı: ${tree[i].toString('hex')}`);
        }
        
        iter++;
    }
    

    console.log(`Merkle root is: ${tree[0].toString('hex')}n`);

    
   
    indexArray.reverse();
    for (let i = 0; i < indexArray.length; i++) {
        console.log(`${ i }. eleman: ${indexArray[i].toString('hex')}`);
    }


    
    console.log(`nnBeginning search...`);
    let dex = null;
    for (let i = 0; i < indexArray.length; i++) {
        if ( keccak256(current).toString('hex') === indexArray[i].toString('hex')) {
            console.log(`n${searchObject.key + searchObject.value} and its hash ${keccak256(current).toString('hex')} is found at ${i}. index`);
            dex = i;
            break;
        }
    }

   
    
    let hash = null;
    if (dex % 2 == 0) {
        hash = keccak256(  indexArray[dex-1] + current );
        console.log(`n`);
        console.log(`${keccak256(current).toString('hex')} and its sibling is at ${dex-1} index which is ${indexArray[dex-1].toString('hex')} hashed together and the result is ${hash.toString('hex')}`);
        dex = Math.floor((dex-1)/2);
    }
    else {
        hash = keccak256( current +  indexArray[dex+1]  );
        console.log(`n`);
        console.log(`${keccak256(current).toString('hex')} and its sibling is at ${dex+1} index which is ${indexArray[dex+1].toString('hex')} hashed together and the result is ${hash.toString('hex')}`);
        dex =  Math.floor((dex-1)/2);
    }

    if (hash === indexArray[dex]) {
        
        console.log(`nProof is valid!`);
    } else {
       
        console.log(`nProof is not valid!`);
    }


}

main(); 


Is there an easier validation libraray for data validation? [closed]

Writing validation has always been a pain for me. There’s an npm package for validation which makes the validation process easier. But I want to know if there is an even better package which can help? Here’s the package which I found:

https://www.npmjs.com/package/super-easy-validator

const Validator = require('super-easy-validator');

// validation rules
let rules = {
  username: 'username|lower|min:8',
  phone: 'optional|phone',
  email: 'optional|email',
  $atleast: 'email|phone',
  password: 'string|min:3|max:20'
};

// request body by client
let requestBody = {
  username: 'john.doe.7',
  email: '[email protected]',
  password: 'johndoe123'
}

let { errors } = Validator.validate(rules, requestBody);
if(errors) {
  console.log(errors);
  return res.status(400).json({
    message: errors[0],
  });
}

how to add dynamic JavaScript to dynamically generated Html elements?

I have a HTML page that gathers data from a database and uses that data to produce dynamic html elements. the problem is that these elements have to create a button that submits data without refreshing the page and then call a function productList(formId);.

this is the current function:

function getWidgets(){
    
    var listUrl = base_url + widgetsPath + url_auth;
    
    console.log("Sending GET to " + listUrl);
    
    function getSuccess(obj){
        var dataWidget = obj.data;

        for (let i=0; i< dataWidget.length; i++){

            var id = dataWidget[i].id;
            var description = dataWidget[i].description;
            var price = dataWidget[i].pence_price;
            var url = dataWidget[i].url;
            var index = i;
            
            
            console.log("index: ",i);
            console.log(dataWidget[i].id);
            console.log(dataWidget[i].description);
            console.log(dataWidget[i].pence_price);
            console.log(dataWidget[i].url);
            console.log(" ");
            console.log("FIX SCRIPT FOR BUTTONS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            console.log(" ");

            var template =`<!-- product -->
            <div class="container" class="product" id="productId_${index}">
                <form action="" class="product">
                    <img src="${url}"></img>
                    <p class="product_Description">${description}</p>
                    <input type="hidden" class="productId" value=${id}>
                    <input type="hidden" class="price" value="0.${price}">
                    <label for="quantity">Quantity:</label>
                    <input type="number" class="quantity" value="1" min="1">
                    <button class="submit">Add to cart</button>
                </form>
            </div>
            <script>
                        document.addEventListener("DOMContentLoaded",() =>{
                            const product${index} = document.querySelector("#productId_${index}")
                            product1.addEventListener("submit",e=>{
                                e.preventDefault();
                                var formId = "productId_${index}";
                                productList(formId);
                            });
                        });
            </script>
            <!-- END product -->`

            $("#widgetContainer").append(template);

        }
        console.log("success");
        console.log(dataWidget);
        alert("FIX SCRIPT FOR BUTTONS");
    };
    
    $.ajax(listUrl, {type: "GET", data: {},success: getSuccess });
};

getWidgets();