Advantage of using @Output instead of using @Input which accepts a function in Angular

What is the advantage of using @Output property = new EventEmitter(); decorator with the event emitter instance when the same functionality can be achieved with @Input property: () => void

and then can pass the method from the parent class,

<selector [property]="parentMethod()">

Also, while doing output binding when @Output decorator is used,

<selector (property)="parentMethod()">

Does it internally subscribe to property event emitter instance? This only seems to be beneficial when Angular is using the same instance of a component class at multiple places (does this happen? ), couldn’t think of any other reason.

Would like to understand the work which Angular is doing behind the scene and which of the above-mentioned approach is better and why?

Better understanding ‘d’ in d3.js with an example

I’m following this example in d3.js for how to make a small-multiple choropleth map:

https://gist.github.com/armollica/6314f45890bcaaa45c808b5d2b0c602f

There’s this wrapper function:

function ready(error, us, manufacturing) {}

And within it, there is:

function render(d) {
    var data = d.values;  //this is the manufacturing data 
    
    var context = d3.select(this).node().getContext("2d");
    
    var color = function(d) {
      console.log(d) //this is the 'US' geography json data
      if (data.has(d.id)) {
        var value = data.get(d.id).pct_change_emp;
        return value ? colorScale(value) : "#fff";
      }
      return "#fff";
    };

    // Want the maps to render sequentially. Use setTimeout to give the
    // browser a break in between drawing each map.
    window.setTimeout(function() {      
      drawMap(context, color);
    }, 500);
  }

I don’t understand how the render function is accessing two different datasets using the same d variable. Console-logging data is the manufacturing data, but console-logging d below the var color declaration is the US geo-json data.

I don’t see how d is returning different datasets here, and where that specification is happening in the code. Everything works functionally, I’m just not understanding it. m

Thanks!

Why is javascript not making the value more than 1 using the +1

I can not make the output number bigger than one when I click a button I a using the +1 operator.
I have search everywhere but just can not find a easy and good solution.

echo <<<_END
    
<p>You have </p><a href="#" id="more" class="list-group-item disabled">0 </a>
<script>
function more(){
           document.getElementById("more").innerHTML = +1;//plus one
        }
</script>
_END;
    echo <<<_END
        <img src="coin.png" width="2%" alt="coins">
    _END;
    echo <<<_END
    <button onClick="more()">More!</button>//the button
    
    _END;
    
    ?>

What is the correct way to pass a function as a Prop in React

There are a few questions with similar wording but none that helps me.

I have a parent component, that wants to pass a function to a child component through Props, and the child component will execute the function within its logic. However, ESLint is returning me the error “JSX props should not use functions react/jsx-no-bind“. I understand that this is inefficient because the function will be re-created everytime the component re-renders. What would be the correct way to do this?

Parent Component

function App() {
  const [recipes, setRecipes] = useState(sampleRecipes);

  function handleRecipeAdd() {
    const newRecipe = // some logic to create newRecipe here
    setRecipes([...recipes, newRecipe]);
    
  }

  return <RecipeList recipes={recipes} handleRecipeAdd={handleRecipeAdd} />;
}

Child Component

interface Props {
  handleRecipeAdd: () => void;
}

export default function RecipeList(props: Props) {
  const { handleRecipeAdd } = props;
  return (
        <button onClick={handleRecipeAdd}>
          Add Recipe
        </button>
  );
}

Note that this is not the exact code for both components, it has been simplified to remove irrelevant code.

Adding an tag to a list with jQuery

I am trying to add an <a> tag to a list of li with the help of jQuery.

The html looks like this:

<div class="level one">
      <ul class="kitchen-tools">
      <li class="my list"></li>
      <li class="my list"></li>
      <li class="my list"></li>
      </ul>
    </div>

I created an empty <a> tag with jQuery. Unfortunately I can’t find a way to add this <a> tag to all my <li> (I tried the jQuery append method).

 let aTag = $("a");
     $(".my list").append(aTag);

I am new to coding, so I am sure I am doing a silly mistake here. Thanks in advance.

react native is not see my virtual device

I am a new software developer and this is my first question 🙂

My system

  • windows 10 home – 19042
  • AMD ryzen 5 4600H
  • react-native – 0.66.4
  • react-native-cli – 2.0.1

I have an android studio and emulator and the emulator is running. I created a react native project and run it.

ERROR: Failed to launch emulator

But the emulator is running, and added environment variables .

this error image

this i am using codes
emulator -avd p2 // p2 is my android device (virtual)
npx react-native init proje_101
cd proje_101
npx react-native run-android

