manage callback within for loop

   const result = [];
   for(i=0; i < 5; i++){
       for(j=0; j<3; j++){
           s3Service.getS3Content(key, bucket, (err, res)=>{
               
               if(err){
                   console.log("error occurred !");
                   result.push({msg:`error occurred for ${key}`})

               }
               
               if(res){
                   result.push(res);
               }
               
           })
       }
   }

How to return result when all outer/inner loop iterations are done ?

I know I can easily solve this issue with promise...then or async...await mechanism.
For some reason, I want to resolve it with callback mechanism.

is there any simple way with callback ?

s3Service.js

const getS3Content = (key, bucketName, cb) => {
  S3.getObject({ Bucket: bucketName, Key: key }, (err, result) => {
    if (err) {
      console.log("error occured in getS3Content", err);
      cb(err);
    }

    if (result) {
      cb(null, result);
    }
  })
}

How we can set multiple backgroud images in PDF with the jspdf?

I’m trying to set dynamic background images using the npm jspdf package. it’s working for me all things but I can’t set the dynamic background. I am trying to this way

import { jsPDF } from "jspdf"
const GanetatePdf = async(name="test.pdf",html) => {
    let pdf = new jsPDF('p', 'pt', 'a4');
    let pWidth = pdf.internal.pageSize.width; // 595.28 is the width of a4
    let srcWidth = html.scrollWidth;
    let margin = 10 // narrow margin - 1.27 cm (36);
    let scale = (pWidth - margin * 2) / srcWidth;

    pdf.html(html, {
        x: margin,
        y: margin,
        html2canvas: {
            scale: scale,
            allowTaint: true,
            backgroundColor: 'white'
        },
        callback: async function (doc) {
            //window.open(pdf.output('bloburl')); 
            let pageInfo = doc.internal.getCurrentPageInfo();
            let totalPages =  doc.internal.getNumberOfPages();
            if(totalPages > 0 && totalPages > pageInfo.pageNumber){
              for(let p=totalPages;p>pageInfo.pageNumber;p--){
                doc.deletePage(p)
              }
            }      
            doc.save(name);
      
        },
        margin :[20, 0, 20, 0]
    });
  } 


   const html = (<div className='row mb-5 p-3 background-image' 
   style={{ backgroundImage: `url('https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSkxORFDMPY7v_DGrlgBxnFBHtwifP9Uz28Y5-8TcNpdTwILs3E')`, "background-repeat": "repeat-y" }}>
Hello World</div>)
   GanetatePdf(name="myfile.pdf",html);

Using this script I am able to create the pdf with images but the background images are not loaded.

CORS preflight failed when all headers are wildcard (Lambda)

I’m trying use JavaScript, Lambda and SES to generate an email from a contact form. The code works when I test it from the Lambda console, but when I invoke it with HTTP it doesn’t work, even though I have confirmed the data is the same and the appropriate headers are allowed.

Here are the console errors in the browser:

Console errors

Here’s my Lambda function:

import boto3
import json

ses = boto3.client('ses')

def lambda_handler(event, context):

    name = event['name']
    email = event['email']
    phone_number = event['phone_number']
    message = event['message']

    # Construct the email message
    subject = f"New message from {name}"
    body = f"From: {name}nEmail: {email}nPhone: {phone_number}nMessage: {message}"
    sender = '[email protected]'
    recipient = '[email protected]'

    # Send the email using AWS SES
    response = ses.send_email(
        Source=sender,
        Destination={
            'ToAddresses': [
                recipient,
            ]
        },
        Message={
            'Subject': {
                'Data': subject,
                'Charset': 'UTF-8'
            },
            'Body': {
                'Text': {
                    'Data': body,
                    'Charset': 'UTF-8'
                }
            }
        }
    )

    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Headers': '*',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*'
        },
        'body': json.dumps('Email sent successfully!')
    }

Here’s my JavaScript:

const formEl = document.querySelector(".contact_form");