and I’m genymotion use trying but same result.

I need some help.

Declaration or statement expected.ts(1128)

im trying to sort out a get function for my api and i have run into this error@ Declaration or statement expected.ts(1128) its in the second else statement.

I have edited the code and taken an oid validation out of it it might be due to this im not too sure.
I’ll have both of the codes before and after the editing in the question.

I edited the function because im trying to get the get request to work without having to have the user to input the oid(object id).

Before:

async function getComments(req) {
   let status = 500, data = null;
   try {
      const oid = req.query.oid;
      if (oid
         && oid.length > 0 && oid.length <= 32
         && oid.match(/^[a-z0-9]+$/i)) {

         const sql = 'SELECT * FROM products';
         const rows = await db.query(sql, [oid]);

         if (rows) {
            status = 200;
            data = {
               'oid': oid,
               'productName': rows,
               'productCondition': rows,  
               'productDescription': rows,
               'productLocation': rows,

            };
         } else {
            status = 204;
         }
      } else {
         status = 400;
      }
   } catch (e) {
      console.error(e);
   }
   return { status, data };
}

After:

async function getComments(req) {
   let status = 500, data = null;
   try {

         const sql = 'SELECT * FROM products';
         const rows = await db.query(sql, [oid]);

         if (rows) {
            status = 200;
            data = {
               'oid': oid,
               'productName': rows,
               'productCondition': rows,  
               'productDescription': rows,
               'productLocation': rows,

            };
         } else {
            status = 204;
         } else {
         status = 400;
      }
   } catch (e) {
      console.error(e);
   }
   return { status, data };
}

need to feel whole progress bar after 30 seconds and keep it in loop for 30 sec

import { Observer } from "mobx-react";
import React, { useRef, useState, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  TouchableWithoutFeedback,
  FlatList,
  Clipboard,
  Animated,
  Platform,
  Dimensions,
} from "react-native";
import FastImage from "react-native-fast-image";
import AppStore from "../../stores/AppStore";
import Scanstore from "../../stores/Scanstore";
import Iconpack from "../../utils/Iconpack";
import Theme from "../../utils/Theme";
import { Screen } from "../CommonComponent/Screen";
import Toast from "react-native-simple-toast";
import { HeaderOtp } from "../CommonComponent/Header";

const hRem = AppStore.screenHeight / 812;
const wRem = AppStore.screenWidth / 375;

const totp = require("totp-generator");

function useInterval(callback, delay) {
  const savedCallback = useRef();
  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

const OtpScreen = ({ route, params, navigation }) => {
  let animation = useRef(new Animated.Value(0));
  const [progress, setProgress] = useState(0);

  useInterval(() => {
    const d = new Date();
    let sec = d.getSeconds();
    // if (elapsedTime % 30 == 0) {
    //   return maxTimeInSeconds;

    setProgress(sec > 30 ? sec - 30 : sec);
    console.log(".........", sec);
  }, 1000);

  useEffect(() => {
    Animated.timing(animation.current, {
      toValue: progress,
      duration: 1000,
      useNativeDriver: false,
    }).start();
    console.log("---->", Scanstore.rData);
    if (Scanstore.loop) {
      Scanstore.fetchSecretKeyArray();
      Scanstore.checkLoop(false);
    }
  }, [progress]);

  const showToast = () => {
    // ToastAndroid.show("Pin Copied Successfully", ToastAndroid.SHORT);
    Toast.show("Pin Copied Successfully.", Toast.LONG);
  };

  const width = animation.current.interpolate({
    inputRange: [0, 30],
    outputRange: ["0%", "100%"],
    extrapolate: "clamp",
  });
  const copyToClipboard = (title) => {
    Clipboard.setString(totp(title));
    showToast();
  };

  const [copiedText, setCopiedText] = useState("");
  const renderFlatlist = ({ item }) => {
    return (
      <TouchableOpacity
        onPress={() => {
          navigation.navigate("OtpDetails", {
            title: item.title,
            // id: item.id,
            otpFrom: item.otpFrom,
          });
        }}
      >
        <View style={Platform.OS === "ios" ? styles.items : styles.items2}>
          <Animated.View
            style={[
              [StyleSheet.absoluteFill],
              {
                backgroundColor: Theme.selectedColor,
                borderTopLeftRadius: 15,
                borderBottomLeftRadius: 15,
                width,
              },
            ]}
          />
          <Text style={styles.itemsContainer}>{totp(item.title)}</Text>
          <Text style={styles.itemsLogin}>{item.otpFrom}</Text>
          <TouchableWithoutFeedback
            onPress={() => {
              copyToClipboard(item.title);
            }}
          >
            <Image source={Iconpack.OTP_COPY} style={styles.copyIcon} />
          </TouchableWithoutFeedback>
        </View>
      </TouchableOpacity>
    );
  };
  const renderBottomSection = () => {
    return (
      <TouchableOpacity
        onPress={(item) => {
          AppStore.checkUserExist();
          navigation.navigate("MainAdd", {
            myTitle: item.title,
            // id: item.id,
          });
        }}
        style={styles.bottomButton}
      >
        <Image style={styles.plusButton} source={Iconpack.PLUS_ICON} />
      </TouchableOpacity>
    );
  };

  const rightSection = () => {
    return (
      <View style={styles.settingStyle}>
        <TouchableOpacity
          onPress={() => {
            navigation.navigate("Settings");
          }}
        >
          <Image source={Iconpack.OTP_SETTINGS} style={styles.settingIcon} />
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <Observer>
      {() => (
        <>
          {/* <Screen
            style={styles.mod1}
            statusBar={"light-content"}
            variant={true}
            showMenu={false}
            onNavigate={navigation}
          > */}
          <FastImage
            style={styles.container}
            source={Iconpack.OTP_BG}
            resizeMode={FastImage.resizeMode.cover}
          />

          {/* <UniversalNavigationHeader
              hideBack={true}
              title={"OTP’s"}
              goBack={navigation.goBack}
              rightView={rightSection}
              showRightView={true}
            /> */}
          <HeaderOtp
            headerText="OTP's"
            onPress={() => {
              navigation.navigate("Settings");
            }}
          />

          <View style={styles.mod1}>
            <FlatList
              data={Scanstore.rData}
              // keyExtractor={(item) => item.id}
              extraData={Scanstore.rData}
              renderItem={renderFlatlist}
              contentContainerStyle={styles.mod3}
            />
          </View>
          <View>{renderBottomSection()}</View>
          {/* </Screen> */}
        </>
      )}
    </Observer>
  );
};

export default OtpScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: "absolute",
    top: 0,
    right: 0,
    left: 0,
    bottom: 0,
    backgroundColor: "#021831",
  },
  settingStyle: {
    marginRight: Dimensions.get("screen").width - 360,
  },
  mod0: {},
  mod1: { flex: 1 },
  headerStyle: {
    flexDirection: "row",
    marginTop: hRem * 56,
    marginHorizontal: wRem * 26.66,
    justifyContent: "space-between",
  },
  mod3: { paddingBottom: 50 },
  otpText: {
    marginLeft: wRem * 136.85,
    ...Theme.encodeSansMed2,
    // lineHeight: hRem * 16,
    color: "#FFFFFF",
    fontWeight: "600",
    marginBottom: hRem * 16,
  },
  settingIcon: {
    width: wRem * 26,
    height: hRem * 26,
  },
  items: {
    backgroundColor: "black",
    marginHorizontal: wRem * 24,
    marginTop: hRem * 16,
    height: hRem * 97,
    flex: 1,
    borderRadius: 15,
    shadowColor: "rgba(27, 100, 206, 0.25)",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 5,
    shadowRadius: 5,
  },
  items2: {
    backgroundColor: "black",
    marginHorizontal: wRem * 24,
    marginTop: hRem * 16,
    height: hRem * 97,
    flex: 1,
    borderRadius: 15,
    shadowColor: "#1b64ce",
    shadowOffset: {
      width: 0,
      height: 3,
    },
    shadowOpacity: 0.36,
    shadowRadius: 6.68,

    elevation: 10,
  },
  itemsContainer: {
    color: "white",
    marginTop: hRem * 28,
    marginLeft: wRem * 29,
    ...Theme.encodeSansMed4,
    // lineHeight: hRem * 16,
  },
  itemsLogin: {
    color: "#898989",
    ...Theme.encodeSansMed5,
    marginLeft: wRem * 29,
    lineHeight: hRem * 19,
  },
  copyIcon: {
    width: wRem * 30,
    height: hRem * 30,
    resizeMode: "contain",
    position: "absolute",
    right: 0,
    // margin: 40,
    marginHorizontal: 24,
    marginTop: 27,
    zIndex: 999,
  },
  bottomButton: {
    justifyContent: "center",
    alignItems: "center",
    position: "absolute",
    bottom: 50,
    width: "100%",
    marginLeft: Theme.devicePixelRatio ? wRem * 150 : wRem * 150,
    borderRadius:
      Math.round(
        Dimensions.get("window").width + Dimensions.get("window").height
      ) / 2,
    width: Dimensions.get("window").width * 0.21,
    height: Dimensions.get("window").width * 0.21,
    backgroundColor: "black",
    shadowColor: "rgba(27, 100, 206, 0.8)",
    shadowOffset: {
      width: 0,
      height: 0,
    },
    shadowOpacity: 10,
    shadowRadius: 15,

    elevation: 10,
  },
  plusButton: {
    position: "absolute",
    textAlign: "center",
    width: wRem * 26,
    height: hRem * 26,
  },
})