formEl.addEventListener('submit', event => {
    event.preventDefault()

    const formData = new FormData(formEl);

    const data = Object.fromEntries(formData);


    fetch('https://myapigatewayuri/prod/contact-form', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then( response => {
        console.log('Here is the response:')
        console.log(response);
        if (response.status === 200) {
            formEl.reset();
            window.alert("Your message was sent successfully. Thank you for reaching out!")
        } else if (response.status !== 200) {
            window.alert("There was a problem sending your message.")
        }
    })
    
});

Here’s the data that is getting sent in the request:

{
'name': 'test name', 
'phone_number': '12345678', 
'email': '[email protected]', 
'message': 'test message'
}

CloudWatch Logs shows this error:

  "errorMessage": "'name'",
    "errorType": "KeyError",
    "stackTrace": [
        "  File "/var/task/lambda_function.py", line 16, in lambda_handlern    name = event['name']n"
    ]

This error does not occur when testing in the console with the same data.

If I change the variable assignment to use the get() method like this:


   name = event.get('name')
    email = event.get('email')
    phone_number = event.get('phone_number')
    message = event.get('message')

The CORS error goes away and the email generates but all the values are ‘none’.

I would have thought this indicates that the data isn’t making it to the function at all, however when running this version of the function I get the following output in CloudWatch logs:


(e5f7444e-a6a5-4b8f-8f47-8f586a342a4a) Method request body before transformations: {
    "name": "test name",
    "phone_number": "12345678",
    "email": "[email protected]",
    "message": "test message"
}


I can’t figure out what is going on here and I’ve run out of things to do to try and narrow down the problem. Any help appreciated.

What’s wrong with my script.js? trying to use an API to build a simple dashboard [closed]

I’m trying to build an ESG dashboard using an API that looks like this –
html output

Below is my script.js file code – I’m sure it has something to do with the results section, please help me out!

document.getElementById('bruh').onclick = async function fetchData() {
    const options = {
        method: 'GET',
        headers: {
            'X-RapidAPI-Key': 'redacted for confidentiality',
            'X-RapidAPI-Host': 'redacted for confidentiality'
        }
    };
    const tick = document.getElementById("tickr").value;
    var results = 'https://yahoo-finance127.p.rapidapi.com/esg-score/symb?=';
    results=results.concat(tick);
    results=results.concat('&symb=');
    const url=results;
    const res = await fetch(url, options);
    const record = await res.json();
    document.getElementById("environment").innerHTML = record.data.map(item => `<li>${environmentScore.fmt}</li>`).join('');
    document.getElementById("social").innerHTML = record.data.map(item => `<li>${socialScore.fmt}</li>`).join('');
    document.getElementById("governance").innerHTML = record.data.map(item => `<li>${governanceScore.fmt}</li>`).join('');
    

}

How to loop an object inside an object

I am currently trying to extract the names, age and nation of each player inside the object. I used object keys and it was able to get the position name.

Note: This is vanilla Javascript

const arsenal = {
    name: "Arsenal",
    city: "London",
    startingLineup: {
        gk: { name: "Aaron Ramsdale", age: 24, country: "England" },
        lb: { name: "Oleksandr Zinchenko", age: 26, country: "Ukraine" },
        rb: { name: "Ben White", age: 25, country: "England" },
        lcb: { name: "Gabriel Magalhaes", age: 25, country: "Brazil" },
        rcb: { name: "William Saliba", age: 22, country: "France" },
        cdm: { name: "Thomas Partey", age: 29, country: "Ghana" },
        cm: { name: "Granit Xhaka", age: 30, country: "Switzerland" },
        cam: { name: "Martin Odegaard", age: 23, country: "Norway" },
        lw: { name: "Gabriel Martinelli", age: 21, country: "Brazil" },
        rw: { name: "Bukayo Saka", age: 21, country: "England" },
        st: { name: "Gabriel Jesus", age: 26, country: "Brazil" },
    },
};

Object.keys(arsenal.startingLineup).forEach((pos) => {
    const name = arsenal.startingLineup[pos.name];
    console.log(pos, name);
});

But when I try to get the other information it comes out as undefined. How can I get the rest of the player info?

gk undefined
lb undefined
rb undefined
lcb undefined
rcb undefined
cdm undefined
cm undefined
cam undefined
lw undefined
rw undefined
st undefined

I am getting the page invalid at server side for below as

I have used select option control in asp.net and binded data using Ajax get api.Also i am performing the validation using RequiredFieldValidator .When i select option and try to continue button its going to server and getting page is invalid .

                    <asp:RequiredFieldValidator ID="rfvtxtWorkshops" ValidationGroup="vStudentCourses"
                                                ControlToValidate="ddlWorkshopsList" ErrorMessage="Provide Select workshop"
                                                CssClass="form-error" runat="server" Display="Dynamic" SetFocusOnError="true" />

How to fix this issue.

How to get Spotify Followers/Following list

So what I want to do is scrape all the followers and followings of a profile.
e.g:
User Mali is following: x,y,z,t
User Mali is followed by: x,y
Users not following back Mali: z
Users Mali is not following: t

I used to do this with selenium where I would go to a users profile and scrape the names of all followers and following but chrome is auto-uptading and my driver stays outdated.

How to trigger a loading animation when the webpage is loading using javascript

I’m trying to make a loader that appears whenever the webpage itself is loading. So like upon first loading in as well as redirecting and whatever else, I want it to load when my browser is loading.

I currently have it set so that the loader is visible until the page is ready but nothing else will trigger it after that.

<body>
    <div class="loaderContainer_Full">
        <div class="loaderContainer_Partial">
            <div class="loader"></div>
        </div>
    </div>
</body>
<script>
    document.onreadystatechange = function() {
            if (document.readyState !== "complete") {
                document.querySelector(
                  ".loaderContainer_Full").style.visibility = "visible";
            } else {
                document.querySelector(
                  ".loaderContainer_Full").style.display = "none";
                document.querySelector(
                  "body").style.visibility = "visible";
            }
        };
</script>

I’ve done some searching but I couldn’t find anything that loads when the page loads. Is this possible? If so how can I do it? I want to do this using only HTML, JavaScript, css and php as it’s for a school assignment.

Link and upload custom files to web page sources

In order to speed up calculations and reduce the load on the web server, I want to perform calculations on the client side. It is necessary that files with binary data be downloaded from the client and available to the script.

I’ve seen this somewhere before, how can I do this? I try various linking options, nothing appears in my sources, except for HTML, JS, CSS files.

<link rel="preload" href="js/astro/ephe/se13681s.se1" as="fetch"> <link rel='preload' href="js/astro/ephe/seas_18.se1" as="fetch">

I get a Render error when I am trying to render one of the pages of my React Native App

Render Error
[6127,”RCTView”, 1, {“collapsable”:false, “backgroundColor”:4278221567,” height”:6,”transform”:
[“translateX”:-7.105427357601002-15}, {“translateX”.”<>”},{“scaleX”.”<>”}]M is not usable as a native method argument

I tried to run the app but when I click on one of the pages, “Challenges” page, it gives me a Render error
Render Error
[6127,”RCTView”, 1, {“collapsable”:false, “backgroundColor”:4278221567,” height”:6,”transform”:
[“translateX”:-7.105427357601002-15}, {“translateX”.”<>”},{“scaleX”.”<>”}]M is not usable as a native method argument

This is my code

import React, { useState, useEffect, useRef } from "react";
import {
  SafeAreaView,
  StatusBar,
  ScrollView,
  StyleSheet,
  Text,
  View,
  FlatList,
  Pressable,
  Dimensions,
  TouchableOpacity,
  Alert,
} from "react-native";
import * as Progress from "react-native-progress";
import * as firebase from "firebase";
import { useNavigation } from "@react-navigation/native";
import { Pedometer } from "expo-sensors";
import ChallengesItem from "../components/ChallengesItem";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
const windowWidth = Dimensions.get("window").width;
const windowHeight = Dimensions.get("window").height;
const Challenges = () => {
  const windowWidth = Dimensions.get("window").width;
  const windowHeight = Dimensions.get("window").height;

  const [searchPhrase, setSearchPhrase] = useState("");
  const [clicked, setClicked] = useState(false);
  const [masterData, setMasterData] = useState([]);
  const [users, setUsers] = useState([]);
  const challengesRef = firebase.firestore().collection("challenges");

  useEffect(() => {
    challengesRef.onSnapshot((querySnapshot) => {
      const users = [];
      querySnapshot.forEach((doc) => {
        const { heading, text, points } = doc.data();
        users.push({
          id: doc.id,
          heading,
          text,
          points,
        });
      });
      setUsers(users);
    });
  }, []);
  let [stepCount, updateStepCount] = useState([0]);
  const subscribe = () => {
    const subscription = Pedometer.watchStepCount((result) =>
      updateStepCount(result.steps)
    );
    Pedometer.isAvailableAsync().then(
      (result) => {
        setPedometerAvailability(String(result));
      },
      (error) => {
        setPedometerAvailability(error);
      }
    );
  };
  useEffect(() => {
    subscribe();
  }, []);

  const [items, setItems] = useState([
    { text: "Walk a minimum of 15,000 steps today", target: 15000 },
    { text: "Walk at least 5km today", target: 10000 },
    { text: "Burn off 150 calories", target: 150000 },
    { text: "Get at least 10,000 steps", target: 10000 },
  ]);
  const [lastRefreshTime, setLastRefreshTime] = useState(null);
  const [currentItem, setCurrentItem] = useState(null);

  useEffect(() => {
    // Check if more than 24 hours have passed since last refresh
    const now = Date.now();
    if (!lastRefreshTime || now - lastRefreshTime > 24 * 60 * 60 * 1000) {
      // Set the last refresh time
      setLastRefreshTime(now);

      // Set the current item
      const randomIndex = Math.floor(Math.random() * items.length);
      setCurrentItem(items[randomIndex]);
    }
  }, [lastRefreshTime]);

// Get the current day of the year (1 to 365)
// const today = new Date();
// const startOfYear = new Date(today.getFullYear(), 0, 0);
// const diff = today - startOfYear;
// const dayOfYear = Math.floor(diff / 86400000); // milliseconds in a day

// // Use the day of the year as the seed for the random number generator
// Math.seedrandom(dayOfYear);

// // Shuffle the array using the Fisher-Yates algorithm
// for (let i = stringsArray.length - 1; i > 0; i--) {
//   const j = Math.floor(Math.random() * (i + 1));
//   [stringsArray[i], stringsArray[j]] = [stringsArray[j], stringsArray[i]];
// }

  const [challenge, setChallenge] = useState([]);
  const AddAlert = () => {
    Alert.alert(`Are you sure you want to take on this challenge?`, "WOOOOO", [
      {
        text: "YES, BRING IT ON",
        onPress: () => setChallenge(challenge),
        style: "cancel",
      },
      {
        text: "No I want my mommy",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
    ]);
  };
  return (
    <SafeAreaView style={{ backgroundColor: "white", flex: 1 }}>
      <ScrollView style={{ flex: 1 }}>
        <View
          style={{
            flex: 1,
            justifyContent: "center",
            padding: 10,
            marginTop: 5,
            backgroundColor: "white",
          }}
        >
          <Text style={{ fontWeight: "bold", fontSize: 38 }}>Challenges</Text>
          <Text style={{ color: "#C1CAD6" }}>
            Whatever it is don't give up!
          </Text>
        </View>
        <View style={{ padding: 10, marginTop: 5 }}>
          <Text style={{ fontSize: 30, fontWeight: "bold" }}>In Progress</Text>
          {/* <ScrollView horizontal showsHorizontalScrollIndicator={false}> */}
              {/* <View
                style={{
                  backgroundColor: "black",
                  height: 200,
                  borderRadius: 15,
                  width: windowWidth - 50,
                  marginRight: 10,
                  justifyContent: "center",
                  alignItems: "center",
                }}
              >
                <View
                  style={{
                    backgroundColor: "black",
                    height: 200,
                    borderRadius: 15,
                    width: windowWidth - 50,
                    justifyContent: "center",
                    alignItems: "center",
                  }}
                >
                  <>
                    {challenge.map((item) => (
                      <View>
                        <Text
                          style={{
                            color: "white",
                            padding: 5,
                            fontWeight: "bold",
                            fontSize: 30,
                            marginBottom: -30,
                          }}
                        >
                          {item.heading}
                        </Text>
                      </View>
                    ))}
                  </>
                  <Progress.Bar
                    progress={0}
                    width={200}
                    style={{ marginTop: 100 }}
                  />
                </View>
              </View> */}
              <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
              <View
                style={{
                  top: 10,
                  backgroundColor: "black",
                  height: 200,
                  borderRadius: 15,
                  width: windowWidth - 50,
                  justifyContent: "center",
                  alignItems: "center",
                }}
              >
                <Text
                  style={{
                    color: "white",
                    padding: 5,
                    fontWeight: "bold",
                    fontSize: 30,
                    marginBottom: -10,
                  }}
                >
                  Daily Challenge
                </Text>
                <Text
                  style={{
                    color: "white",
                    padding: 5,
                    fontWeight: "bold",
                    fontSize: 15,
                    marginBottom: -30,
                    marginTop: 10,
                  }}
                >
                  {currentItem && <Text>{currentItem.text}</Text>}
                  
                </Text>
                <Progress.Bar
                  progress={stepCount/currentItem?.target}
                  width={200}
                  style={{ marginTop: 100 }}
                />
              </View>
            </View>
          {/* </ScrollView> */}
        </View>
        <View style={{ padding: 10, marginTop: 5 }}>
          <Text style={{ fontSize: 30, fontWeight: "bold" }}>For you</Text>
        </View>
        <View>
          {/*
                backgroundColor: "#FFFF82",
                backgroundColor: "#B5D99C",
           */}
          <FlatList
            style={{ height: "100%" }}
            data={users}
            searchPhrase={searchPhrase}
            setClicked={setClicked}
            numColumns={1}
            renderItem={({ item }) => (
              <Pressable style={[styles.containers]}>
                <TouchableOpacity
                  style={{
                    backgroundColor: "#E9ECF1",
                    flexDirection: "row",
                    marginBottom: 15,
                    borderRadius: 17,
                    marginHorizontal: 20,
                  }}
                  onPress={() => [setChallenge([...challenge, item])]}
                >
                  <View
                    style={{
                      backgroundColor: "#89B3DD",
                      width: 35,
                      height: 35,
                      borderRadius: 10,
                      alignSelf: "center",
                      marginHorizontal: 15,
                    }}
                  ></View>
                  <View
                    style={{
                      justifyContent: "center",
                      alignItems: "center",
                      flex: 1,
                    }}
                  >
                    <View
                      style={[
                        styles.innerContainer,
                        {
                          paddingHorizontal: 10,
                          width: windowWidth - 130,
                          height: 80,
                          borderRadius: 15,
                          marginLeft: 10,
                          justifyContent: "center",
                        },
                      ]}
                    >
                      <Text
                        style={[
                          styles.itemHeading,
                          { padding: 5, color: "#252C45" },
                        ]}
                      >
                        {item.heading}
                      </Text>
                      <Text
                        style={[
                          styles.itemText,
                          { paddingHorizontal: 5, color: "#252C45" },
                        ]}
                      >
                        ✨{item.text}✨
                      </Text>
                    </View>
                  </View>
                  <View
                    style={{
                      justifyContent: "center",
                      alignItems: "center",
                      width: 70,
                    }}
                  >
                    <Text
                      style={{
                        fontSize: 28,
                        marginRight: 10,
                        marginLeft: 10,
                        fontWeight: "800",
                      }}
                    >
                      {item.points}
                    </Text>
                  </View>
                </TouchableOpacity>
              </Pressable>
            )}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};
const Stack = createNativeStackNavigator();
export default function ChallengesStack() {
  return (
    <Stack.Navigator initialRouteName="Challenges">
      <Stack.Screen
        name="Challenges"
        component={Challenges}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="SecondPage"
        component={ChallengesItem}
        options={{ headerShown: true }}
      />
    </Stack.Navigator>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: StatusBar.currentHeight,
    marginHorizontal: 16,
  },
  item: {
    backgroundColor: "white",
    padding: 20,
    marginVertical: 8,
    shadowColor: "black",
    shadowColor: "#171717",
    shadowOffset: { width: -2, height: 4 },
    shadowOpacity: 1,
    shadowRadius: 3,
    width: windowWidth - 19,
    borderRadius: 14,
  },
  header: {
    fontSize: 32,
    backgroundColor: "#fff",
  },
  title: {
    fontSize: 24,
  },
  innerContainer: {
    flexDirection: "column",
    marginBottom: 20,
    justifyContent: "center",
  },
  itemHeading: {
    fontWeight: "bold",
    fontSize: 20,
  },
  itemText: {
    fontWeight: "300",
    fontSize: 16,
  },
  bottomSheet: {
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: -4,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  progressBar: {
    height: 15,
    flexDirection: "row",
    width: "100%",
    backgroundColor: "white",
    borderColor: "#000",
    borderWidth: 2,
    borderRadius: 5,
  },
});

Find the number of occurrences in an array using reduce in javascript

I was trying to find a solution to find out the number of occurrences of a number in an array and came across the below solution:

const occurrences = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
  return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc
}, {});

console.log(occurrences)

The code above works as expected. But I am not able to understand properly how it works. Can someone please simplify and explain the reduce method above? Thanks in advance.

How to change iconfont’s default font size and repackage?

For example, the google icon, the default is 24px, and the text content of my webpage uses 14px, so when I use the google icon, there will be some problems, mainly the line height, for example, when the text of the icon is placed on the button, the height of my button Destroyed, but when I use css to change the google icon to 14px, it is too small, which is not what I want.

I have an idea now, to preset the google font to 14px, but the actual size is the same as 24px, and finally repackage for my webpage, then I can keep the text content and icon at 14px and keep the appearance perfect, Is this possible?

Will there be some automatic generation tools? For example javascript libs or gulp plugin?