here I have pasted the whole code here, ** the problem currently I am facing is, my progress bar feel up after 30 sec but after 30 sec it comes back and it starts at 31sec position, when it reaches 60 sec it does not completely touch the end and it came back and it starting from 0 seconds. I have a little bit of confusion I am just using 30 seconds but it iterating in 60 seconds *

the thing is the progress bar when at 30 seconds position it touches to the end but at 60 it not touches to the end some space like gap it’s leaving after 60 seconds, need to feel whole progress bar after 30 seconds and keep it in the loop for 30-sec pls helped me out, thanks in advance.

i am using new Date() method and getSeconds() method for getting device time

how to use usestate with node.js backend and react frontend

i use node.js in my HTML file using tag now how do i use useState with it
I tried:

const {useState} = React

Here is my code

const {useState} = React;
function App(){
const {text, setText} = useState("Hello world")
console.log(text);
function handleClick(){
  setText("Hello universe")
}

return <h1 onClick={handleClick}> {text} </h1>
}

ReactDOM.render(<App />, document.getElementById('root'))

Is there a way to return all successful promises from fetch until one fails?

The Javascript function Promise.allSettled waits for all resolved or rejected promises to finish. Promise.all won’t return the resolved promises if any of them are rejected, and Promise.race and Promise.any only give the first settled or fufilled promise.

Is there a way to send off multiple promises (say 100), and then as soon as one fails (perhaps have 20 succeed) cancel the unsettled promises (of which there are 100 – 20 – 1 = 79 not yet settled)? I don’t even need the details of which failed, but just a sort of Promise.someSettled function.

Is that possible?

How do I insert data from a table to a form

I have a form which I want to be auto-completed with data from a table I made. How can I achieve this?
This is my table:

    while($row  = mysqli_fetch_assoc($result))
    {
        echo "<tr>";
        echo "<td>" . $row['ID_Angajati'] . "</td>";
        echo "<td>" . $row['Nume'] . "</td>";
        echo "<td>" . $row['Prenume'] . "</td>";
        echo "<td>" . $row['CNP'] . "</td>";
        echo "<td>" . $row['Data_Nasterii'] . "</td>";
        echo "<td>" . $row['Sex'] . "</td>";
        echo "<td>" . $row['Numar_Telefon'] . "</td>";
        echo "<td>" . $row['Salariu'] . "</td>";
        echo "<td class = container_update ><button type = 'button' onclick = 'yes_js_modal();'>Update</a></td>";
        echo "<td class = container_delete ><a href = 'includes/delete.php?id=$row[ID_Angajati]'>&times;</a></td>";
        echo "</tr>";
    }
    echo "</table>";

And this is my form:

<form action="" method="POST">
<table align="center">

<tr>
<td>ID_Angajati:</td>
<td><input type = "text" name="ids" required></td>
</tr>

<tr>
<td>Nume:</td>
<td><input type = "text" name="nume" required></td>
</tr>

<tr>
<td>Prenume:</td>
<td><input type = "text" name="prenume" required></td>
</tr>

<tr>
<td>CNP:</td>
<td><input type = "text" name="cnp" required></td>
</tr>

<tr>
<td>Data Nasterii:</td>
<td><input type = "text" name="data" required></td>
</tr>

<tr>
<td>Sex:</td>
<td><input type = "text" name="sex" required></td>
</tr>

<tr>
<td>Numar Telefon:</td>
<td><input type = "text" name="nr_telf" required></td>
</tr>

<tr>
<td>Salariu:</td>
<td><input type = "text" name="sal" required></td>
</tr>

<tr>
<td colspan = "2" align = "center">
<input type="submit" id="button" name="submit" value="Update Details"></a>
</td>
</tr>

</table>
</form>

I want for instance ID_Angajati from my form to be auto-completed in the form with the value of one of my rows in the table. This will happen when I click on the “Update” button from the table.